Python Debugging Via VS Code In Docker Container
Introduction
Debugging is an essential part of software development, and it can be particularly challenging when working with applications running inside Docker containers. Visual Studio Code (VS Code) provides powerful debugging capabilities that can be leveraged to debug Python applications running in Docker containers.
In this blog post, we will explore how to set up Python debugging in VS Code for applications running inside Docker containers.
Example Program
This is a simple Python program with an intentional bug that we will use to demonstrate debugging in VS Code. We could insert breakpoints in the code lines marked with comments, and then use VS Code to step through the code and inspect variables to find the bug.
1 | # import debugpy |
Debugging Via Attaching To A Running Container
To start a Docker container for debugging, the Docker container has to have debugpy installed and the port for debugpy (default is 5678) has to be exposed. We can use the following command to start a Docker container with the necessary configurations for debugging:
1 | $ docker run -it --rm --gpus all -v $(pwd):/mnt -w /mnt -p 5678:5678 nvcr.io/nvidia/pytorch:26.04-py3 |
The docker container nvcr.io/nvidia/pytorch:26.04-py3, which has debugpy pre-installed, is used for quick demonstration.
To start the program for debugging in Docker container, we can use the following command to start the debugpy server and wait for the VS Code client to connect:
1 | $ python -m debugpy --listen 0.0.0.0:5678 --wait-for-client debug_math.py |
In VS Code, with our launch.json where attach and port are configured, we can start debugging by Command Palette Ctrl + Shift + D and hitting F5. This will connect to the debugpy server running in our Docker container, allowing us to set breakpoints and step through our code as if it were running locally.
Debugging In Development Container
To start the development container for debugging, we can use the Remote-Containers: Reopen in Container command via the Command Palette Ctrl + Shift + P in VS Code. This will open the current workspace inside the development container, allowing us to run and debug our code directly within the container environment.
The development container and VS Code extension setups are a little bit more complicated. The reference setup could be found in the GitHub repository for this example.
References
Python Debugging Via VS Code In Docker Container
https://leimao.github.io/blog/Python-VS-Code-Debugging-In-Docker-Container/