menu E4b9a6's blog
rss_feed
E4b9a6's blog
有善始者实繁,能克终者盖寡。

Docker容器的Debug调试(Python)

作者:E4b9a6, 创建:2023-02-06, 字数:2372, 已阅:77, 最后更新:2024-03-10

这篇文章更新于 256 天前,文中部分信息可能失效,请自行甄别无效内容。

Docker运行非常方便,但Debug相对复杂,尤其是遇到一些在容器内独有的Bug时往往比较棘手

下面以uvicorn的web服务为例搭配VS Code,实践为容器Python应用进行Debug

创建一个hello-world的uvicorn项目,目录结构如下

Bash
➜  debugpy tree -I __pycache__ -I venv
.
├── Dockerfile
├── requirements.txt
└── web
    └── __init__.py

__init__.py文件内容如下

Python
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    message = "Hello World"
    return {"message": message}

VSCode的Debug配置单.launch.json如下

JSON
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python: Uvicorn",
      "type": "python",
      "request": "launch",
      "python": "${workspaceFolder}/venv/bin/python",
      "module": "uvicorn",
      "console": "internalConsole",
      "env": {},
      "args": ["web:app", "--port=5000"]
    }
  ]
}

F5启动调试,设置断点后访问localhost:5000,成功触发断点如下

download.png

添加一个Dockerfile文件如下,CMD-1是正常运行uvicorn应用的指令,CMD-2用于远程调试uvicorn应用的指令

Docker
FROM python:3.7.4-slim-stretch

WORKDIR /app

COPY ./ /app

RUN apt update && \
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
pip3 install -r /app/requirements.txt

# CMD-1 正常运行的指令
# CMD ["uvicorn", "web:app", "--host=0.0.0.0", "--port=5000"]

# CMD-2 安装debugpy支持远程DEBUG的指令
CMD ["sh", "-c", "pip install debugpy -t /tmp && python /tmp/debugpy --wait-for-client --listen 0.0.0.0:5678 -m uvicorn web:app --host 0.0.0.0 --port 5000 --reload"]

打包镜像并运行容器

Bash
sudo docker build -t debugpy:v23.02.01 .
sudo docker run -p 25000:5000 -p 15678:5678 debugpy:v23.02.01

修改.launch.json文件,增加Remote Attach调试配置如下

JSON
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python: Uvicorn",
      "type": "python",
      "request": "launch",
      "python": "${workspaceFolder}/venv/bin/python",
      "module": "uvicorn",
      "console": "internalConsole",
      "env": {},
      "args": ["web:app", "--port=5000"]
    },
    {
      "name": "Python: Remote Attach",
      "type": "python",
      "request": "attach",
      "port": 15678,
      "host": "localhost",
      "pathMappings": [
        {
          "localRoot": "${workspaceFolder}",
          "remoteRoot": "/app"
        }
      ]
    }
  ]
}

选择Python: Remote Attach启动调试,设置断点后访问localhost:25000,成功触发断点如下

download _1_.png


[[replyMessage== null?"发表评论":"发表评论 @ " + replyMessage.m_author]]

account_circle
email
web_asset
textsms

评论列表([[messageResponse.total]])

还没有可以显示的留言...
gravatar
[[messageItem.m_author]] [[messageItem.m_author]]
[[messageItem.create_time]]
[[getEnviron(messageItem.m_environ)]]
[[subMessage.m_author]] [[subMessage.m_author]] @ [[subMessage.parent_message.m_author]] [[subMessage.parent_message.m_author]]
[[subMessage.create_time]]
[[getEnviron(messageItem.m_environ)]]