在VsCode上使用开发容器devcontainer

概要

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

过程

创建配置文件

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

文件结构如下:

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 打开工作文件夹,并按 F1Ctrl+Shift+P 打开命令面板,输入 reopen in container(或点击左下角的蓝色图标,并选择"在容器中重新打开")。

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

相关推荐
言之。17 小时前
Claude Code IDE 集成工作原理详解
ide·人工智能
悠悠子衿1213818 小时前
Claude+VSCODE配置git导致频繁弹出git bash 的CMO窗口解决方法
ide·git·vscode
大志哥12319 小时前
IntelliJ IDEA父子工程中导入公网远程备份项目到新目录
java·ide·intellij-idea
梁萌19 小时前
idea使用AI插件(CodeGeeX)
java·ide·ai·intellij-idea·插件·codegeex
wqfhenanxc20 小时前
vscode/cursor 远程Linux基础命令
linux·ide·vscode
Lv117700821 小时前
Visual Studio中的常量和只读变量
ide·笔记·c#·visual studio
Balding Curry21 小时前
vscode快速添加插件的3种方式
ide·vscode·编辑器
yyovoll21 小时前
循环知识点介绍 -蓝桥杯
jvm·ide·java-ee
Clarence Liu1 天前
MacOS 在Trae IDE中构建现代C++开发环境:从新手到高效的完整指南
c++·ide·macos
木楚1 天前
在idea中构建传统ssm框架的步骤和方式
java·ide·intellij-idea