container-image-debugging
Skill1 starsChanged 2 months agoMITView on GitHub
Debug containers from the outside in - docker exec versus docker run, getting a shell into a distroless or scratch image, reading docker inspect state, why a container exits immediately, OOMKilled and exit 137, ENTRYPOINT and CMD override semantics, and the OCI image layout. Use when a container will not start, exits with code 1 or 137, drops its connection, or a command behaves differently under docker run than in production. Triggers on "container exits immediately", "exit code 137", "OOMKilled", "no shell in distroless", "docker exec", "exec /bin/sh not found", "container keeps restarting", "ImagePullBackOff".
- Reads credentials
- Installs packages
In this repository126 other files it gives its agents.
- eu-data-backend-job-hunterSkill
- job-application-matcherSkill
- llm-agents-and-tool-useSkill
- llm-application-architectureSkill
- llm-cost-and-latency-optimizationSkill
- llm-evaluationSkill
- llm-fine-tuning-and-adaptersSkill
- llm-privacy-and-safetySkill
- llm-prompt-engineeringSkill
- llm-rag-systemsSkill
- structured-output-and-jsonSkill
- graphql-api-designSkill
- pagination-and-filteringSkill
- rest-api-designSkill
- webhooks-and-integrationsSkill
- caching-architecture-multi-layerSkill
- resilience-patternsSkill
- service-boundaries-and-monolithsSkill
- system-design-interviewSkill
- go-concurrencySkill
- go-error-handlingSkill
- java-spring-patternsSkill
- nodejs-server-performanceSkill
- python-async-patternsSkill
- python-data-modelingSkill
- python-packaging-and-toolingSkill
- python-performanceSkill
- rest-api-implementationSkill
- rust-error-handlingSkill
- rust-ownership-patternsSkill
- typescript-type-safetySkill
- ci-caching-and-speedupSkill
- ci-pipeline-designSkill
- deployment-strategiesSkill
- github-actions-hardeningSkill
- release-versioning-and-changelogsSkill
- reproducible-buildsSkill
- aws-iam-and-securitySkill
- aws-serverless-architectureSkill
- azure-fundamentalsSkill
- cloud-cost-optimizationSkill
- cloud-networking-and-vpcSkill
- gcp-cloud-architectureSkill
- code-review-skillsSkill
- design-review-and-refactoring-architectureSkill
- refactoring-techniqueSkill
- understanding-unknown-codebaseSkill
- buildkit-and-cacheSkill
- container-runtime-securitySkill
- docker-compose-workflowsSkill
- dockerfile-authoringSkill
- docker-image-optimizationSkill
- database-connection-managementSkill
- database-transactionsSkill
- distributed-databasesSkill
- nosql-data-modelingSkill
- postgres-query-tuningSkill
- redis-and-cachingSkill
- schema-migrationsSkill
- data-modeling-for-analyticsSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
4 rules. About 0 are common, 3 are distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈3
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 18
Do these in order. Each one eliminates a class of cause.
- Distinctive: line 207
Never add a shell to a production image "temporarily" and forget.
- Very specific: line 268
Use --since and docker inspect --format '{{.RestartCount}}'.
- Distinctive: line 295
Keep scripts LF. This looks exactly like a missing file.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Container Image Debugging
Debug a container from the outside: what did the runtime try to run, what
code did it exit with, and what did it write before it died. Get a shell
inside only as a last resort — most container problems are visible from
inspect and logs.
Triage order
Do these in order. Each one eliminates a class of cause.
- 1.
docker ps -a— is it running, exited, or restarting? - 2.
docker logs <c>— the last thing it printed. Usually the answer. - 3.
docker inspect <c>—.State(ExitCode, OOMKilled, Error, Path, Args) and.Config(Entrypoint, Cmd, User, Env) - 4.
docker inspect <c> --format '{{.Path}} {{.Args}}'— what was actually executed, after override - 5. Reproduce the exact command with
docker run --entrypoint …locally - 6. Only then: get a shell, or
docker cpthe filesystem out
Step 1 — is it running?
docker ps -a --filter name=app --format '{{.Names}}\t{{.Status}}\t{{.Image}}'Status strings and what they mean:
| Status | Meaning |
Up 3 minutes | running |
Exited (0) 2 seconds ago | exited cleanly — the process finished, your CMD is wrong (it is a one-shot, not a server) |
Exited (1) 2 seconds ago | application error — read the logs |
Exited (137) | SIGKILL: docker stop grace expired, or OOMKilled. Check .State.OOMKilled. |
Exited (139) | segfault — usually a native module/architecture mismatch |
Exited (143) | SIGTERM handled; a clean stop |
Exited (125) | docker run itself failed (bad flags, image missing) |
Exited (126) | command found but not executable (wrong arch, no +x, bad shebang) |
Exited (127) | command not found — wrong PATH, typo, or a base image without the binary |
Restarting (1) 3 seconds ago | restart policy looping; this is Kubernetes' CrashLoopBackOff in miniature |
Exited (0) on a server is the most common surprise: you built the image, ran
it, it "worked" (printed nothing and returned). Look at Config.Cmd — a CMD
that runs a build step, a test, or a REPL exits 0 immediately.
Step 2 — the logs
docker logs --tail 200 --timestamps app
docker logs -f app # follow
docker logs --since 10m app # only the last 10 minutes
docker logs app 2>&1 | less # stderr is a separate stream- stdout and stderr are separate streams. An app that only writes to stderr shows nothing in a pipeline that drops it.
- A log driver can swallow everything.
--log-driver noneor a daemon-widelog-driverwith an aggressive rotation meansdocker logsis empty. Checkdocker inspect --format '{{.HostConfig.LogConfig}}'. - A buffering runtime produces no logs until exit. Python without
-uorPYTHONUNBUFFERED=1block-buffers when stdout is a pipe; a JVM without a console appender does the same. The container looks hung with empty logs. Fix in the image (ENV PYTHONUNBUFFERED=1,-XX:+UsePerfData/-Djava.util.logging), not bydocker exec. - Multi-line logs are preserved in
docker logsbut get mangled bydocker-compose logs(it re-emits line by line). For Compose usedocker logs $(docker compose ps -q svc). - No logs at all and an instant exit usually means the failure is before the
app starts: bad entrypoint path, missing binary, permission denied. Skip to
inspect.
Step 3 — read docker inspect usefully
The full JSON is a wall. Ask for the fields that matter:
docker inspect app \
--format 'status={{.State.Status}} exit={{.State.ExitCode}} oom={{.State.OOMKilled}} err={{.State.Error}} restarts={{.RestartCount}} started={{.State.StartedAt}}'docker inspect app \
--format 'user={{.Config.User}} workdir={{.Config.WorkingDir}}'
docker inspect app --format 'entrypoint={{json .Config.Entrypoint}} cmd={{json .Config.Cmd}}'
docker inspect app --format '{{.Path}} {{.Args}}' # ACTUAL resolved command
docker inspect app --format '{{json .Config.Env}}'
docker inspect app --format 'image={{.Config.Image}} platform={{.Os}}/{{.Architecture}}'
docker inspect app --format '{{json .HostConfig.RestartPolicy}} {{json .Mounts}}'What to do with each:
State.ExitCode+OOMKilled+Errortogether classify the exit.Errornon-empty is a runtime-level failure (bad mount, OCI hook), not an app crash.Path/Argsis the resolved command after every override. This is the fastest way to see that yourdocker run --entrypoint shreplaced the entrypoint, or that the image'sCMDis a shell string.Config.Env— checkPATH,HOME, and any*_HOMEyour app writes to.Mounts— a read-only mount where the app needs to write, or a bind mount pointing at a path that does not exist on the host (Docker creates a directory there, silently changing the semantics).HostConfig.LogConfig— explains empty logs.Config.Healthcheck— if present,State.Health.Loghas the last probe output. Read it; it is often the only clue in an otherwise silent container.
In one shot, when you need the state of a specific field and nothing else:
docker inspect --format '{{json .State.Health}}' app
docker inspect --format '{{range .State.Health.Log}}{{.ExitCode}} {{.Output}}{{end}}' appOOMKilled / exit 137
The kernel OOM-killer killed the process; the runtime reports 137 (128+9).
Confirmed behaviour: docker kill also produces exit 137 with
OOMKilled=false, so the exit code alone is ambiguous — always check the
flag.
docker inspect app --format 'oom={{.State.OOMKilled}} exit={{.State.ExitCode}}'
docker events --filter event=oom --since 30m # watch for the event
docker stats --no-stream # current usageCauses, in order of likelihood:
- The app's own heap/per-process limit is bigger than the container limit.
A JVM with default ergonomics sizes
-Xmxfrom host RAM, not the container limit, and will be OOM-killed the moment it touches it. A Node process and a Python process do the same thing. Set the runtime's limit explicitly (seekubernetes-resource-tuningfor the exact numbers). - A memory limit that is too low for the workload at peak — e.g. a batch job that loads the whole file.
- A leak — memory grows across restarts.
docker statstwice, a minute apart, tells you. - Host-wide OOM — the kernel killed your process because the host ran
out, not the cgroup.
dmesg | tail -50(orjournalctl -k) shows the out-of-memory killer's page counts and which process it chose.
Distinguishing 3 from 4: a cgroup OOM appears in docker events as an oom
event for that container; a host OOM appears in the kernel log with the
process's cgroup in the dump.
Getting into a container
docker exec needs a shell and the process to be running.
docker exec -it app sh # alpine/busybox
docker exec -it app bash # debian-based
docker exec -u 0 -it app sh # as root inside, if the user is non-root
docker exec -it app sh -c 'ls -la /app; cat /etc/os-release'
docker exec -it app env | sort # what the app actually seesFailures and what they mean:
| Error | Meaning |
Error response from daemon: Container … is not running | it exited; you cannot exec into a dead container. Use docker run with an override, or docker cp. |
OCI runtime exec failed: exec failed: unable to start container process: exec: "sh": executable file not found in $PATH: unknown | distroless/scratch image — there is no shell. Expected. |
exec: /bin/sh: permission denied | the exec user lacks permission, or the fs is --read-only and /bin is fine but something else is not |
no TTY allocated when not using -it | cosmetic; drop -it for scripted execs |
Getting a shell into a distroless image
Pick the least invasive option that works:
- Run the same image with a shell injected from outside — start the app
under a debugger image that shares the PID namespace:
Requiresdocker run --rm -it --pid container:app --entrypoint sh nicolaka/netshoot nsenter -t 1 -m -u -n -i sh # PID 1 is the app's process--pid container:<id>; the target must be running. - Re-build a debug variant of the same image — the correct answer for
anything reproducible:
A debug stage in the same Dockerfile as aFROM gcr.io/distroless/static-debian12 COPY --from=build /out/app /app COPY --from=busybox:1.36 /bin/busybox /busybox # or: FROM busybox as a stage USER 0:0 ENTRYPOINT ["/busybox", "sh"]--target debugyou never push. Copy a static busybox in; do notapt-get installa shell into the shipped image. docker cpthe filesystem out for offline analysis:docker cp app:/etc/nginx/nginx.conf ./nginx.conf docker export app | tar -t | head -100 docker export app | tar -xO app/etc/passwddocker run --entrypoint … <image> <cmd>to run a specific tool from the image itself — often the right move for a one-off check (--entrypoint /app/bin/healthcheck).
Never add a shell to a production image "temporarily" and forget; that is how remote-code-execution CVEs happen.
Why a container exits immediately
Work down this list:
CMDis not a server.docker psshowsExited (0). InspectConfig.Cmd— a build command, a test, or an interactive REPL.- The entrypoint script
execs nothing / uses"$@"wrongly. A common bug:ENTRYPOINT ["entrypoint.sh"]withCMDunset, and the script ends withoutexecing anything. - Missing config → the app exits 1 immediately (no
DATABASE_URL, failed to read a mounted secret, a config file that is not there). The error is in the logs; if not, run it with the env visible:docker run --rm --env-file .env -it app sh -c 'env | sort'. - The entrypoint path is wrong for the stage you built. A multi-stage build
that copies the binary to
/app/bin/serverwhileENTRYPOINT ["/app/bin"]. Verified semantics: the entrypoint is resolved inside the final image, and a relative or wrong path gives exit 126/127. - Architecture mismatch → exit 126 or "exec format error" (running an
amd64image onarm64or vice versa).docker image inspect img --format '{{.Os}}/{{.Architecture}}'. --read-onlyand the app needs to write → usually a clear error, but some apps die quietly. Re-run without--read-onlyto confirm.- The process was PID 1 and got SIGTERM immediately (compose
depends_onchurn, orchestrator health check failing, or adocker stopthat raced the start). Check.State.StartedAtvsFinishedAtand the restart count.
Isolate by running the same thing by hand with the overrides you need:
docker run --rm --entrypoint sh -it app:tag -c 'echo "PATH=$PATH"; id; ls -la /app'Reproducible debugging recipe
C=app
docker rm -f $C 2>/dev/null
docker run -d --name $C --init app:tag
sleep 3
docker ps -a --filter name=$C --format '{{.Status}}'
docker logs --tail 100 $C
docker inspect $C --format 'exit={{.State.ExitCode}} oom={{.State.OOMKilled}} err={{.State.Error}}'
docker inspect $C --format '{{.Path}} {{.Args}}'
docker events --since 1m --until 0s --filter container=$C--init matters for the diagnosis too: without it, a SIGKILL on stop looks
identical to an OOMKill. See dockerfile-authoring for the measured
stop-time difference.
Gotchas
Exited (0)is not "the container is broken". It is "the process returned success". A server that exits 0 is a configuration error, not a crash.docker logson a restarting container shows only the current instance's output; the previous crash is gone unless the driver keeps it. Use--sinceanddocker inspect --format '{{.RestartCount}}'.- A container that restarts loses
/tmpand any write layer. Crash reports written to the container filesystem are destroyed by the restart. Write them to a volume or stdout. docker cpworks on stopped containers;docker execdoes not. That asymmetry is the whole debugging strategy when the container will not stay up.--entrypointondocker runreplacesENTRYPOINTand passes remaining args; positional args replaceCMDentirely. Verified. If you expected yourCMDto survive--entrypoint sh, it does not — you must type the command.- Env vars from
docker run -eare not visible indocker inspectof the image, only of the container. To reproduce a CI run exactly, use the same--env-fileand--mountflags, not the image's defaults. - A
HEALTHCHECKfailing does not stop the container by itself (norestartbehaviour); only orchestrators act on it.docker runwill happily leave a container marked(unhealthy)running forever. docker system prunedeletes stopped containers and their logs. Take adocker cpor save the logs before cleaning up a failed deployment.docker inspecton a name that matches several containers requires the id; use$(docker compose ps -q svc).- A multi-stage
--targetbuilt in dev is not the shipped image. When the behaviour differs, comparedocker historybetween the two. no such file or directoryondocker runof a locally-built image after a rebuild with a different base means a stale image id;docker image pruneand rebuild. The name resolves to the old dangling image.- Windows line endings in an entrypoint script produce
/entrypoint.sh: not found(the\rbecomes part of the interpreter path). Keep scripts LF. This looks exactly like a missing file.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

