This guide explains how to setup a Django project and Docker together for debugging sessions within VSCode. We will follow the steps detailed here. The specifics in this document are about Django but it should work all the the same for FastAPI or any dockerized Python code.
Given that you have your Django services setup like so:
command: python manage.py runserver 0.0.0.0:8000
We will use the Debug Adapter Protocol of VSCode to communicates with a debugging server that runs in Docker. For that purpose Microsoft offers an easy to use debugging server for Python called debugpy. You can install it in your dependencies or simply add it at every start debugging session. I chose the second option and added this to my docker-compose.yaml
<< : *api-def
command: ["sh", "-c", "pip install debugpy -t /tmp && python /tmp/debugpy --wait-for-client --listen 0.0.0.0:5678 manage.py runserver 0.0.0.0:8000 --nothreading --noreload"]
You can now start your application with this debugging server attached:
docker compose up debug
Then configure VSCode to use this server. Create a .vscode/launch.json file in your project containing something like this:
"name": "Remote debug",
Once done you should see a new action in your Run and Debug tab (⇧⌘D)
Then add some breakpoints where you want to stop and hit this code path and should get something like this:
Nice that works! That was quite easy wasn’t it?