Skip to main content

Debugging Docker Containers with Logs and Exec

Debug Docker containers step by step with exit codes, logs, inspect, exec, diff, and stats to find the root cause of failures fast.

44 Terms

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 OOMKilled flag to learn why a container died.
  • Scope and search logs, including for containers stuck in a restart loop.
  • Use docker inspect to 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.

flowchart TD A[docker ps -a] -->|state and code| B{Running?} B -->|No| C[Exit code and OOMKilled] B -->|Yes| D[docker logs] C -->|then| D D -->|config question| E[docker inspect] D -->|need inside view| F[docker exec] F -->|resource issue| G[docker stats] classDef start fill:#326CE5,color:#FFFFFF classDef step fill:#DBEAFE,color:#1E293B classDef decide fill:#FFEDD5,color:#1E293B class A start class C,D,E,F,G step class B decide

Rules that save time:

  1. Exit code first. It tells you whether the process finished, failed, or was killed.
  2. Logs second. Most failures print their reason to stdout or stderr.
  3. Inspect for configuration. It shows the environment, mounts, ports, limits, and restart count the container really has, which may differ from what you intended.
  4. Exec to investigate, never to fix. Changes inside a container vanish on recreation.
  5. 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
Bash
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 code
docker 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
Bash
# 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 object
docker inspect order-worker --format '{{json .State}}' | jq
# Watch OOM and die events as they happen
docker events --filter event=oom --filter event=die

Exit 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.

Bash
docker logs payment-api # everything stored
docker logs --tail 100 payment-api # last 100 lines
docker logs -f --tail 50 payment-api # follow new output
docker logs --timestamps payment-api # prefix each line with a time
docker logs --since 30m payment-api # last 30 minutes
docker logs --since 2h --until 1h payment-api # a specific window
# stderr and stdout are separate streams, so merge them before filtering
docker 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 up
docker logs --timestamps payment-api > /tmp/payment-api.log 2>&1

Docker 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:

Bash
# Find when the container last started, then read around that time
docker inspect payment-api --format 'Started={{.State.StartedAt}} Restarts={{.RestartCount}}'
docker logs --timestamps --until "2025-01-15T14:23:00" --tail 80 payment-api
# Watch restarts happening
docker events --filter container=payment-api --filter event=start --filter event=die

If 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
Bash
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
Bash
docker exec -it payment-api sh # use bash only if the image has it
docker exec -it --user root payment-api sh # when you need package tools

Inside the container, check what the application sees:

Bash
ps aux # is the process alive, and as which user
env | sort # effective environment
ls -la /app/data # permissions on writable paths
df -h # disk space
cat /etc/resolv.conf # DNS server, 127.0.0.11 on user-defined networks
getent hosts postgres # does the service name resolve
nc -zv postgres 5432 # can it reach the port
ss -tln # what is listening

Minimal 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.

Bash
# Shares the network and process namespaces of the target container
docker run -it --rm \
--network container:payment-api \
--pid container:payment-api \
nicolaka/netshoot
# Inside: ss -tln, curl localhost:8080/health, tcpdump, dig postgres

Docker 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.

Bash
# 1. Logs persist until the container is removed
docker logs --tail 100 payment-api
# 2. What changed on disk compared with the image: A added, C changed, D deleted
docker diff payment-api
# 3. Copy files out for inspection, works on stopped containers
docker cp payment-api:/app/logs/error.log ./error.log
# 4. Start the same image with a shell instead of the app
docker run -it --rm --entrypoint sh registry.example.com/payment-api:v3.1.0
# 5. Snapshot the exact filesystem state and explore it
docker commit payment-api debug-payment-api
docker run -it --rm --entrypoint sh debug-payment-api
docker rmi debug-payment-api

Method 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
Bash
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.
Bash
# Raise limits on a running container, setting swap together to avoid an error
docker update --memory 1g --memory-swap 1g payment-api

Treat 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 inspect output, and docker stats before restarting or removing anything.
  • Scope your logs: use --tail or --since so you read minutes, not gigabytes.
  • Check OOMKilled early: 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 logs and lost on removal.
  • Limit who can exec: shell access to production containers should be audited.
Tip

When 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 inspect is the most complete source of truth about a container. Read State, Config, HostConfig, and Mounts before assuming the configuration is what you intended.

Common Mistake

Reaching for docker logs --previous. That flag does not exist in Docker. Use --timestamps with --since and --until, or watch docker events, to isolate an earlier run.

Security

docker inspect prints environment variables in plain text, and docker exec gives 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

Resources

Explore More in Docker Networking and Storage

All 5 Topics

Frequently Asked Questions

Is Debugging Docker Containers with Logs and Exec free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Debugging Docker Containers with Logs and Exec topic cover?

Debug Docker containers step by step with exit codes, logs, inspect, exec, diff, and stats to find the root cause of failures fast.

Found a mistake, an outdated step or a broken link?