Lesson 11 of 24Real apps
Debugging Containers
A repeatable triage routine for containers that crash, hang, or cannot be reached, including shell-less images, network faults, builds, and attaching a debugger.
It is 4 pm and a teammate pings you: "the new image works on my machine but in staging it just restarts". You have no shell in the image, the logs say one line, and the deploy is due tomorrow. Docker CLI Essentials gave you the first moves: docker ps -a, docker logs, the exit code, and --entrypoint sh. This lesson turns them into a full routine and adds the cases those moves do not cover: images with no shell, services that are up but unreachable, builds that are slow or wrong, and stepping through code with a real debugger inside a container.
A triage order that always works
Under pressure, people jump straight to rebuilding the image with more print statements. Gather evidence first; it is cheaper. Each step narrows the problem before the next one.
docker ps -a shows every container, including dead ones. Exited (137) 2 minutes ago or Restarting (1) already tells you the kind of failure.
docker inspect returns a large JSON document. Ask for the fields you need with --format (-f):
docker inspect -f '{{.State.Status}} exit={{.State.ExitCode}} oom={{.State.OOMKilled}}' apidocker inspect -f '{{.State.Error}}' api # why the runtime could not start itdocker inspect -f '{{.State.StartedAt}} {{.State.FinishedAt}}' apidocker inspect -f '{{json .Config.Entrypoint}} {{json .Config.Cmd}}' apidocker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' apidocker inspect -f '{{json .Mounts}}' apidocker inspect -f '{{json .NetworkSettings.Networks}}' apidocker events --since 30m --filter container=api.State.Error is the most overlooked field. When Docker cannot even start your process (missing binary, bad mount), the reason lives there, not in the logs, because the app never ran to write any. StartedAt and FinishedAt tell you whether it died in 50 ms (a startup problem) or after 3 hours (a leak or an external event). .Config.Env shows the environment the container actually got, after .env files, Compose interpolation, and -e flags. Most "but I set that variable" arguments end here.
Reading exit codes like a log line
When a process dies from a signal, the exit code is 128 + the signal number. Learn the common ones and an exit code tells you where to look before you read a single log line.
| Code | Meaning | Usual cause |
|---|---|---|
0 | Finished normally | CMD was a one-shot command, or a daemon that forked into the background |
1 | App error | Unhandled exception; the traceback is in docker logs |
125 | Docker itself failed | Bad flag, unknown option, a port already allocated |
126 | Command cannot be invoked | Script not executable (chmod +x missing), or a directory instead of a file |
127 | Command not found | Typo in CMD, binary not on PATH, or a script with Windows line endings |
137 | SIGKILL (128 + 9) | OOM killer, or docker stop timed out |
139 | SIGSEGV (128 + 11) | Native code crash: a binary or wheel built for the wrong CPU or libc |
143 | SIGTERM (128 + 15) | Stopped on purpose, and the app exited on the signal |
Run this decoder. It is the logic you should do in your head.
Press Run (⌘ Enter) to see what happens.What does this print?
SIGNALS = {9: "SIGKILL", 11: "SIGSEGV", 15: "SIGTERM"}
code = 139
print(code - 128, SIGNALS[code - 128])The CRLF entrypoint
The strangest 127 you will meet: the logs say exec /docker-entrypoint.sh: no such file or directory, but the file is plainly there. The script was saved with Windows line endings (CRLF). Its first line is really #!/bin/sh\r, and the kernel looks for an interpreter called sh\r, which does not exist. Depending on the runtime version, you see exit code 127 or a start error in .State.Error; the message is the giveaway.
Prove it by printing the file with control characters visible (^M is the \r). This works on Debian-based images:
docker run --rm --entrypoint cat myapi:1.0 -A /docker-entrypoint.shFix it at the source with a .gitattributes line, so Git checks scripts out with LF on every OS:
*.sh text eol=lfGetting inside
docker exec -it api sh only works while the container is running. For a container that crashes on start, you have three options:
- Override the entrypoint in a fresh container from the same image:
docker run --rm -it --entrypoint sh myapi:1.0. Note that--entrypointalso clears the image's CMD, so you are at a shell and can run the start command by hand and watch it fail. - Copy files out of the dead container:
docker cp api:/app/config.yaml ./config.yamlworks on stopped containers too. - See what changed:
docker diff apilists files added (A), changed (C), or deleted (D) in the container's writable layer compared with the image. It quickly answers "did the app write that file?" and "why is the writable layer 3 GB?".
Images with no shell
Distroless images and Docker Hardened Images ship without sh, so exec and --entrypoint sh have nothing to run. That is good for security and annoying at 4 pm. Two ways in:
docker debug (part of Docker Desktop) opens a shell into any container or image, even shell-less and stopped ones, with a toolbox (curl, vim, htop, and more you can install) that lives outside the image. The image is never changed. Which Docker Desktop plans include it has changed over time, so check the docs for yours.
A toolbox container that joins the target's namespaces works on any Docker host, including Linux servers without Desktop:
docker run --rm -it --pid container:api --network container:api nicolaka/netshoot--pid container:api puts you in the same process namespace, so ps aux shows the app's processes. --network container:api puts you in the same network namespace: localhost is the app's localhost, and ss -lntp lists exactly what the app is listening on. nicolaka/netshoot is a popular image packed with network tools (curl, dig, tcpdump, ss). Kubernetes has the same idea built in as kubectl debug with ephemeral containers.
docker exec -it api sh fails with executable file not found. What is the most direct way to see which address and port the app is listening on?Network: up but unreachable
Most "it is running but I cannot reach it" problems are one of four things. Test from inside and outside the container to split them.
docker compose exec api getent hosts db # does the name db resolve?docker run --rm --network container:api nicolaka/netshoot curl -sS localhost:8000/healthcurl -sS localhost:8000/health # from the host, through -pdocker port api # what is actually published| Inside works? | Outside works? | Likely cause |
|---|---|---|
| Yes | No, connection reset or refused | App bound to 127.0.0.1 inside the container, or the wrong port published |
| No | No | App not listening at all: crashed, wrong port, still starting |
| Yes | Yes, but the API cannot reach the DB | Service name wrong, different networks, or the app connects to localhost |
The first row is the classic. A server that listens on 127.0.0.1 only accepts connections from inside its own network namespace. Traffic published with -p arrives on the container's network interface, not its loopback, so it is refused. ss -lntp from the toolbox shows 127.0.0.1:8000 instead of 0.0.0.0:8000. Fix the bind address (--host 0.0.0.0 for uvicorn, HOSTNAME=0.0.0.0 for Next.js standalone).
The third row's classic: DATABASE_URL=postgres://...@localhost:5432/app. Inside a container, localhost is the container itself, not your laptop and not the db service. Use the service name (db), and host.docker.internal only for something running on your machine outside Docker. getent hosts db returning nothing means the two containers are not on the same network; compare .NetworkSettings.Networks for both.
Port conflicts fail loudly: Bind for 0.0.0.0:5432 failed: port is already allocated means something on the host (often a local Postgres you forgot about) already holds that port. Publish a different host port ("5433:5432").
Debugging builds
Builds fail or slow down for their own reasons. The tools:
docker build --progress=plain .prints every step's full output instead of the collapsed view, so you see the actual compiler error or theRUNcommand's echo output.docker build --no-cache .rules out a stale cached layer. If the build succeeds only with--no-cache, a cache key is missing something (often aRUN apt-get updatecached from weeks ago).docker build --target build -t myapi:debug .stops at a named stage of a multi-stage build. Thendocker run --rm -it --entrypoint sh myapi:debuglets you look at exactly what the build stage produced before the runtime stage copies it.- Look at the
transferring contextline near the top of the build output. If it says hundreds of MB for a small app, your.dockerignoreis missingnode_modules,.venv,.git, or a data folder. That slows every build and can leak files into the image.
Attaching a real debugger
Print debugging is fine until it is not. Both Python and Node can wait for a debugger over a TCP port, and that works through Docker like any other port.
For Python, debugpy listens on a port and your editor attaches. Run it from a Compose override so production never sees it:
services:
api:
command: >
python -m debugpy --listen 0.0.0.0:5678 --wait-for-client
-m uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
ports:
- "127.0.0.1:5678:5678"{
"version": "0.2.0",
"configurations": [
{
"name": "Attach to api container",
"type": "debugpy",
"request": "attach",
"connect": { "host": "localhost", "port": 5678 },
"pathMappings": [
{ "localRoot": "${workspaceFolder}/api/app", "remoteRoot": "/app/app" }
]
}
]
}Three details make it work. debugpy must listen on 0.0.0.0 inside the container, for the same reason as the web server. The host side is bound to 127.0.0.1, so nobody on your coffee-shop Wi-Fi can attach a debugger, which is remote code execution by design. And pathMappings tells the editor that /app/app/main.py in the container is api/app/main.py on your disk; without it, breakpoints show as unverified and never hit. --wait-for-client pauses startup until you attach, which you want for startup bugs and not otherwise.
For Node, the same idea: node --inspect=0.0.0.0:9229 server.js, publish 127.0.0.1:9229:9229, and attach from VS Code or Chrome's chrome://inspect.
Practice: three broken containers
Each case gives you the evidence. Name the cause before reading the explanation.
Match each piece of evidence to its cause.
connection refused on localhost:5432. Postgres runs as the db service and is healthy. What should you check first?- .State.Error
- The
docker inspectfield that records why the runtime could not start the container's process. - exit code 128 + n
- A process killed by signal n exits with 128 + n: 137 is SIGKILL, 139 is SIGSEGV, 143 is SIGTERM.
- CRLF
- Windows line endings. In a script's first line they make the kernel look for an interpreter that does not exist.
- docker diff
- Lists files added, changed, or deleted in a container's writable layer compared with its image.
- namespace sharing
- Running a toolbox container with
--pid container:x --network container:xto see another container's processes and sockets. - docker debug
- A Docker Desktop command that opens a shell with tools into any container or image, even ones with no shell.
- debugpy
- Python's debug adapter.
--listen 0.0.0.0:5678lets an editor attach to code running in a container.