作者:E4b9a6, 创建:2023-02-06, 字数:2372, 已阅:77, 最后更新:2024-03-10
Docker运行非常方便,但Debug相对复杂,尤其是遇到一些在容器内独有的Bug时往往比较棘手
下面以uvicorn
的web服务为例搭配VS Code
,实践为容器Python应用进行Debug
创建一个hello-world的uvicorn项目,目录结构如下
➜ debugpy tree -I __pycache__ -I venv
.
├── Dockerfile
├── requirements.txt
└── web
└── __init__.py
__init__.py
文件内容如下
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
message = "Hello World"
return {"message": message}
VSCode的Debug配置单.launch.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,成功触发断点如下
添加一个Dockerfile
文件如下,CMD-1是正常运行uvicorn
应用的指令,CMD-2用于远程调试uvicorn
应用的指令
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"]
打包镜像并运行容器
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
调试配置如下
{
"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,成功触发断点如下