在ubuntu上使用vscode容器開發(fā)

vscode

在ubuntu上使用vscode容器開發(fā)

  • 創(chuàng)建一個非root用戶運(yùn)行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
    
    # 執(zhí)行
    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相關(guān)文件
    # requirements.txt python依賴文件
    # index.html flask頁面文件
    # launch.json vscode運(yùn)行調(diào)試文件
    
  • 重要文件說明

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

      項目中的devcontainer.json文件告訴Visual Studio Code如何使用定義良好的工具和運(yùn)行時堆棧訪問(或創(chuàng)建)開發(fā)容器。該容器可用于運(yùn)行應(yīng)用程序或用于使用代碼庫的沙盒工具累盗,庫或運(yùn)行時倔喂。它可以與Remote-Containers擴(kuò)展或GitHub Codespaces一起使用

      Property Type Description
      Dockerfile or image
      image string 必填 使用已存在鏡像時必填捅膘。 vscode會使用鏡像名稱來創(chuàng)建開發(fā)容器嚎于。
      build.dockerfile / dockerFile string 必填 使用Dockerfile時必填作谚。 指定一個用來生成Docker鏡像的Dockerfile文件型型。路徑相對于devcontainer.json文件忆家。 可以在這個地址找到各種Dockerfile樣例犹菇。
      build.context / context string 指定運(yùn)行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 容器運(yùn)行時發(fā)布到Host的端口揭芍。多個端口用數(shù)組表示。 缺省值"[]"
      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參數(shù)卸例。語法參見Docker文檔Docker CLI --mount flag称杨。 可以使用${localWorkspaceFolder}引用本地的工作區(qū)目錄,或使用${env:VARNAMEHERE}應(yīng)用環(huán)境變量
      workspaceFolder string 設(shè)置vscode連接到容器后缺省的工作目錄币厕。 通常結(jié)合workspaceMount屬性使用
      runArgs array 運(yùn)行容器時的命令行參數(shù)Docker CLI arguments列另。 缺省值"[]"。 可以使用${localWorkspaceFolder}引用本地的工作區(qū)目錄旦装,或使用${env:VARNAMEHERE}應(yīng)用環(huán)境變量
      overrideCommand boolean 告訴容器在啟動時是否執(zhí)行命令 /bin/sh -c "while sleep 1000; do :; done"页衙,用以覆蓋缺省的啟動執(zhí)行命令。 缺省值"true"阴绢。
      shutdownAction enum 指定在vscode斷開連接或者關(guān)閉時店乐,是否停止容器。 缺省值"stopContainer"
      Docker Compose
      dockerComposeFile string, array 必填 指定一個Docker Compose文件呻袭,路徑相對于devcontainer.json文件眨八。 當(dāng)需要擴(kuò)展Docker Compose配置時,可以使用數(shù)組左电。數(shù)組的順序和重要廉侧,后面的文件內(nèi)容會覆蓋之前的設(shè)置。 缺省的.env文件會在項目的根路徑下尋找篓足,但可以通過Docker Compose文件中的env_file指定另外的路徑段誊。
      service string 必填 指定啟動后vscode連接哪個service。
      runServices array 指定Docker Compose文件中的哪些services需要啟動栈拖。同時在斷開連接后连舍,這些services將會根據(jù)shutdownAction的設(shè)置決定是否關(guān)閉。 缺省值為所有的services涩哟。
      workspaceFolder string 連接到容器后進(jìn)入的工作目錄索赏。缺省值"/"
      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斷開連接或者關(guān)閉時盼玄,是否停止容器。 缺省值"stopCompose"
      General
      name string 容器顯示名稱
      extensions array 需要安裝到容器中的vscode擴(kuò)展潜腻。 缺省值"[]"
      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 容器創(chuàng)建后第一次啟動時執(zhí)行的一組命令埃儿。命令執(zhí)行目錄是容器中workspaceFolder指定的目錄。多條命令之間使用&&進(jìn)行連接砾赔。 缺省值 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指定一個端口蝌箍。缺省為一個隨機(jī)可用端口青灼。
      // devcontainer.json文件內(nèi)容
      
      {
         // 啟動容器后的名稱
          "name": "Python 3",
         // 如何構(gòu)建鏡像
          "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],
      
          // 容器被創(chuàng)建后運(yùn)行的命令,加-i參數(shù),添加清華源
          "postCreateCommand": "pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt",
      
          // Comment out to connect as root instead.
          "remoteUser": "vscode"
      }
      
      
  • 構(gòu)建開發(fā)容器

    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
  • 調(diào)試

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末暴心,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子杂拨,更是在濱河造成了極大的恐慌专普,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,657評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件弹沽,死亡現(xiàn)場離奇詭異檀夹,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)策橘,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評論 3 394
  • 文/潘曉璐 我一進(jìn)店門炸渡,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人丽已,你說我怎么就攤上這事蚌堵。” “怎么了沛婴?”我有些...
    開封第一講書人閱讀 164,057評論 0 354
  • 文/不壞的土叔 我叫張陵吼畏,是天一觀的道長。 經(jīng)常有香客問我嘁灯,道長泻蚊,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,509評論 1 293
  • 正文 為了忘掉前任丑婿,我火速辦了婚禮性雄,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘羹奉。我一直安慰自己秒旋,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,562評論 6 392
  • 文/花漫 我一把揭開白布尘奏。 她就那樣靜靜地躺著滩褥,像睡著了一般。 火紅的嫁衣襯著肌膚如雪炫加。 梳的紋絲不亂的頭發(fā)上瑰煎,一...
    開封第一講書人閱讀 51,443評論 1 302
  • 那天铺然,我揣著相機(jī)與錄音,去河邊找鬼酒甸。 笑死魄健,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的插勤。 我是一名探鬼主播沽瘦,決...
    沈念sama閱讀 40,251評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼农尖!你這毒婦竟也來了析恋?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,129評論 0 276
  • 序言:老撾萬榮一對情侶失蹤盛卡,失蹤者是張志新(化名)和其女友劉穎助隧,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體滑沧,經(jīng)...
    沈念sama閱讀 45,561評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡并村,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,779評論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了滓技。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片哩牍。...
    茶點(diǎn)故事閱讀 39,902評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖令漂,靈堂內(nèi)的尸體忽然破棺而出膝昆,到底是詐尸還是另有隱情,我是刑警寧澤洗显,帶...
    沈念sama閱讀 35,621評論 5 345
  • 正文 年R本政府宣布外潜,位于F島的核電站,受9級特大地震影響挠唆,放射性物質(zhì)發(fā)生泄漏处窥。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,220評論 3 328
  • 文/蒙蒙 一玄组、第九天 我趴在偏房一處隱蔽的房頂上張望滔驾。 院中可真熱鬧,春花似錦俄讹、人聲如沸哆致。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽摊阀。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間胞此,已是汗流浹背臣咖。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留漱牵,地道東北人夺蛇。 一個月前我還...
    沈念sama閱讀 48,025評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像酣胀,于是被迫代替她去往敵國和親刁赦。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,843評論 2 354

推薦閱讀更多精彩內(nèi)容