使用VSCode调试Docker中的Python程序
# 1 方法一
# 1.1 首先准备以下文件
# 1.1.1 test.py
import debugpy;debugpy.connect(('127.0.0.1', 5678))
# 这是一个测试文件
def add(a, b):
"""返回两个数的和"""
return a + b
# 测试函数
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
assert add(0, 0) == 0
# 运行测试
if __name__ == "__main__":
x = 42
y = 24
print(f"Sum of {x} and {y} is {add(x, y)}")
test_add()
print("All tests passed!")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 1.1.2 requirements.txt
debugpy
1
# 1.1.3 Dockerfile
# 使用官方Python基础镜像
FROM python:3.12-slim
# 设置环境变量,指定Python使用国内源
ENV PYTHONPIP_NO_CACHE_DIR=off
ENV PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple
# 设置工作目录
WORKDIR /app
# 复制项目文件到工作目录
COPY . /app
# 安装依赖
RUN pip install --no-cache-dir -r requirements.txt
# 指定容器启动时运行的命令
CMD ["python", "-m", "debugpy", "--listen", "0.0.0.0:5678", "--wait-for-client", "test.py"]
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 1.1.4 .vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Remote Attach (Docker)",
"type": "debugpy",
"request": "attach",
"connect": {
"host": "localhost",
"port": 5678
},
"pathMappings": [
{
"localRoot": "${workspaceFolder}",
"remoteRoot": "/app"
}
]
}
]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 1.2 运行容器
# 构建镜像
docker build -t docker_dubug_test .
# 运行容器
docker run -it --rm -p 5678:5678 docker_dubug_test:latest
1
2
3
4
2
3
4
# 1.3 开始 debug
打断点:
开始debug:
# 1.4 参考
https://blog.csdn.net/zhshenqiong/article/details/148063652 https://blog.csdn.net/sssszswkshs/article/details/147553801
# 2 方法二
以远程开发的形式连接容器代码
# 2.1 安装容器插件
Dev Containers
# 2.2 安装远程开发插件
Remote Explorer
# 2.3 以远程连接的方式连接 Docker 容器
再Remote Explorer
中,可以像操控远程服务器一样,操控已经启动的 Docker 容器
上次更新: 2025/07/18, 09:51:17