【发布时间】:2020-07-09 20:22:35
【问题描述】:
为易于使用的环境配置 VS Code。我想有一种简单的方法在 Docker 中启动 Python 脚本并附加调试器。
我有什么好工作的:
- 已创建 Dockerfile 和 docker-compose.yaml 以正确运行 docker-compose up|start。
- 我能够附加到 running docker 容器并调试我的代码。
我想得到什么?
一个按钮即可启动和附加。
我需要使用 docker-compose 启动应用程序。我不想在 VS Code 中配置 docker-run 任务。
我的代码和想法:
Dockerfile:
FROM python:3.6-alpine
RUN mkdir -p /work/
WORKDIR /work/
COPY ./python/requirements.txt ./requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
COPY ./python/src/ .
CMD python -m ptvsd --host 0.0.0.0 --port 5678 --wait run.py < tests/input.txt > tests/output.txt
docker-compose.yaml
version: "3.7"
services:
py-service:
container_name: py-container
image: py-image
build:
context: ./
volumes:
- ./python/src/:/work
ports:
- 5678:5678
launch.json 配置:
{ // simple attach to running container - works good
"name": "Python Attach",
"type": "python",
"request": "attach",
"pathMappings": [
{
"localRoot": "${workspaceFolder}/python/src/",
"remoteRoot": "/work/"
}
],
"port": 5678,
"host": "127.0.0.1"
},
{ // launch docker container and attach to debugger - NOT works
"name": "Run Py in Docker",
"type": "docker",
"request": "launch",
"platform": "python",
"preLaunchTask": "docker-compose-start",
"python": {
"pathMappings": [
{
"localRoot": "${workspaceFolder}/python/src/",
"remoteRoot": "/work/"
}
],
"projectType": "general",
"host": "127.0.0.1",
"port": 5678,
},
},
tasks.json 运行 docker-compose 命令
{
"label": "docker-compose-start",
"type": "shell",
"command": "docker-compose up"
},
问题是 Run Py in Docker 的执行正常启动了我的容器,但无法附加调试器并且超时失败。当容器仍在运行并等待附加时。可以通过某种方式解决这个问题吗?
更新
终于可以启动和调试了!这是我的task.json:
{
"label": "docker-compose-start",
"type": "shell",
"command": "docker-compose up --build -d",
"isBackground": true,
"problemMatcher": [
{
"pattern": [{ "regexp": ".", "file": 1, "location": 2, "message": 3, }],
"background": {
"activeOnStart": true,
"beginsPattern": "^(Building py-service)$",
"endsPattern": "^(Creating|Recreating|Starting) (py-container) ... (done)$",
}
},
],
},
launch.json:
{
"name": "run py",
"type": "python",
"request": "attach",
"preLaunchTask": "docker-compose-start",
"pathMappings": [
{
"localRoot": "${workspaceFolder}/python/src/",
"remoteRoot": "/work/"
}
],
"port": 5678,
"host": "127.0.0.1"
},
毕竟,将所有 docker up|build 输出显示到问题中给我带来了不便。 VS Code 每次都要求继续,但 Enter 有帮助。
【问题讨论】: