跳转至

VS Code Devcontainer:远程/容器化开发环境

为什么要学 Devcontainer

"在我电脑上能跑啊"——这句话是团队协作中最大的笑话,也是最真实的痛点。不同成员的操作系统、Python/Node 版本、系统库、环境变量都不一样,导致代码在本地能跑但在别人机器上炸了。

Dev Container(开发容器)的核心理念是:把完整的开发环境定义为代码,用 Docker 容器封装。任何人 clone 仓库后,VS Code 自动创建一个一致的开发环境——相同的 OS、相同的工具版本、相同的扩展。

核心价值: - 新人 onboarding 从"配半天环境"变成"一键启动" - 开发环境 100% 可复现,消除"在我这里能跑"问题 - 不污染宿主机(Python 版本冲突、全局包混乱等一去不返) - 支持远程开发(GitHub Codespaces、远程服务器) - 与 CI 环境保持一致

适用场景: - 多人协作项目的统一环境 - 需要特定系统库/工具的项目 - 多语言/多版本切换频繁的开发者 - 远程服务器开发 - 开源项目降低贡献门槛


核心概念

白话解释

概念白话说明
devcontainer.json开发容器的配置文件,定义用什么镜像、装什么工具、用什么扩展
Dockerfile自定义镜像的构建文件(可选,简单场景直接用预构建镜像)
Features可组合的工具安装模块(如 Node.js、Python、Docker-in-Docker)
Workspace Mount把项目代码挂载到容器内的方式
Port Forwarding容器内端口自动映射到宿主机
Post-Create Command容器创建后自动执行的命令(如 npm install)
docker-compose.yml多容器编排(如项目 + 数据库 + Redis)
GitHub Codespaces云端 Dev Container,不需要本地 Docker

工作流程

项目仓库
├── .devcontainer/
│   ├── devcontainer.json   ← 环境配置
│   └── Dockerfile          ← 自定义镜像(可选)
├── src/
└── ...

开发者 clone → VS Code 检测到 devcontainer.json → 提示"在容器中重新打开"
→ Docker 构建/拉取镜像 → 启动容器 → 安装扩展 → 执行初始化命令
→ 开发者在容器中编码(体验和本地一样)

安装配置

前置要求

  1. Docker Desktop(Windows/macOS)或 Docker Engine(Linux)
  2. VS Code(最新版)
  3. Dev Containers 扩展
# 安装 VS Code 扩展
code --install-extension ms-vscode-remote.remote-containers

验证 Docker

docker --version
docker run hello-world

创建第一个 Dev Container

在项目根目录:

mkdir .devcontainer

创建 .devcontainer/devcontainer.json

{
    "name": "Python 开发环境",
    "image": "mcr.microsoft.com/devcontainers/python:3.12",
    "features": {
        "ghcr.io/devcontainers/features/node:1": {
            "version": "20"
        }
    },
    "customizations": {
        "vscode": {
            "extensions": [
                "ms-python.python",
                "ms-python.vscode-pylance",
                "charliermarsh.ruff"
            ],
            "settings": {
                "python.defaultInterpreterPath": "/usr/local/bin/python"
            }
        }
    },
    "postCreateCommand": "pip install -r requirements.txt",
    "forwardPorts": [8000],
    "remoteUser": "vscode"
}

启动容器

  1. 打开 VS Code
  2. Ctrl+Shift+P → "Dev Containers: Reopen in Container"
  3. 等待构建完成(首次较慢,后续有缓存)
  4. 左下角变成绿色标记表示已在容器中

快速上手

使用预构建镜像

最简单的方式——直接用微软提供的预构建镜像:

{
    "name": "Node.js",
    "image": "mcr.microsoft.com/devcontainers/javascript-node:20"
}

常用预构建镜像:

语言/场景镜像
Python 3.12mcr.microsoft.com/devcontainers/python:3.12
Node.js 20mcr.microsoft.com/devcontainers/javascript-node:20
Go 1.22mcr.microsoft.com/devcontainers/go:1.22
Rustmcr.microsoft.com/devcontainers/rust:latest
Java 21mcr.microsoft.com/devcontainers/java:21
通用 (Ubuntu)mcr.microsoft.com/devcontainers/base:ubuntu

使用 Features 组合工具

Features 是可插拔的工具安装器,避免写 Dockerfile:

{
    "name": "全栈开发环境",
    "image": "mcr.microsoft.com/devcontainers/base:ubuntu",
    "features": {
        "ghcr.io/devcontainers/features/python:1": {
            "version": "3.12"
        },
        "ghcr.io/devcontainers/features/node:1": {
            "version": "20"
        },
        "ghcr.io/devcontainers/features/docker-in-docker:2": {},
        "ghcr.io/devcontainers/features/git:1": {},
        "ghcr.io/devcontainers/features/github-cli:1": {}
    }
}

端口转发

{
    "forwardPorts": [3000, 5432, 6379],
    "portsAttributes": {
        "3000": {
            "label": "Frontend",
            "onAutoForward": "openBrowser"
        },
        "5432": {
            "label": "PostgreSQL",
            "onAutoForward": "silent"
        }
    }
}

进阶用法

1. 自定义 Dockerfile

当预构建镜像不满足需求时:

.devcontainer/Dockerfile:

FROM mcr.microsoft.com/devcontainers/python:3.12

# 安装系统依赖
RUN apt-get update && apt-get install -y \
    libpq-dev \
    ffmpeg \
    && rm -rf /var/lib/apt/lists/*

# 安装 Python 工具
RUN pip install --no-cache-dir \
    poetry \
    ruff \
    mypy

# 安装 uv (快速包管理器)
RUN curl -LsSf https://astral.sh/uv/install.sh | sh

.devcontainer/devcontainer.json:

{
    "name": "Custom Python",
    "build": {
        "dockerfile": "Dockerfile",
        "context": ".."
    },
    "postCreateCommand": "poetry install"
}

2. 使用 Docker Compose(多服务)

.devcontainer/docker-compose.yml:

services:
  app:
    build:
      context: ..
      dockerfile: .devcontainer/Dockerfile
    volumes:
      - ..:/workspace:cached
    command: sleep infinity
    depends_on:
      - db
      - redis

  db:
    image: postgres:16
    environment:
      POSTGRES_DB: myapp
      POSTGRES_USER: dev
      POSTGRES_PASSWORD: devpass
    ports:
      - "5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"

volumes:
  pgdata:

.devcontainer/devcontainer.json:

{
    "name": "Full Stack with DB",
    "dockerComposeFile": "docker-compose.yml",
    "service": "app",
    "workspaceFolder": "/workspace",
    "customizations": {
        "vscode": {
            "extensions": [
                "ms-python.python",
                "cweijan.vscode-database-client2"
            ]
        }
    },
    "forwardPorts": [8000, 5432, 6379]
}

3. 环境变量管理

{
    "containerEnv": {
        "DATABASE_URL": "postgresql://dev:devpass@db:5432/myapp",
        "REDIS_URL": "redis://redis:6379",
        "DEBUG": "true"
    },
    "remoteEnv": {
        "LOCAL_WORKSPACE_FOLDER": "${localWorkspaceFolder}"
    }
}

使用 .env 文件:

{
    "runArgs": ["--env-file", ".devcontainer/.env"]
}

4. 生命周期钩子

{
    "initializeCommand": "echo '宿主机上执行,容器创建前'",
    "onCreateCommand": "echo '容器首次创建时执行'",
    "updateContentCommand": "echo '代码更新时执行'",
    "postCreateCommand": "pip install -r requirements.txt && pre-commit install",
    "postStartCommand": "echo '每次容器启动时执行'",
    "postAttachCommand": "echo '每次 VS Code 连接时执行'"
}

5. 多人协作标准化配置

推荐的项目标准配置:

{
    "name": "项目名-dev",
    "image": "mcr.microsoft.com/devcontainers/python:3.12",
    "features": {
        "ghcr.io/devcontainers/features/node:1": {"version": "20"},
        "ghcr.io/devcontainers/features/github-cli:1": {}
    },
    "customizations": {
        "vscode": {
            "extensions": [
                "ms-python.python",
                "charliermarsh.ruff",
                "ms-python.mypy-type-checker",
                "esbenp.prettier-vscode",
                "eamodio.gitlens"
            ],
            "settings": {
                "editor.formatOnSave": true,
                "python.analysis.typeCheckingMode": "basic",
                "[python]": {
                    "editor.defaultFormatter": "charliermarsh.ruff"
                }
            }
        }
    },
    "postCreateCommand": "pip install -e '.[dev]' && pre-commit install",
    "forwardPorts": [8000],
    "remoteUser": "vscode"
}

6. GitHub Codespaces

devcontainer.json 同时被 GitHub Codespaces 使用,实现"浏览器中一键开发":

{
    "name": "Codespace",
    "image": "mcr.microsoft.com/devcontainers/universal:2",
    "hostRequirements": {
        "cpus": 4,
        "memory": "8gb",
        "storage": "32gb"
    },
    "waitFor": "onCreateCommand",
    "updateContentCommand": "pip install -r requirements.txt",
    "postCreateCommand": "echo 'Ready to code!'",
    "customizations": {
        "codespaces": {
            "openFiles": ["README.md"]
        }
    }
}

7. GPU 支持(机器学习)

{
    "name": "ML Dev",
    "image": "mcr.microsoft.com/devcontainers/python:3.12",
    "runArgs": [
        "--gpus", "all"
    ],
    "features": {
        "ghcr.io/devcontainers/features/nvidia-cuda:1": {
            "cudaVersion": "12.2"
        }
    },
    "postCreateCommand": "pip install torch torchvision"
}

8. 挂载 SSH keys 和 Git 配置

VS Code Dev Containers 扩展会自动: - 转发 SSH agent(无需复制 SSH key 到容器) - 共享 Git 配置(~/.gitconfig) - 共享 GPG 密钥

如果需要手动配置:

{
    "mounts": [
        "source=${localEnv:HOME}/.ssh,target=/home/vscode/.ssh,type=bind,readonly"
    ]
}


常见问题

Q1: 构建很慢

  • 使用预构建镜像而非从零构建
  • Docker BuildKit 缓存层(不要频繁改 Dockerfile 前面的指令)
  • 使用 .dockerignore 排除不需要复制到镜像的文件
  • 考虑推送自定义镜像到 registry,直接 pull

Q2: 容器中文件权限问题

{
    "remoteUser": "vscode",
    "containerUser": "vscode"
}

如果还有问题,添加:

{
    "postCreateCommand": "sudo chown -R vscode:vscode /workspace"
}

Q3: 如何保留容器中安装的东西

使用 named volumes:

{
    "mounts": [
        "source=project-node_modules,target=/workspace/node_modules,type=volume"
    ]
}

Q4: VS Code 扩展在容器中不工作

某些扩展需要区分"UI 扩展"和"Workspace 扩展"。在 customizations.vscode.extensions 中声明的扩展会自动安装到容器中。如果扩展需要本地 UI,在 VS Code 设置中手动安装到本地。

Q5: 与 Docker Compose 项目如何共存

如果项目已有 docker-compose.yml 用于部署,Dev Container 可以使用独立的 compose 文件:

{
    "dockerComposeFile": ["../docker-compose.yml", "docker-compose.dev.yml"],
    "service": "app",
    "workspaceFolder": "/app"
}


参考资源

资源链接
官方文档https://containers.dev
VS Code 文档https://code.visualstudio.com/docs/devcontainers/containers
预构建镜像https://github.com/devcontainers/images
Features 列表https://containers.dev/features
模板集合https://containers.dev/templates
GitHub Codespaceshttps://github.com/features/codespaces
规范仓库https://github.com/devcontainers/spec

小结: Dev Container 把"环境即代码"的理念落地到了日常开发中。一次配置,团队所有人(包括未来的你自己)都不需要再花时间配环境。对于任何多人协作的项目,.devcontainer/ 目录应该和 .gitignore 一样成为标配。