如何使用PyCharm调试Docker-Compose环境中运行的进程
Great to hear your Docker Compose setup is running smoothly! Debugging a Django app inside a container with PyCharm on Mac is totally straightforward—here's how I usually configure it:
First, make sure your Django container exposes a debug port and has the right environment settings to allow remote debugging. Update your docker-compose.yml:
services: django: build: ./django command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" - "5678:5678" # Map debug port to your host environment: - DEBUG=True - ALLOWED_HOSTS=* # Or restrict to your Mac's IP for production, but * works for debugging - DEBUG_MODE=True # Custom env var to toggle debugging volumes: - ./django:/app # Your existing code mount (already working for you)
Add the PyCharm debug client to your requirements.txt (match the version to your PyCharm release—e.g., for 2023.2, use this):
pydevd-pycharm~=2023.2
Rebuild your Django image or restart the container to install it:
docker-compose up --build django
- Open PyCharm and go to Run > Edit Configurations
- Click the
+button and select Python Debug Server - Name your config (e.g., "Docker Django Debug")
- Set
Hosttohost.docker.internal(Mac Docker uses this to reach your host machine) andPortto5678(matches the port in docker-compose) - Copy the auto-generated debug snippet—you’ll need this for the next step.
Instead of hardcoding the debug setup, use the DEBUG_MODE env var to toggle it. Add this to your project’s settings.py:
import os if os.environ.get("DEBUG_MODE") == "True": import pydevd_pycharm pydevd_pycharm.settrace( "host.docker.internal", port=5678, stdoutToServer=True, stderrToServer=True, suspend=False # Set to True if you want the app to pause on startup until debugger connects )
- In PyCharm, launch your new debug server configuration (click the green bug icon next to your config name)
- Start your Docker Compose stack:
docker-compose up - Set breakpoints in your code (click the gutter next to any line in a view, model, or utility file)
- Access your Django app via
localhost:8000—when the code hits your breakpoint, PyCharm will take over, letting you inspect variables, step through execution, and debug like you would with a local app.
For a more integrated experience, skip the manual debug server setup:
- Go to Run > Edit Configurations and add a Docker Compose config
- Select your
docker-compose.ymlfile and choose thedjangoservice - Switch to the Debug tab and check "Enable debug"
- Select your pre-configured Docker Python interpreter
- Launch this config—PyCharm handles port mapping, debug client setup, and breakpoint detection automatically.
内容的提问来源于stack exchange,提问作者AlonS

