在VsCode上使用开发容器devcontainer

概要

本文主要介绍了如何在 VsCode 中使用开发容器来确保项目的开发成员使用统一的开发环境。

过程

创建配置文件

在工程文件夹下创建 .devcontainer 文件夹,并在其中创建 devcontainer.json 和 Dockerfile 文件。

文件结构如下:

shell 复制代码
.devcontainer/
├── Dockerfile
└── devcontainer.json

其中,devcontainer.json 文件内容如下:

json 复制代码
{
    "name": "Python Dev (3.12)",
    "build": {
        "dockerfile": "Dockerfile",
        "context": "..",
        "options": [
            "--network=host"
        ]
    },
    "settings": {
        "terminal.integrated.defaultProfile.linux": "bash",
        "python.defaultInterpreterPath": "/usr/bin/python3"
    },
    "extensions": [
        "ms-python.python",
        "ms-azuretools.vscode-docker"
    ],
    "postCreateCommand": "uv sync",
    "remoteUser": "root"
}

Dockerfile 是根据你需要定制的镜像描述文件,这里以一个简单的 python flask 工程举例:

shell 复制代码
# 使用 Ubuntu 24.04 作为基础镜像
FROM ubuntu:24.04

# 安装依赖项
RUN sed -i 's@//.*archive.ubuntu.com@//mirrors.tuna.tsinghua.edu.cn@g' /etc/apt/sources.list.d/ubuntu.sources && \
    apt-get update && \
    apt-get install -y python3.12 python3.12-venv python3-pip curl git

# 设置工作目录
WORKDIR /workspace

使用容器构建开发环境

要在 VsCode 中使用容器,你需要下载 "Dev Containers"插件。

在启动之前,你可以使用 podman/docker build 命令先构建一下镜像,确认 Dockerfile 没有问题:

shell 复制代码
cd .devcontainer
podman build -t container-test:latest .

安装完成后,使用 VsCode 打开工作文件夹,并按 F1 或 Ctrl+Shift+P 打开命令面板,输入 reopen in container(或点击左下角的蓝色图标,并选择"在容器中重新打开")。

随后,VsCode 将自动构建容器并启动,启动后的环境即为构建完成的容器。

相关推荐
莫卢俊德11 分钟前
vscode ssh config
ide·vscode·ssh
郝学胜-神的一滴1 天前
Effective Python 条款44:善用属性注解
开发语言·c++·vscode·python·算法·stl
BD_Marathon5 天前
安装Jupyter notebook
ide·python·jupyter
讓丄帝愛伱6 天前
Zed Markdown 预览不能铺满全屏的原因及解决
ide
FungLeo6 天前
FengCMS · PHP+MySQL 升级实录 · 编辑器迁移:KindEditor → wangEditor5 +服务端 HTML Purifier
mysql·编辑器·php·富文本编辑器·fengcms
BD_Marathon6 天前
Jupyter魔法命令
ide·python·jupyter
郝学胜-神的一滴7 天前
Effective STL 条款 07:指针容器销毁前先删除
开发语言·c++·vscode·leetcode·rpc·visual studio
aaaameliaaa7 天前
VSCode的安装与配置
ide·笔记·vscode·编辑器
Star(up up up)8 天前
MySQL 事务隔离级别是如何实现的?从 MVCC 到锁机制原理详解
笔记·vscode·sql·学习·程序人生·mysql·学习方法
ScilogyHunter9 天前
[14] TMS570LC4357_VIM向量中断:128 通道、双 VIM 与硬件向量分发
单片机·编辑器·vim·excel·hercules·tms570