使用debugpy和vs代码在docker容器中调试python导致超时/连接被拒绝 launch.json Dockerfile docker-compose.yaml tasks.json

问题描述

我正在尝试使用debugpy为在docker中运行的python脚本的Visual Studio Code设置本机调试。理想情况下,我只想按F5并继续前进(如果需要,包括构建阶段)。当前,我在VS代码编辑器本身内嵌的items引起的超时(发生了异常:RuntimeError等待适配器连接超时)或连接被拒绝之间反弹。

我从Microsoft提供的文档中创建了launch.json:

launch.json

items

到目前为止,构建图像的方式如下:

Dockerfile

debugpy.listen(5678)

我发现一些示例尝试使用docker-compose.yaml进行简单处理,但是我不确定目前是否需要使用该示例。

docker-compose.yaml

{
    "version": "0.2.0","configurations": [
        {
            "name": "Attach to Integration (test)","type": "python","request": "attach","pathMappings": [
                {
                    "localRoot": "${workspaceFolder}/test","remoteRoot": "/test"
                }
            ],"port": 5678,"host": "127.0.0.1"
        }
    ]
}

我基于CLI命令FROM python:3.7-slim-buster as base RUN apt-get -y update; apt-get install -y vim git cmake workdir / RUN mkdir .cache src in out config log copY requirements.txt . RUN pip install -r requirements.txt; rm requirements.txt #! Todo: config folder needs to be a mapped volume so they can change creds without rebuild workdir /src copY test ../test copY config ../config copY src/ . #? D E B U G I M A G E FROM base as debug RUN pip install debugpy CMD python -m debugpy --listen 0.0.0.0:5678 ../test/edu.employer._test.py #! P R O D U C T I O N I M A G E # FROM base as prod # CMD [ "python","/test/edu.employer._test.py" ]

脚本的“关键”部分只是监听并等待bugger:

services:
    tester:
        container_name: tester
        image: employer/test:1.0.0
        build:
            context: .
            target: debug
            dockerfile: test/edu.employer._test.Dockerfile

        volumes:
            - ./out:/out
            - ./.cache:/.cache
            - ./log:/log

        ports:
            - 5678:5678

screenshot

解决方法

您必须使用以下命令配置调试器:debugpy.listen(("0.0.0.0",5678))

之所以会这样,是因为默认情况下,debugpy在本地主机上进行监听。如果您的Docker容器位于另一台主机上,则必须添加0.0.0.0

,

结果是我需要创建一个task.json文件并提供有关运行映像的详细信息...

tasks.json

deletePlayerHistory()

并定义一个preLaunchTask:

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0","tasks": [
        {
            "type": "docker-run","label": "docker-run: debug","dependsOn": ["docker-build"],"dockerRun": {
                "image": "employer/test:1.0.0"
                // "env": {
                //   "FLASK_APP": "path_to/flask_entry_point.py"
                // }
            },"python": {
              "args": [],"file": "/test/edu.employer._test.py"
            }
        }
    ]
}