Debugging Containers
When a container misbehaves, guessing is slow. Work from the outside in: is it running? what did it say? how is it configured? what does it see from the inside? Each question has a command.
| Question | Command |
|---|---|
| Is it running, restarting, exited? With which exit code? | docker ps -a |
| What did it print? | docker logs --tail 100 <name> |
| Was it OOM-killed? Health status? | docker inspect --format '{{json .State}}' <name> |
| Which env, mounts, ports, command does it really have? | docker inspect <name> |
| What does the filesystem look like inside? | docker exec -it <name> sh / docker debug <name> |
| What changed since start? | docker diff <name> |
| What is the daemon doing? | docker events --since 10m |
Triage by symptom
Most problems fall into a few patterns. This helper encodes the usual first diagnosis from the information docker ps and docker logs give you:
def triage(status, exit_code=None, oom=False, log_tail=""):
log = log_tail.lower()
if status == "restarting":
return "crash loop: read `docker logs`; the restart policy is hiding the crash"
if status == "exited":
if oom or exit_code == 137:
return "killed (OOM or SIGKILL): check State.OOMKilled, raise --memory or fix the leak"
if exit_code == 127 or "not found" in log:
return "command not found: wrong CMD/ENTRYPOINT, missing binary, or a script with CRLF line endings"
if exit_code == 126 or "permission denied" in log:
return "not executable / permission denied: chmod +x the script, check USER and file ownership"
if exit_code == 0:
return "main process finished: a container needs a foreground process to keep running"
if "connection refused" in log or "could not connect" in log:
return "dependency not reachable: check service name, network and depends_on/healthcheck"
return "app error: read the stack trace in the logs, then reproduce with `docker run -it ... sh`"
if status == "running (unhealthy)":
return "process alive but failing its check: run the healthcheck command by hand with docker exec"
return "looks fine from outside: test from inside with docker exec / a debug container"
cases = [
("exited", 0, False, ""),
("exited", 127, False, "exec /entrypoint.sh: no such file or directory... not found"),
("exited", 137, True, ""),
("exited", 1, False, "psycopg.OperationalError: connection refused (db:5432)"),
("restarting", 1, False, ""),
("running (unhealthy)", None, False, ""),
]
for status, code, oom, log in cases:
print(f"{status:<20} {str(code):<5} -> {triage(status, code, oom, log)}")exited 0 -> main process finished: a container needs a foreground process to keep running
exited 127 -> command not found: wrong CMD/ENTRYPOINT, missing binary, or a script with CRLF line endings
exited 137 -> killed (OOM or SIGKILL): check State.OOMKilled, raise --memory or fix the leak
exited 1 -> dependency not reachable: check service name, network and depends_on/healthcheck
restarting 1 -> crash loop: read `docker logs`; the restart policy is hiding the crash
running (unhealthy) None -> process alive but failing its check: run the healthcheck command by hand with docker exec
Note:
exec /entrypoint.sh: no such file or directorywhile the file clearly exists usually means the script has Windows line endings (#!/bin/sh\r), so the kernel looks for an interpreter calledsh\r. Add*.sh text eol=lfto.gitattributes.
"I can't reach my app"
The most common debugging session of all. A request from your browser to localhost:8080 passes several checkpoints, and any of them can be the culprit:
def diagnose(container):
checks = [
("container is running", container["running"]),
("host port is published", container["published"].get(8080) is not None),
("published to the port the app uses",
container["published"].get(8080) == container["app_port"]),
("app listens on 0.0.0.0, not 127.0.0.1", container["bind_address"] == "0.0.0.0"),
("app is actually started (logs show 'listening')", container["listening"]),
]
for label, ok in checks:
print(f" [{'ok' if ok else 'FAIL'}] {label}")
if not ok:
return label
return None
broken = {"running": True, "published": {8080: 80}, "app_port": 3000,
"bind_address": "0.0.0.0", "listening": True}
print("curl localhost:8080 ->", "connection reset")
first_problem = diagnose(broken)
print("first failing check:", first_problem)
print("fix: docker run -p 8080:3000 ...")curl localhost:8080 -> connection reset
[ok] container is running
[ok] host port is published
[FAIL] published to the port the app uses
first failing check: published to the port the app uses
fix: docker run -p 8080:3000 ...
The commands behind those checks:
docker ps --format '{{.Names}}\t{{.Status}}\t{{.Ports}}'
docker port web
docker logs web | grep -i listen
docker exec web sh -c 'netstat -tlnp 2>/dev/null || ss -tlnp'
docker exec web wget -qO- http://localhost:3000/healthIf the request works from inside the container but not from the host, the problem is publishing or the bind address. If it fails inside too, the problem is the app.
When the image has no shell
Distroless and scratch images have no sh, so docker exec -it web sh fails. Options:
docker debug web(Docker Desktop / Docker Pro) attaches a toolbox shell to any container, even one without a shell, without changing the image.- A sidecar debug container sharing the target's network and process namespaces:
docker run --rm -it --network container:web --pid container:web nicolaka/netshoot
# now: curl localhost:3000, ss -tlnp, ps aux, tcpdump -i eth0 ...- Start the image with a different entrypoint to look around before the app runs:
docker run --rm -it --entrypoint sh shop-api:1.4(only if the image has a shell). - Copy files out:
docker cp web:/app/config.yaml .
Build problems
docker build --progress=plain --no-cache . # full output of every RUN step
docker build --target build -t dbg . && docker run --rm -it dbg shLook at the first failing step; everything after it is just noise. --progress=plain shows the complete output that BuildKit normally collapses.
Test yourself
A container exits immediately with code 0 and no errors. What is the most likely reason?
- It was OOM-killed
- Its main process finished; nothing kept running in the foreground
- The image is corrupted
- The port is already in use
curl localhost:3000 works inside the container (via docker exec) but not from the host. Where is the problem?
- In the application code
- In port publishing or the app's bind address
- In the image size
- In the restart policy
How can you get network tools next to a distroless container that has no shell?
- Install them with apt in the container
- Run a debug container with
--network container:<name>(or usedocker debug) - Rebuild the host
- It's impossible