简体   繁体   English

Docker 容器中的 VS Code 远程调试 Python

[英]VS Code Remote Debugging Python in a Docker container

I am using VS Code's "Remove - WSL" extension to try to connect to a Docker container (backed by WSL2) running a Python job.我正在使用 VS Code 的“Remove - WSL”扩展来尝试连接到运行 Python 作业的 Docker 容器(由 WSL2 支持)。

The python job is started somewhat like this: python 作业开始有点像这样:

exec python3 -m debugpy --listen 5678 --wait-for-client some_file.py

In my docker-compose.yml file I have set在我设置的 docker-compose.yml 文件中

ports:
  - "5678:5678"

And I run the service with我运行服务

docker-compose up

My VS Code launch.json contains the following:我的 VS 代码 launch.json 包含以下内容:

    {
        "name": "Python: Remote Attach",
        "type": "python",
        "request": "attach",
        "connect": {
            "host": "localhost",
            "port": 5678
        },
        "pathMappings": [
            {
                "localRoot": "/home/myname/tensorflow_models/research",
                "remoteRoot": "/home/tensorflow/models/research"
            }
        ]
    }

However, running the above task briefly opens the debug bar and then closes it with no error message.但是,运行上述任务会短暂打开调试栏,然后在没有错误消息的情况下关闭它。

When I exec into the container I can run netcat localhost 5678 and it will return json.当我执行到容器中时,我可以运行netcat localhost 5678 ,它将返回 json。 However, it doesn't return anything when I run the same from WSL:但是,当我从 WSL 运行相同的内容时,它不会返回任何内容:

netcat localhost 5678

or on Windows from powershell:或在 powershell 的 Windows 上:

powercat -c localhost -p 5678

Or even from within the container using the container's ip:甚至使用容器的 ip 从容器内:

# Manually get ip address
ip a
# Doesn't return anything
netcat <ip> 5678

The problem was that by default debugpy only listens on localhost (local connections only).问题在于,默认情况下debugpy仅侦听localhost (仅本地连接)。 The solution was to set the listen address to 0.0.0.0 (all addresses bound to the host):解决方案是将监听地址设置为0.0.0.0 (所有地址绑定到主机):

exec python3 -m debugpy --listen 0.0.0.0:5678 --wait-for-client some_file.py

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM