Overview and What You Will Learn
To debug a Docker container, work in a fixed order: check the state and exit code, read the logs, inspect the configuration, then investigate from inside the container or check resource use. Each step narrows the problem, and following the order beats restarting the container and hoping.
In this lab you will:
- Read exit codes and the
OOMKilledflag to learn why a container died. - Scope and search logs, including for containers stuck in a restart loop.
- Use
docker inspectto read the configuration the container actually has. - Investigate from the inside with
docker exec, including images without a shell. - Debug a container that has already stopped, and diagnose memory and CPU problems.
Why This Matters in Production
During an incident, restarting a container destroys information. Memory pressure, a half-written file, or a connection state may be the clue, and a restart erases the evidence. Engineers who gather the exit code, logs, and inspect output first can name the cause in minutes and fix it once, instead of fixing symptoms repeatedly.
Think of a video platform at peak traffic, or a payments API at month end: the container that fails is usually failing for a boring reason, such as a missing environment variable, a memory limit, or a dependency that is unreachable. A repeatable routine finds those reasons quickly.
Core Principles
Start with what Docker already knows, and only go inside the container when the outside view is not enough.
Rules that save time:
- Exit code first. It tells you whether the process finished, failed, or was killed.
- Logs second. Most failures print their reason to stdout or stderr.
- Inspect for configuration. It shows the environment, mounts, ports, limits, and restart count the container really has, which may differ from what you intended.
- Exec to investigate, never to fix. Changes inside a container vanish on recreation.
- Preserve evidence before cleanup. Save logs and inspect output before you remove or recreate anything.
Detailed Step-by-Step Practical Lab
How to Read Exit Codes and Find OOM Kills
docker ps -a --format "table {{.Names}}\t{{.Status}}" # payment-api Exited (1) 5 minutes ago# db-migrator Exited (0) 10 minutes ago# order-worker Exited (137) 2 minutes ago # Find every container that exited with a given codedocker ps -a --filter "exited=137"| Exit code | Meaning | First step |
|---|---|---|
| 0 | Process finished normally | Fine for jobs, wrong for servers |
| 1 | Application error | Read the logs |
| 125 | Docker daemon error on docker run |
Read the error text, check flags |
| 126 | Command found but not executable | Fix file permissions |
| 127 | Command not found | Check CMD and ENTRYPOINT paths |
| 137 | SIGKILL (OOM kill or docker kill) |
Check OOMKilled |
| 139 | Segmentation fault | Application or native library bug |
| 143 | SIGTERM (normal docker stop) |
Usually not an error |
# Was it killed for exceeding its memory limit?docker inspect order-worker --format 'OOMKilled={{.State.OOMKilled}} ExitCode={{.State.ExitCode}} Error={{.State.Error}}' # The full state objectdocker inspect order-worker --format '{{json .State}}' | jq # Watch OOM and die events as they happendocker events --filter event=oom --filter event=dieExit 137 does not always mean memory. If OOMKilled is false, something sent SIGKILL, such as docker kill, a stop timeout, or an external script.
How to Read and Search Logs
docker logs reads the stored output of the container's main process. It works with the json-file, local, and journald drivers, and with many remote drivers through a local cache.
docker logs payment-api # everything storeddocker logs --tail 100 payment-api # last 100 linesdocker logs -f --tail 50 payment-api # follow new outputdocker logs --timestamps payment-api # prefix each line with a timedocker logs --since 30m payment-api # last 30 minutesdocker logs --since 2h --until 1h payment-api # a specific window # stderr and stdout are separate streams, so merge them before filteringdocker logs payment-api 2>&1 | grep -iE "error|fatal|exception"docker logs payment-api 2>&1 | grep -c "connection refused" # Keep a copy for your team before cleaning updocker logs --timestamps payment-api > /tmp/payment-api.log 2>&1Docker has no --previous flag. That belongs to kubectl. A container with a restart policy keeps the same log stream across restarts, so earlier runs are in the same output. To isolate one crash:
# Find when the container last started, then read around that timedocker inspect payment-api --format 'Started={{.State.StartedAt}} Restarts={{.RestartCount}}'docker logs --timestamps --until "2025-01-15T14:23:00" --tail 80 payment-api # Watch restarts happeningdocker events --filter container=payment-api --filter event=start --filter event=dieIf logs are empty, confirm the app writes to stdout and stderr rather than to a file, and check the logging driver with docker inspect payment-api --format '{{.HostConfig.LogConfig.Type}}'.
How to Inspect Configuration
docker inspect payment-api --format '{{.Config.Image}}'docker inspect payment-api --format '{{range .Config.Env}}{{println .}}{{end}}'docker inspect payment-api --format '{{json .NetworkSettings.Ports}}'docker inspect payment-api --format '{{range .Mounts}}{{.Type}} {{.Source}} -> {{.Destination}}{{println}}{{end}}'docker inspect payment-api --format 'Policy={{.HostConfig.RestartPolicy.Name}} Restarts={{.RestartCount}}'docker inspect payment-api --format 'Memory={{.HostConfig.Memory}} NanoCpus={{.HostConfig.NanoCpus}}'docker inspect payment-api --format '{{range $name, $net := .NetworkSettings.Networks}}{{$name}}: {{$net.IPAddress}}{{println}}{{end}}'docker inspect payment-api --format 'Created={{.Created}} Started={{.State.StartedAt}}'Memory is in bytes, so 536870912 is 512 MiB, and NanoCpus of 1500000000 is 1.5 CPUs. Environment values, including passwords, are shown in plain text.
How to Investigate Inside a Running Container
docker exec -it payment-api sh # use bash only if the image has itdocker exec -it --user root payment-api sh # when you need package toolsInside the container, check what the application sees:
ps aux # is the process alive, and as which userenv | sort # effective environmentls -la /app/data # permissions on writable pathsdf -h # disk spacecat /etc/resolv.conf # DNS server, 127.0.0.11 on user-defined networksgetent hosts postgres # does the service name resolvenc -zv postgres 5432 # can it reach the portss -tln # what is listeningMinimal images may lack nc, curl, or even a shell. Alpine images ship BusyBox tools, but not curl.
How to Debug Images Without a Shell
Distroless and scratch images have no shell, so docker exec fails. Attach a debugging container that shares the target's namespaces instead.
# Shares the network and process namespaces of the target containerdocker run -it --rm \ --network container:payment-api \ --pid container:payment-api \ nicolaka/netshoot # Inside: ss -tln, curl localhost:8080/health, tcpdump, dig postgresDocker Desktop also provides docker debug <container> for the same purpose, where available.
How to Debug a Container That Has Stopped
docker exec needs a running container, so use these methods for one that has exited.
# 1. Logs persist until the container is removeddocker logs --tail 100 payment-api # 2. What changed on disk compared with the image: A added, C changed, D deleteddocker diff payment-api # 3. Copy files out for inspection, works on stopped containersdocker cp payment-api:/app/logs/error.log ./error.log # 4. Start the same image with a shell instead of the appdocker run -it --rm --entrypoint sh registry.example.com/payment-api:v3.1.0 # 5. Snapshot the exact filesystem state and explore itdocker commit payment-api debug-payment-apidocker run -it --rm --entrypoint sh debug-payment-apidocker rmi debug-payment-apiMethod 4 reproduces missing binaries and wrong permissions. Methods 2, 3, and 5 show what the crashed run itself changed.
How to Diagnose Memory and CPU Problems
docker stats --no-stream --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.MemPerc}}\t{{.PIDs}}"# NAME CPU % MEM USAGE / LIMIT MEM % PIDS# payment-api 45.2% 420MiB / 512MiB 82.0% 31- MEM % above 85: an OOM kill is close. Raise the limit or find the leak.
- CPU % stuck near the limit: the process is CPU-bound or looping, and may be throttled.
- PIDS climbing: the app is leaking child processes or threads.
# Raise limits on a running container, setting swap together to avoid an errordocker update --memory 1g --memory-swap 1g payment-apiTreat a raised limit as a stopgap. Fix the leak in the application and set the new limit in your deployment configuration.
Production Best Practices & Common Pitfalls
- Collect before you cure: save logs,
docker inspectoutput, anddocker statsbefore restarting or removing anything. - Scope your logs: use
--tailor--sinceso you read minutes, not gigabytes. - Check
OOMKilledearly: it explains exit 137 faster than any log line. - Make fixes in the image or configuration: never rely on a change made through
docker exec. - Add health checks and structured logs: they turn guesswork into evidence next time.
- Log to stdout and stderr: logs written to files inside the container are invisible to
docker logsand lost on removal. - Limit who can exec: shell access to production containers should be audited.
TipWhen a container is stuck restarting, run
docker events --filter container=<name>in one terminal and watch the start and die events with timestamps while you read the logs around the same times.
Remember
docker inspectis the most complete source of truth about a container. ReadState,Config,HostConfig, andMountsbefore assuming the configuration is what you intended.
Common MistakeReaching for
docker logs --previous. That flag does not exist in Docker. Use--timestampswith--sinceand--until, or watchdocker events, to isolate an earlier run.
Security
docker inspectprints environment variables in plain text, anddocker execgives a shell with the container user's rights, often root. Log both, restrict them on production hosts, and never paste raw inspect output into public tickets.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
docker ps -a |
State and exit code of every container |
docker inspect <n> --format '{{.State.OOMKilled}}' |
Check for an OOM kill |
docker logs --tail 100 --timestamps <n> |
Recent logs with times |
docker exec -it <n> sh |
Shell inside a running container |
docker diff <n> |
Files changed since the image |
docker cp <n>:/path ./path |
Copy files out of a container |
docker events --filter container=<n> |
Live lifecycle events |
docker stats --no-stream |
Resource snapshot |
| Problem | Likely cause | Fix |
|---|---|---|
| Exit 127 | CMD binary missing in image |
Check paths with docker run --rm --entrypoint sh |
Exit 137 with OOMKilled=true |
Memory limit too low or leak | Raise limit, then fix the leak |
| Empty logs | App logs to a file | Log to stdout and stderr |
exec: "bash": not found |
Minimal image | Use sh or a debug container |
| Cannot reach another container by name | Default bridge or different network | Use a user-defined network |
permission denied writing data |
Non-root user, root-owned path | chown during the build, before USER |