在ubuntu上使用vscode容器开发

vscode

在ubuntu上使用vscode容器开发

  • 创建一个非root用户运行docker

    # 官方链接:https://docs.docker.com/engine/install/linux-postinstall/
    (base) hsj@ubuntu:~$ sudo groupadd docker
    [sudo] hsj 的密码: 
    groupadd:“docker”组已存在
    (base) hsj@ubuntu:~$ sudo usermod -aG docker $USER
    # 重启电脑
    # 测试
    (base) hsj@ubuntu:~$ docker run hello-world
    Unable to find image 'hello-world:latest' locally
    latest: Pulling from library/hello-world
    0e03bdcc26d7: Pull complete 
    Digest: sha256:8c5aeeb6a5f3ba4883347d3747a7249f491766ca1caa47e5da5dfcf6b9b717c0
    Status: Downloaded newer image for hello-world:latest
    
    Hello from Docker!
    This message shows that your installation appears to be working correctly.
    
    # 如果报错
    WARNING: Error loading config file: /home/user/.docker/config.json -
    stat /home/user/.docker/config.json: permission denied
    
    # 执行
    sudo chown "$USER":"$USER" /home/"$USER"/.docker -R
    sudo chmod g+rwx "$HOME/.docker" -R
    
  • 在vscode搜索插件remote-containers,安装

  • 下载官方测试列子

    (base) hsj@ubuntu:~/vscodeProject$ git clone https://github.com/microsoft/vscode-remote-try-python.git
    (base) hsj@ubuntu:~/vscodeProject$ cd vscode-remote-try-python/
    (base) hsj@ubuntu:~/vscodeProject/vscode-remote-try-python$ tree -a
    .
    ├── app.py
    ├── .devcontainer
    │   ├── devcontainer.json
    │   └── Dockerfile
    ├── .gitattributes
    ├── .gitignore
    ├── LICENSE
    ├── README.md
    ├── requirements.txt
    ├── static
    │   └── index.html
    └── .vscode
        └── launch.json
    # 文件说明
    # app.py Flask app 入口文件
    # devcontainer.json vscode容器配置文件
    # Dockerfile 容器镜像生成文件
    # .gitattributes,.gitignore,LICENSE,README.md git相关文件
    # requirements.txt python依赖文件
    # index.html flask页面文件
    # launch.json vscode运行调试文件
    
  • 重要文件说明

    • devcontainer.json文件, 官方链接:https://code.visualstudio.com/docs/remote/devcontainerjson-reference

      项目中的devcontainer.json文件告诉Visual Studio Code如何使用定义良好的工具和运行时堆栈访问(或创建)开发容器。该容器可用于运行应用程序或用于使用代码库的沙盒工具,库或运行时。它可以与Remote-Containers扩展或GitHub Codespaces一起使用

      Property Type Description
      Dockerfile or image
      image string 必填 使用已存在镜像时必填。 vscode会使用镜像名称来创建开发容器。
      build.dockerfile / dockerFile string 必填 使用Dockerfile时必填。 指定一个用来生成Docker镜像的Dockerfile文件。路径相对于devcontainer.json文件。 可以在这个地址找到各种Dockerfile样例。
      build.context / context string 指定运行docker build命令时的上下文目录。 路径是基于devcontainer.json文件的相对路径。 缺省值"."
      build.args Object A set of name-value pairs containing Docker image build arguments that should be passed when building a Dockerfile. Environment and pre-defined variables may be referenced in the values. Defaults to not set. For example: "build": { "args": { "MYARG": "MYVALUE", "MYARGFROMENVVAR": "${localEnv:VARIABLE_NAME}" } }
      build.target string A string that specifies a Docker image build target that should be passed when building a Dockerfile. Defaults to not set. For example: "build": { "target": "development" }
      appPort integer, string, array 容器运行时发布到Host的端口。多个端口用数组表示。 缺省值"[]"
      containerEnv object A set of name-value pairs that sets or overrides environment variables for the container. Environment and pre-defined variables may be referenced in the values. For example: "containerEnv": { "MY_VARIABLE": "${localEnv:MY_VARIABLE}" } Requires the container be recreated / rebuilt to change.
      remoteEnv object A set of name-value pairs that sets or overrides environment variables for VS Code (or sub-processes like terminals) but not the container as a whole. Environment and pre-defined variables may be referenced in the values. Be sure Terminal > Integrated: Inherit Env is is checked in settings or the variables will not appear in the terminal. For example: "remoteEnv": { "PATH": "${containerEnv:PATH}:/some/other/path", "MY_VARIABLE": "${localEnv:MY_VARIABLE}" } Updates are applied when VS Code is restarted (or the window is reloaded).
      containerUser string Overrides the user all operations run as inside the container. Defaults to either root or the last USER instruction in the related Dockerfile used to create the image. On Linux, the specified container user's UID/GID will be updated to match the local user's UID/GID to avoid permission problems with bind mounts (unless disabled using updateRemoteUserID). Requires the container be recreated / rebuilt for updates to take effect.
      remoteUser string Overrides the user that VS Code runs as in the container (along with sub-processes like terminals, tasks, or debugging). Defaults to the containerUser. On Linux, the specified container user's UID/GID will be updated to match the local user's UID/GID to avoid permission problems with bind mounts (unless disabled using updateRemoteUserID). Updates are applied when VS Code is restarted (or the window is reloaded), but UID/GID updates are only applied when the container is created and requires a rebuild to change.
      updateRemoteUserUID boolean On Linux, if containerUser or remoteUser is specified, the container user's UID/GID will be updated to match the local user's UID/GID to avoid permission problems with bind mounts. Defaults to true. Requires the container be recreated / rebuilt for updates to take effect.
      mounts array An array of additional mount points to add to the container when created. Each value is a string that accepts the same values as the Docker CLI --mount flag. Environment and pre-defined variables may be referenced in the value. For example: "mounts": ["source=${localWorkspaceFolder}/app-scripts,target=/usr/local/share/app-scripts,type=bind,consistency=cached"] ⚠️ Codespaces ignores "bind" mounts with the exception of the Docker socket.
      workspaceMount string 覆盖缺省的mount参数。语法参见Docker文档Docker CLI --mount flag。 可以使用${localWorkspaceFolder}引用本地的工作区目录,或使用${env:VARNAMEHERE}应用环境变量
      workspaceFolder string 设置vscode连接到容器后缺省的工作目录。 通常结合workspaceMount属性使用
      runArgs array 运行容器时的命令行参数Docker CLI arguments。 缺省值"[]"。 可以使用${localWorkspaceFolder}引用本地的工作区目录,或使用${env:VARNAMEHERE}应用环境变量
      overrideCommand boolean 告诉容器在启动时是否执行命令 /bin/sh -c "while sleep 1000; do :; done",用以覆盖缺省的启动执行命令。 缺省值"true"
      shutdownAction enum 指定在vscode断开连接或者关闭时,是否停止容器。 缺省值"stopContainer"
      Docker Compose
      dockerComposeFile string, array 必填 指定一个Docker Compose文件,路径相对于devcontainer.json文件。 当需要扩展Docker Compose配置时,可以使用数组。数组的顺序和重要,后面的文件内容会覆盖之前的设置。 缺省的.env文件会在项目的根路径下寻找,但可以通过Docker Compose文件中的env_file指定另外的路径。
      service string 必填 指定启动后vscode连接哪个service。
      runServices array 指定Docker Compose文件中的哪些services需要启动。同时在断开连接后,这些services将会根据shutdownAction的设置决定是否关闭。 缺省值为所有的services。
      workspaceFolder string 连接到容器后进入的工作目录。缺省值"/"
      remoteEnv object A set of name-value pairs that sets or overrides environment variables for VS Code (or sub-processes like terminals) but not the container as a whole. Environment and pre-defined variables may be referenced in the values. Be sure Terminal > Integrated: Inherit Env is is checked in settings or the variables will not appear in the terminal. For example: "remoteEnv": { "PATH": "${containerEnv:PATH}:/some/other/path", "MY_VARIABLE": "${localEnv:MY_VARIABLE}" } Updates are applied when VS Code is restarted (or the window is reloaded)
      remoteUser string Overrides the user that VS Code runs as in the container (along with sub-processes like terminals, tasks, or debugging). Does not change the user the container as a whole runs as (which can be set in your Docker Compose file). Defaults to the user the container as a whole is running as (often root). Updates are applied when VS Code is restarted (or the window is reloaded).
      shutdownAction enum 指定在vscode断开连接或者关闭时,是否停止容器。 缺省值"stopCompose"
      General
      name string 容器显示名称
      extensions array 需要安装到容器中的vscode扩展。 缺省值"[]"
      settings object 添加到容器中的vscode settings.json
      forwardPorts array An array of ports that should be forwarded from inside the container to the local machine.
      postCreateCommand string, array 容器创建后第一次启动时执行的一组命令。命令执行目录是容器中workspaceFolder指定的目录。多条命令之间使用&&进行连接。 缺省值 none
      postStartCommand string, array A command string or list of command arguments to run when the container starts (in all cases). The parameters behave exactly like postCreateCommand, but the commands execute on start rather than create. Not set by default. ⚠️ Not yet supported in Codespaces.
      postAttachCommand string, array A command string or list of command arguments to run after VS Code has attached to a running container (in all cases). The parameters behave exactly like postCreateCommand, but the commands execute on attach rather than create. Not set by default. ⚠️ Not yet supported in Codespaces.
      initializeCommand string, array A command string or list of command arguments to run on the local machine before the container is created. This runs either when the container image is being built and when the running container is created or started. The commands execute from the workspaceFolder locally. For example, "yarn install". The array syntax ["yarn", "install"] will invoke the command (in this case yarn) directly without using a shell. ⚠️ The command is run wherever the source code is located. For Codespaces this is in the cloud.
      userEnvProbe enum Indicates the type of shell VS Code should use to "probe" for user environment variables to use by default while debugging or running a task: none (default), interactiveShell, loginShell, or interactiveLoginShell. Interactive shells will typically include variables set in /etc/bash.bashrc and .bashrc while login shells usually include variables from these "rc" files, /etc/profile and .profile. Defaults to none since the other modes can slow startup. ⚠️ Not yet supported in Codespaces.
      devPort integer 允许给vscode server指定一个端口。缺省为一个随机可用端口。
      // devcontainer.json文件内容
      
      {
         // 启动容器后的名称
          "name": "Python 3",
         // 如何构建镜像
          "build": {
              "dockerfile": "Dockerfile",
              "context": "..",
              // Update 'VARIANT' to pick a Python version: 3, 3.6, 3.7, 3.8 
              "args": { "VARIANT": "3" }
          },
          
          // Set *default* container specific settings.json values on container create.
          "settings": { 
              "terminal.integrated.shell.linux": "/bin/bash",
              "python.pythonPath": "/usr/local/bin/python",
              "python.linting.enabled": true,
              "python.linting.pylintEnabled": true,
              "python.formatting.autopep8Path": "/usr/local/py-utils/bin/autopep8",
              "python.formatting.blackPath": "/usr/local/py-utils/bin/black",
              "python.formatting.yapfPath": "/usr/local/py-utils/bin/yapf",
              "python.linting.banditPath": "/usr/local/py-utils/bin/bandit",
              "python.linting.flake8Path": "/usr/local/py-utils/bin/flake8",
              "python.linting.mypyPath": "/usr/local/py-utils/bin/mypy",
              "python.linting.pycodestylePath": "/usr/local/py-utils/bin/pycodestyle",
              "python.linting.pydocstylePath": "/usr/local/py-utils/bin/pydocstyle",
              "python.linting.pylintPath": "/usr/local/py-utils/bin/pylint"
          },
      
          // Add the IDs of extensions you want installed when the container is created.
          "extensions": [
              "ms-python.python"
          ],
      
          // Use 'forwardPorts' to make a list of ports inside the container available locally.
          "forwardPorts": [9000],
      
          // 容器被创建后运行的命令,加-i参数,添加清华源
          "postCreateCommand": "pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt",
      
          // Comment out to connect as root instead.
          "remoteUser": "vscode"
      }
      
      
  • 构建开发容器

    image-20201031155754156
  • 查看镜像和容器

    (base) hsj@ubuntu:~$ docker images
    REPOSITORY                                                          TAG                 IMAGE ID            CREATED             SIZE
    vsc-vscode-remote-try-python-819f272b21d401852f1bc06907b2a3e5-uid   latest              0723fa47dbba        56 minutes ago      1.1GB
    vsc-vscode-remote-try-python-819f272b21d401852f1bc06907b2a3e5       latest              23abb7955f18        56 minutes ago      1.1GB
    (base) hsj@ubuntu:~$ docker container ls
    CONTAINER ID        IMAGE                                                               COMMAND                  CREATED             STATUS              PORTS               NAMES
    87530ce7c203        vsc-vscode-remote-try-python-819f272b21d401852f1bc06907b2a3e5-uid   "/bin/sh -c 'echo Co…"   57 minutes ago      Up 57 minutes                           busy_gagarin
    
  • 启动测试

    在vscode终端输入flask run --host 0.0.0.0 --port 9000,浏览器输入localhost:9000

    image-20201031160135407
  • 调试

你可能感兴趣的:(在ubuntu上使用vscode容器开发)