How to debug a Docker container
Topic: Containers core
Summary
Inspect a running or exited container with docker logs, docker exec, and docker inspect. Check exit code, environment, and resource usage. Use this when a container fails to start, exits unexpectedly, or when you need to see what is running inside.
Intent: How-to
Quick answer
- Logs: docker logs container_name; docker logs -f container_name to follow. Exit code: docker inspect container_name --format '{{.State.ExitCode}}'. If exit code non-zero, check logs and the command that was run.
- Shell inside container: docker exec -it container_name sh (or bash if available). Run ps, cat /etc/os-release, check processes and files. Use docker exec to run one-off commands: docker exec container_name cat /app/config.json.
- Inspect: docker inspect container_name for full config (env, mounts, network). Resource usage: docker stats container_name. If container exits immediately, ensure the main process does not exit (use a long-running CMD or tail -f).
Prerequisites
Steps
-
Check logs and exit code
docker logs mycontainer; docker logs -f mycontainer. docker inspect mycontainer --format '{{.State.ExitCode}}' and '{{.State.Error}}'. Fix the command or config that caused the failure.
-
Exec into container
docker exec -it mycontainer sh. If container is stopped, run a new temporary container with same image and volume: docker run -it --rm -v myvol:/data myimage sh to inspect volume.
-
Inspect config and resources
docker inspect mycontainer for env, mounts, network. docker stats mycontainer for CPU and memory. Check if OOM killed: docker inspect --format '{{.State.OOMKilled}}' mycontainer.
-
Common fixes
Exits immediately: CMD may be wrong or process exits; use tail -f /dev/null or a proper daemon. Cannot connect: check network and port mapping; check process listens on 0.0.0.0. Permission: fix volume or file ownership.
Summary
Use docker logs, docker exec, and docker inspect to debug containers. Use this when a container fails to start or behave as expected.
Prerequisites
Steps
Step 1: Check logs and exit code
View logs and inspect exit code and error message; fix the underlying cause.
Step 2: Exec into container
Use docker exec to get a shell or run commands inside a running container; use a temporary container to inspect volumes if the main container is stopped.
Step 3: Inspect config and resources
Use docker inspect and docker stats to see config and resource usage; check for OOM.
Step 4: Common fixes
Address common issues: wrong CMD, network or port config, and permissions.
Verification
- You can determine why a container failed or how it is configured; fixes are applied and the container runs as expected.
Troubleshooting
No logs — Process may not write to stdout; check log files inside the container. exec fails — Container may be stopped; use docker run with the same image and volumes to debug.