How to debug Python apps inside a Docker Container with VS Code
Learn how you can use a debugger in VS Code inside a Docker Container to debug Python apps.
This article shows how you can can use a debugger in VS Code to debug Python apps inside a Docker Container.
#more
Step 1: Add debugpy¶
First, we need to add debugpy. An implementation of the Debug Adapter Protocol for Python maintained by Microsoft.
We can install it with
pip install debugpy
Then add this code snippet at the top of your code:
import debugpy
debugpy.listen(("0.0.0.0", 5678))
Optionally, we can also add these lines to wait with script execution until we've attached VS Code.
print("Waiting for client to attach...")
debugpy.wait_for_client()
Step 2: Run the container¶
Now, run the container and map the port:
docker run -p 5678:5678 your_image
Or if you use docker-compose
:
services:
app:
...
ports:
- 5678:5678
...
Step 3: Open VS Code and connect Debugger¶
In VS Code, click on Run -> Add Configuration -> Remote Attach
and then leave the default configuration as localhost and port 5678.
This creates a launch.json
file inside the .vscode
folder that tells the debugger to attach to port 5678 where the remote debug server is running.
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: Remote Attach",
"type": "python",
"request": "attach",
"connect": {
"host": "localhost",
"port": 5678
},
"pathMappings": [
{
"localRoot": "${workspaceFolder}",
"remoteRoot": "."
}
],
"justMyCode": true
}
]
}
You can now set breakpoints and then click on Run -> Start Debugging
to start the debugging session. Enjoy!
Tip
This works with VS Code when running it on the host machine, but you can also connect VS Code to your running container and debug inside the container!
Further Resources¶
- Article: Debugging for Dockerized ML applications in Python
- Talk: Best Practices for Compose-managed Python Apps
FREE VS Code / PyCharm Extensions I Use
✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*
Python Problem-Solving Bootcamp
🚀 Solve 42 programming puzzles over the course of 21 days: Link*