最近我开始为我的项目使用docker,运行以下
Django以前设置调试器很容易,但在使用docker compose后,我无法做到这一点。一旦我启动调试器,它就会加载一段时间,然后自动停止,任何地方都没有日志或错误。这是相关代码。
launch.json
{
"configurations": [
{
"name": "Python: Remote Attach",
"type": "python",
"request": "attach",
"connect": {
"host": "localhost",
"port": 443
},
"pathMappings": [
{
"localRoot": "${workspaceFolder}",
"remoteRoot": "."
}
]
}
]
}
docker-compose.yml
version: '3'
services:
db:
image: postgres:12
env_file: .env
environment:
- POSTGRES_DB=${DB_NAME}
- POSTGRES_USER=${DB_USER}
- POSTGRES_PASSWORD=${DB_PASSWORD}
ports:
- "5431:5432"
volumes:
- dbdata:/var/lib/postgresql/data
nginx:
image: nginx:1.14
ports:
- "443:443"
- "80:80"
volumes:
- ./config/nginx/:/etc/nginx/conf.d
- ./myapp/static:/var/www/myapp.me/static/
web:
restart: always
build: ./myapp
command: bash -c "
python manage.py collectstatic --noinput
&& python manage.py makemigrations
&& python manage.py migrate
&& gunicorn --certfile=/etc/certs/localhost.crt --keyfile=/etc/certs/localhost.key myapp.wsgi:application --bind 0.0.0.0:443 --reload"
expose:
- "443"
depends_on:
- db
- nginx
env_file:
- .env
volumes:
- ./myapp:/opt/myapp
- ./config/nginx/certs/:/etc/certs
- ./myapp/static:/var/www/myapp.me/static/
broker:
image: redis:alpine
expose:
- "6379"
celery:
build: ./myapp
command: celery -A myapp worker -l info
env_file:
- .env
volumes:
- ./myapp:/opt/myapp
depends_on:
- broker
- db
celery-beat:
build: ./myapp
command: celery -A myapp beat -l info
env_file:
- .env
volumes:
- ./myapp:/opt/myapp
depends_on:
- broker
- db
volumes:
dbdata:
最后我自己解决了这个问题。从这个问题中几乎没有什么收获。
您需要使用debugpy并将其放在manage.py文件中才能开始侦听端口。我做了类似的事情
import debugpy
debugpy.listen(('0.0.0.0', 5678))
debugpy.wait_for_client()
debugpy.breakpoint()
除此之外,我们还需要将此端口映射到主机内部的端口。为此,我们需要在docker compose 的web服务中更改并添加一行
ports:
- "5678:5678"
我的launch.json看起来像这个
{
"configurations": [
{
"name": "Python: Remote Attach",
"type": "python",
"request": "attach",
"connect": {
"host": "0.0.0.0",
"port": 5678
},
"pathMappings": [
{
"localRoot": "${workspaceFolder}/myapp",
"remoteRoot": "."
}
]
}
]
}
注意:请确保您的需求文件中有debugpy,或者手动安装它。
如果您将调试器作为一个模块,则可以使用环境变量打开和关闭它。我只是把这篇文章作为fastapi/gunicorn调试解决方案的基础。
# debugger.py
from os import getenv
def initialize_flask_server_debugger_if_needed():
if getenv("DEBUGGER") == "True":
import multiprocessing
if multiprocessing.current_process().pid > 1:
import debugpy
debugpy.listen(("0.0.0.0", 10001))
print("⏳ VS Code debugger can now be attached, press F5 in VS Code ⏳", flush=True)
debugpy.wait_for_client()
print("� VS Code debugger attached, enjoy debugging �", flush=True)
参见Adrian的这篇文章:VS代码中的Flask调试