在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
  • 调试

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,699评论 6 513
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,124评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,127评论 0 358
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,342评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,356评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,057评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,654评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,572评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,095评论 1 318
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,205评论 3 339
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,343评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,015评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,704评论 3 332
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,196评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,320评论 1 271
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,690评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,348评论 2 358

推荐阅读更多精彩内容