Module 8 Lesson 4: Debugging in Containers
See what's happening inside. Learn how to use 'exec', logs, and remote debuggers to troubleshoot applications running inside Docker containers.
Module 8 Lesson 4: Debugging in Containers
When your app crashes inside a container, you can't just "Look" at it easily. You need specific tools to peer through the "Walls" of the container.
1. The "Interactive Shell" (docker exec)
This is your #1 tool. It allows you to enter a running container and run commands like ls, env, or cat to see what went wrong.
docker exec -it my-app bash
# or for small images like alpine
docker exec -it my-app sh
What to check inside:
- Config:
cat .envorenv(Are the variables correct?) - Files:
ls -la(Are the files in the right folder? Do they have the right permissions?) - Connectivity:
ping database(Can this container see the DB?)
2. Advanced Logging
If your app won't even start, you can't exec into it. You must use logs.
docker logs <id>: Show the history.docker logs --tail 50 <id>: Just the last 50 lines.docker logs -t <id>: Show Timestamps (Critical for syncing app logs with database errors).
3. Remote Debugging (Connecting your IDE)
Modern IDEs (VS Code, GoLand, PyCharm) allow you to connect their Visual Debugger to a process running inside a container.
- Expose a Debug Port: Launch your container with an extra port (e.g.,
-p 9229:9229for Node.js). - Start in Debug Mode: Change your app's start command (e.g.,
node --inspect=0.0.0.0 app.js). - Attach IDE: In VS Code, use a
launch.jsonconfiguration to "Attach" to that port. - Profit: You can now set Breakpoints in your local code, and the container will "Pause" when it hits them!
4. Inspecting Metadata
Sometimes the problem isn't the app; it's the Docker configuration.
docker inspect <id>
Look for:
- Mounts: Is the volume actually mounted to the right place?
- NetworkSettings: What is the IP address?
- State: Why did it exit? (Check the
ErrorandExitCode).
Exercise: The Mystery Crash
Scenario: Your Python app keeps exiting with a ModuleNotFoundError.
- List all containers (including stopped ones). Found it?
- Run
docker logs. What is the exact name of the missing module? - "Jump inside" a temporary instance of that image:
docker run -it my-image sh. - Run
pip list. Is the library there? - Check your
Dockerfile. Did you forget toCOPY requirements.txtbefore runningpip install? - How would you use
docker inspectto verify that yourrequirements.txtwas actually copied into the/appfolder?
Summary
Debugging in Docker is a two-step process: First, look at the Metadata (Logs and Inspect). Second, look at the Internal State (Exec). Mastering these tools turns "Invisible bugs" into solvable problems.
Next Lesson: Final polishing: Development vs. Production Dockerfiles.