Debugging Running Containers
Learn how to debug Docker containers with docker exec, docker logs, docker inspect, and docker stats. Troubleshoot running containers effectively.
Detailed Explanation
Essential Debugging Commands
When a container misbehaves, Docker provides several commands to investigate without stopping the container.
Opening a Shell with docker exec
The most common debugging technique is opening a shell inside the running container:
docker exec -it my-app /bin/sh
For Alpine-based images, use /bin/sh since bash is not installed. For Debian/Ubuntu-based images, /bin/bash works.
Run a specific command without an interactive session:
docker exec my-app cat /etc/nginx/nginx.conf
docker exec my-app env
docker exec my-app ls -la /app
Viewing Logs with docker logs
Stream logs in real time with -f (follow):
docker logs -f --tail 200 my-app
Filter by time range for incident investigation:
docker logs --since "2024-01-15T10:00:00" --until "2024-01-15T11:00:00" my-app
Inspecting Container Details
docker inspect returns comprehensive JSON about the container:
# Get IP address
docker inspect --format '{{.NetworkSettings.IPAddress}}' my-app
# Check restart count
docker inspect --format '{{.RestartCount}}' my-app
# View environment variables
docker inspect --format '{{.Config.Env}}' my-app
Monitoring Resource Usage
Watch real-time CPU, memory, and I/O with docker stats:
docker stats --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.NetIO}}"
Use Case
Diagnosing application crashes, investigating high memory or CPU usage, checking configuration files inside containers, and auditing environment variables during security reviews.