跳到主要内容

Dev Container 教程 (一) 基本使用

小林
后端开发工程师, 专注Go开发、微服务和云原生

作为开发者, 我们常面临这样的挑战:如何让系统环境、编程工具链、依赖库及编辑器配置在不同机器上保持一致?如何避免每次搭建开发环境浪费大量时间? 本文介绍的 Dev Containers 就为了解决这些问题, 让你一键启动一个标准化的开发环境

messenger-running.png

什么是 Dev Container

Dev Container 是一种将容器用作完整开发环境的技术方案. 简单表示

开发环境=devcontainer.json+Docker+VSCode开发环境 = devcontainer.json + Docker + VSCode

为什么使用 Dev Container

  • 环境一致性:无论怎样更换设备, 只需拉取容器即可获得完全一致的开发环境, 避免繁琐的环境配置过程
  • 团队协作:确保所有团队成员使用完全相同的开发环境, 消除"我的机器可以, 你的不行"的常见问题
  • 贴近生产:提供纯净的 Linux 环境, 更接近实际生产环境, 减少环境差异导致的问题
  • 流程简化:自动化环境部署, 简化开发流程, 提升开发效率
  • 工具集成:内置常用开发工具, 自动安装 VSCode 插件, 开箱即用
  • 配置同步:确保 VSCode 设置和插件在所有环境中保持一致
  • 远程开发:支持远程开发场景, 使开发环境与本地机器解耦

前置条件

快速入门

从零开始创建一个 Dev Container

下面以创建 Python 开发环境为例, 演示如何从零开始创建 Dev Container

new-devcontainers

  • 点击 VSCode 左下角的 Open a Remote Window 按钮
  • 在弹出菜单中选择 New Dev Container...
  • 在模板列表中输入 python 进行过滤
  • 输入容器名称(如 python-demo)
  • 等待 Docker 拉取容器镜像(可点击 show log 查看进度)
  • 成功后, VSCode 将打开新窗口, 表示已进入 Dev Container 环境
  • 在终端输入 python --version 确认 Python 环境是否可用

此时, 工作目录下会生成 Dev Container 配置文件:

.devcontainer/devcontainer.json
// For format details, see https://aka.ms/devcontainer.json. For config options, see the
// README at: https://github.com/devcontainers/templates/tree/main/src/python
{
"name": "Python 3",
// Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
"image": "mcr.microsoft.com/devcontainers/python:1-3.12-bullseye"

// 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": "pip3 install --user -r requirements.txt",

// Configure tool-specific properties.
// "customizations": {},

// Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
// "remoteUser": "root"
}

Dev Container 做了什么事?

img

  • 拉取配置中 image 字段指定的 Docker 镜像
  • 如使用 Dockerfile 或 Features, 会自动构建定制化镜像

img

  • 启动 Docker 容器作为开发环境
  • 容器关闭后自动销毁, 确保环境纯净

img

  • 创建与容器名称相同的持久化卷
  • 将持久化卷挂载到工作目录, 确保数据不丢失

img

  • 自动安装配置模板中指定的 VSCode 插件
  • 开箱即用, 无需手动配置开发环境

用 Dev Container 打开已有项目

exist-devcontainers

以下演示如何为现有项目配置 Dev Container(以 Golang Gin 项目为例):

  • 点击左下角的 Open a Remote Window 按钮
  • 选择 Add Dev Container Configuration Files...
  • 选择 Add Configuration to workspace 将配置文件存放到工作目录
  • 在模板列表中输入 go 进行过滤
  • 选择 Go 版本(如 1.24-bookworm)
  • 按需选择 Features(可跳过)
  • 点击 Reopen in Container 在新窗口打开容器

生成的配置文件如下:

.devcontainer/devcontainer.json
// For format details, see https://aka.ms/devcontainer.json. For config options, see the
// README at: https://github.com/devcontainers/templates/tree/main/src/go
{
"name": "Go",
// Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
"image": "mcr.microsoft.com/devcontainers/go:1-1.24-bookworm"

// 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": "go version",

// Configure tool-specific properties.
// "customizations": {},

// Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
// "remoteUser": "root"
}

同样预装了相关插件, 预装哪些插件根据配置模板会有不同

img

注意

使用 Dev Container 打开已有项目时, 不会创建持久化卷, 而是直接将本地目录挂载到容器工作目录. 这意味着在容器中对工作目录的修改会直接反映到本地文件系统

配置完成后, 可运行项目并访问 http://localhost:8080/ping

go run main.go

Dev Container 会自动将容器内部端口转发到本地, 无需手动配置端口映射

img

配置 devcontainer.json

下面以 Python FastAPI 项目为例, 优化第一个示例devcontainer.json 配置, 提升开发体验

.devcontainer/devcontainer.json
// For format details, see https://aka.ms/devcontainer.json. For config options, see the
// README at: https://github.com/devcontainers/templates/tree/main/src/python
{
"name": "Python 3",
// Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
"image": "mcr.microsoft.com/devcontainers/python:1-3.12-bullseye",
// 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": "pip3 install --user -r requirements.txt",
// Configure tool-specific properties.
"customizations": {
"vscode": {
"settings": {
"window.newWindowProfile": "Default", // 新窗口使用的配置文件, 只能在"默认配置文件"中设置
"files.autoSave": "afterDelay", // 自动保存文件
"editor.formatOnSave": true, // 保存时自动格式化
"files.simpleDialog.enable": true, // 简单对话框, ctrl+n 新建文件时不再弹出对话框
"editor.insertSpaces": true, // 使用空格代替制表符
"editor.tabSize": 4, // 缩进空格数
"editor.autoClosingDelete": "always", // 删除左括号时总是自动删除右括号
"editor.minimap.autohide": "mouseover", // 鼠标不在缩略图上时隐藏缩略图, 鼠标在缩略图上时显示缩略图
"terminal.integrated.cursorStyle": "underline", // 终端光标样式使用下划线
"explorer.confirmDelete": false, // 删除文件时不再弹出确认对话框
"explorer.confirmDragAndDrop": false, // 拖放移动文件或文件夹时不再弹出确认对话框
"vsicons.dontShowNewVersionMessage": true, // 不显示新版本消息
"workbench.iconTheme": "vscode-icons" // 使用 vscode-icons 图标主题
},
"extensions": [
"piotrpalarz.vscode-gitignore-generator", // .gitignore 文件生成器
"mhutchie.git-graph", // Git 图形化视图
"eamodio.gitlens", // Git 增强工具, 主要为了能显示代码作者
"ms-python.vscode-pylance", // Python 语言支持
"vscode-icons-team.vscode-icons", // VSCode 图标主题
"github.copilot", // GitHub Copilot, AI 代码补全
"github.copilot-chat" // GitHub Copilot Chat, AI 聊天助手
]
}
},
// Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
// "remoteUser": "root"
"containerEnv": {
"PIP_INDEX_URL": "https://mirrors.aliyun.com/pypi/simple/",
"PIP_TRUSTED_HOST": "mirrors.aliyun.com"
},
"postCreateCommand": "pip install -U pip && pip install fastapi uvicorn[standard]",
"postStartCommand": "uvicorn main:app --reload"
}
  • name: 必填项, 会显示在 VSCode 的 UI 上
  • image: 基础 Docker 镜像地址
  • customizations: 跟编辑器相关的配置, VSCode 的相关设置可以在这里配置, 我这里修改 settings.json 的一些值和预装插件, VSCode 配置可以参考我之前的文章
  • containerEnv: 注入容器的环境变量, 这里通过环境变量设置 pip 使用阿里源
  • postCreateCommand: 每次容器构建完成前执行的最后一段命令, 我们在这里配置安装项目所需的依赖库
  • postStartCommand: 每次容器启动前执行的最后一段命令, 可以在这里配置启动服务的命令
  • 更多配置项可以参考Dev Container 官方文档

配置完成后, 点击左下角按钮选择 Rebuild Container 重建容器:

rebuild-devcontainer

容器构建完成后, Dev Container 会自动启动服务并映射端口, 可点击 Open in Browser 直接访问应用

img

总结

本文通过示例介绍了 Dev Container 的基本使用, 为避免篇幅过长, 我将在后续文章介绍 Dev Container 更多高级用法

更多

参考