Debug Django in a docker-compose container with VS Code

John Miao
2 min readJan 26, 2021

--

I used to use PyCharm Professional to debug my Django projects in a Mac, but now I have to use a Windows PC on my work. However the PyCharm isn’t working very well with WSL2, or at least I couldn’t figure out how. So I turned into VS Code.

VS Code is great, only I couldn’t debug my Django project in a docker container like I did with PyCharm at the beginning. I googled a lot but there is just no a tip to fit my need. Finally I figured it out and I want to write it down to share the way if you have the same needs as mine.

Assuming you know docker very well and have a Dockerfile already.

First the normal docker-compose.yml file

version: "3"services:  backend:    image: django-web    command: bash -c "python ./manage.py migrate && python ./manage.py runserver 0.0.0.0:8000"...

Then for the debugging, you will need a docker-compose-debug.yml file (the whole idea is that command line)

version: '3'services:  backend:    command: ["sh", "-c", "pip install debugpy -t /tmp && python ./manage.py migrate && python /tmp/debugpy --wait-for-client --listen 0.0.0.0:5678 ./manage.py runserver 0.0.0.0:8000"]    ports:      - 8000:8000      - 5678:5678

Then you need to add a debug config in the launch.json file

{  "version": "0.2.0",  "configurations": [{     "name": "Python: Remote Attach",     "type": "python",     "request": "attach",     "connect": {         "host": "localhost",         "port": 5678      },    "pathMappings": [{        "localRoot": "${workspaceFolder}",        "remoteRoot": "/app"     }],    "django": true,},

Then that’s it. You can now debug with command:

docker-compose -f docker-compose.yml -f docker-compose-debug.yml up --build

Wait for the service to finish starting up and then hit F5 in VS Code and it should work.

If no debug, simply go with

docker-compose up --build

Conclusion

Benefits of this way is that:

  1. You don’t need to add any extra debug code into your source code.
  2. The Django hot reload works! No More --noreload --nothreading!

It should work in Mac and Linux too but I didn’t test.

--

--

John Miao
John Miao

Responses (3)