In this lesson, you will learn how to attach a debugger to a remote, containerized Python application, allowing you to inspect live state in production-like environments without manual log-scraping.
The Challenge of Distributed Systems
When your application is hidden inside a Docker container or running on a remote cloud server, standard tools like pdb (which you mastered in lesson 18) are difficult to use because they require direct access to the standard input/output stream. In a distributed system, you cannot simply open a terminal and type "continue." Instead, you must decouple the debugger’s interface from the process running the code.
Using debugpy for Remote Connection
To inspect a remote process, we use debugpy, which implements the Debug Adapter Protocol. This allows your local IDE (like VS Code or PyCharm) to act as a "controller" for the code executing on the remote server.
First, install the library in your remote environment: pip install debugpy. Then, wrap your entry point to wait for a connection:
import debugpy
# Allow the process to listen on a specific port
debugpy.listen(("0.0.0.0", 5678))
# Optional: Wait for the debugger to attach before continuing
print("Waiting for debugger attach...")
debugpy.wait_for_client()
# Your distributed service logic starts here
run_my_service()
Bridging the Gap
To make this work in a containerized environment, you must map the port defined in your code to your host machine. If you are using Docker, you would start your container with the -p 5678:5678 flag. Once the container is running, you configure your local IDE’s "Remote Attach" configuration to target localhost:5678.
Once connected, your local IDE gains full control over the remote execution context. You can set breakpoints, inspect variables, and evaluate expressions exactly as if the code were running on your machine, effectively bringing the visibility of local debugging to your remote infrastructure.
Key Takeaway: Remote debugging transforms production-like environments into interactive workspaces by using a listener to bridge your local IDE with the execution context of a remote process.