For beginners who have recently started using Python in Docker, debugging can be quite complex. This detailed and easy-to-understand guide will help you learn and apply basic debugging techniques in Docker containers.
Docker makes deployment of Python applications much more reliable by encapsulating environments. But this also introduces a big challenge for beginners in debugging in those isolated containers. It is obviously a difficult task to fix something inside a closed container when you cannot find or see it, and try to fix it with your usual tools.
In this article, we will understand how new data science professionals can debug Python apps in Docker.
Why is Debugging Inside Docker Different?
First, let us understand how debugging is different inside a Docker container. Usually, debugging Python applications is a straightforward process when done locally.
You can instantly see errors, edit the code quickly, rerun it, and test again with the help of usual tools like debuggers, IDEs, and logs.
But debugging inside Docker works quite differently.
Containers work in an isolated environment and have their own file systems, dependencies, and processes. This makes it hard to trace the errors and view outputs in real time.
Even doing a small code change will require rebuilding the image and restarting the container from scratch, which obviously will slow down the feedback loop.
This isolation creates a disconnect that makes diagnosing issues inside Docker very difficult for beginners.
Understanding the Example
First, let us start with a Buggy Python Sample. Let’s craft a simple program with an obvious bug:
app.py
def calculate_sum(numbers):
total = 0
for num in numbers:
total += num
print(f"Adding {num}, total is now {total}")
return total
def main():
numbers = [1, 2, 'three', 4, 5] # 'three' causes a TypeError
result = calculate_sum(numbers)
print(f"Final result: {result}")
if name == 'main':
main()
This code will blow up when it tries to add an integer and a string. Thus, this example is ideal for hands-on debugging.
1.Containerize the Code
Create a Docker file
FROM python:3.11-slim
WORKDIR /app
COPY app.py .
CMD ["python", "app.py"]
Build and run:
docker build -t debug-demo .
docker run debug-demo
You’ll see the TypeError, but no interactive way to inspect variables or the call stack inside the container environment.
2. Add debugpy for Remote Debugging
Install and integrate debugpy:
• Add to your app
import debugpy
debugpy.listen(("0.0.0.0", 5678))
print("Waiting for debugger to attach...")
debugpy.wait_for_client()
• Update Dockerfile
RUN pip install debugpy
CMD ["python", "app.py"]
• Run the container
docker run -p 5678:5678 debug-demo
•In your editor, for example, VS Code or anything that you are using, create a launch.json configuration to attach to the debug port and start debugging.
You can also set breakpoints, inspect variables, and step through code inside the container.
3. Use VS Code Dev Containers
VS Code’s Dev Container functionality (via a devcontainer.json) helps data science professionals to develop inside an environment matching their container setup, making debugging effortless. It supports rich integration with build, run, and debugging workflows.
4. Use breakpoint() + docker attach
You can use breakpoint() that offers simplicity, and then run the container interactively.
docker run -it debug-demo
The execution will pause at breakpoint(), giving you a REPL inside the container. From another terminal, run:
docker attach
This drops you into an interactive debugging session, quick and no-frills.
5. Add Logging and Print Debugging
Even within Docker, simple print() statements or Python’s logging module can help trace execution. Especially for logic issues, prints often catch 80% of bugs fast. Use:
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("Current value of total: %s", total)
It logs context-rich info and lets you control verbosity better than raw print()
6. Mount Code for Live Debugging
For faster iteration, mount your local code into the container so edits reflect immediately:
docker run -v "$(pwd)":/app -w /app debug-demo
Combine this with debugpy for hot-reload debugging without rebuilding the image each time. VS Code workflows support this through volumes defined within tasks.json
7. Combine with Container Tools for a Smooth Workflow
• Docker Compose: Define your app and debug port mapping in docker-compose.yml for ease of use.
• Efficient Dockerfile practices: Use slim or Alpine-based images for faster builds and smaller footprints
• Logging strategy: Route logs to stdout/stderr so Docker can capture them cleanly.
We highly recommend enrolling in the best data science certifications to master these coding and data science skills and give your career an edge over others.
Conclusion
Though debugging a Python application in a Docker container can be challenging, it isn’t impossible for beginners, but it requires a different approach. You can start by mastering print debugging and breakpoint(). Then go for learning powerful tools like debugpy and VS Code’s container support as you progress in your coding skills. Through this, you can enjoy flexibility and confidence. Once you have learned how to peek inside the code in a container, you will be able to work easily on container-based development smoothly and confidently.
Top comments (0)