At Trustyou, we are dockerizing our Fastapi projects for all the steps from linting, mypy, black... Moreover we use docker-compose to run some tests as well as the application locally. And there is a question raised, how could we to debug our application?
Our requirements:
- Running Fastapi application using docker-compose
- Be able to debug application
- Auto reload
There are some guides out their but in this tutorial I would like to simplify it and go step by step with you.
Setup
Setup "Run and Debug"
We need to create a configuration file .vscode/launch.json
. This file contains information for Run and Debug
tab. We can add this file to git but ignoring all order files in .vscode
folder.
File: .vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Remote Attach",
"type": "python",
"request": "attach",
"port": 5678,
"host": "localhost",
"pathMappings": [
{
"localRoot": "${workspaceFolder}",
"remoteRoot": "/code"
}
]
}
]
}
Create docker-compose.debug.yml file
This file is quite similar to our docker-compose.yml, except it expose port 5678. This port is used by debugpy, vscode debugger will communicate with container via this port.
File: docker-compose.debug.yml
version: '3.4'
services:
fastapi-vscode-debug-setup:
image: fastapi-vscode-debug-setup
build:
context: .
dockerfile: ./Dockerfile
volumes:
- ./hello_world:/code/hello_world
command: ["sh", "-c", "pip install debugpy -t /tmp && python /tmp/debugpy --wait-for-client --listen 0.0.0.0:5678 -m uvicorn hello_world.main:app --host 0.0.0.0 --port 8000 --reload"]
environment:
- APP_MESSAGE=Hello debugger
ports:
- 8000:8000
- 5678:5678
After we have everything is set up. Now it time to debug our application.
Debugging
- Start docker-compose debugging by: Right click on
docker-compose.debug.yml
file and clickCompose Up
. You can also run commanddocker compose -f docker-compose.debug.yml up
. They are both the same - Go to
Run and Debug
, selectPython: Remote Attach
and clickStart Debugging
button - If there is nothing wrong, the debugger will connect to container and you can add a break point to test it π. For example, I added a breakpoint to
main.py
and access http://localhost:8000, you would expect something similar to image happens
If you want to stop debugging, Right click on
docker-compose.debug.yml
file and clickCompose Down
or stop docker compose from your termimal
This can be applied to not only Fastapi/Python project but also for other projects. You could check them here
You can check all the code in this repository https://github.com/duynguyenhoang/fastapi-vscode-debug-setup
Read more:
Top comments (0)