使用 VSCode Dev Containers 扩展在 Docker 容器中进行开发的配置指南。通过 .devcontainer/devcontainer.json 文件定义开发环境,实现团队开发环境的标准化和项目依赖的隔离。

参考: https://code.visualstudio.com/docs/devcontainers/containers


简介

  • 在 Docker 容器内进行开发
  • 统一团队的开发环境
  • 隔离项目依赖

安装插件

  • Dev Containers
  • Remote - Containers

配置

.devcontainer/devcontainer.json

.devcontainer/devcontainer.jsonVSCode Dev Containers 扩展 使用的配置文件,位置和作用如下:

这个文件应该在项目根目录下:

your-project/
├── .devcontainer/
│   └── devcontainer.json
├── src/
├── README.md
└── ...其他项目文件

如何创建这个文件

通过 VSCode 创建 (命令行: Dev Containers: Add Dev Container Configuration Files) 或手动创建。

示例

以下配置示例包含 GPU 直通、X11 图形转发、工作区挂载等实际项目场景的完整设置,适用于需要 GUI 或 GPU 的开发环境。

// For format details, see https://aka.ms/devcontainer.json. For config options, see the
// README at: https://github.com/devcontainers/templates/tree/main/src/ubuntu
{
  "name": "umi-dev",
  // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
  "image": "umi:dev-20250911",
 
  // Features to add to the dev container. More info: https://containers.dev/features.
  // "features": {},
 
  // Use 'forwardPorts' to make a list of ports inside the container available locally.
  // "forwardPorts": [],
 
  // Use 'postCreateCommand' to run commands after the container is created.
  "postCreateCommand": "uname -a",
 
  // Configure tool-specific properties.
  "customizations": {
    "vscode": {
      "settings": {
        "terminal.integrated.defaultProfile.linux": "bash"
      }
    }
  },
 
  // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
  // "remoteUser": "root"
  "remoteUser": "ubuntu",
  // 让 Dev Containers 使用其默认的长驻命令保持容器存活(修复镜像 CMD 为非交互 bash 时容器秒退的问题)
  "overrideCommand": true,
  "init": true,
  "workspaceFolder": "/home/ubuntu/sean_ws/umi-flow",
  "workspaceMount": "type=bind,source=${localEnv:HOME}/sean_ws/umi-flow,target=/home/ubuntu/sean_ws/umi-flow,consistency=cached",
 
  "containerEnv": {
    "DISPLAY": "${localEnv:DISPLAY}",
    "XAUTHORITY": "/home/ubuntu/.Xauthority",
    "QT_X11_NO_MITSHM": "1",
    "LIBGL_ALWAYS_SOFTWARE": "0"
  },
 
  "runArgs": [
    "--env",
    "DISPLAY",
    "--ipc=host",
    "--device=/dev/dri"
 
    /* 如果你的宿主机是 NVIDIA GPU 并已安装 nvidia-container-toolkit,可取消下一行注释启用: */
    // "--gpus=all"
  ],
 
  "mounts": [
    "type=bind,source=/tmp/.X11-unix,target=/tmp/.X11-unix,consistency=cached",
    "type=bind,source=${localEnv:HOME}/.Xauthority,target=/home/ubuntu/.Xauthority,consistency=cached"
  ]
}