Skip to content

Debug scripts: Docker containers

16 paste-and-run bash scripts that collect what you need to find the error.

Index
16 items
  1. Paste the container ID, pod, service or URL into the box.
  2. Copy the script and paste it into a terminal on the machine (or where kubectl works).
  3. Read the report. It is also saved as debug-*.txt in the current folder to share.

Daily snapshot of every container (problems first)

Read-only

No input needed. One table of every container: status, health, restarts, exit code, OOM kill, memory use vs limit, uptime and image age, with anything abnormal at the top. Plus the deaths and OOM kills of the last 24 hours.

(
h() { printf '\n=== %s ===\n' "$*"; }
docker info >/dev/null 2>&1 || { echo "Docker daemon not reachable"; exit 1; }
T=$(mktemp -d); NOW=$(date +%s)
docker stats --no-stream --format '{{.Name}} {{.MemPerc}} {{.CPUPerc}}' > "$T/stats" 2>/dev/null

h "All containers (!! = needs a look)"
for id in $(docker ps -aq); do
  docker inspect "$id" --format '{{.Name}}|{{.State.Status}}|{{if .State.Health}}{{.State.Health.Status}}{{else}}-{{end}}|{{.RestartCount}}|{{.State.ExitCode}}|{{.State.OOMKilled}}|{{.State.StartedAt}}|{{.Image}}|{{.Config.Image}}'
done | while IFS='|' read -r N ST HL RC EC OOM STARTED IMGID IMG; do
  N=${N#/}
  MEM=$(awk -v n="$N" '$1 == n {print $2}' "$T/stats"); CPU=$(awk -v n="$N" '$1 == n {print $3}' "$T/stats")
  UP="-"; [ "$ST" = running ] && UP="$(( (NOW - $(date -d "$STARTED" +%s)) / 3600 ))h"
  AGE="$(( (NOW - $(date -d "$(docker image inspect "$IMGID" --format '{{.Created}}' 2>/dev/null || echo now)" +%s)) / 86400 ))d"
  F=""
  [ "$ST" = restarting ] && F="$F restarting"
  [ "$ST" = exited ] && [ "$EC" != 0 ] && F="$F exit=$EC"
  [ "$ST" = dead ] && F="$F dead"
  [ "$HL" = unhealthy ] && F="$F unhealthy"
  [ "$RC" -gt 0 ] 2>/dev/null && F="$F restarts=$RC"
  [ "$OOM" = true ] && F="$F OOM-killed"
  [ -n "$MEM" ] && [ "${MEM%%[.%]*}" -ge 85 ] 2>/dev/null && F="$F mem=$MEM"
  [ "$UP" != "-" ] && [ "${UP%h}" -lt 1 ] && F="$F started<1h"
  [ -n "$F" ] && K=0 M="!!" || K=1 M="  "
  printf '%s|%s %-28s %-11s %-10s %-7s %-7s %-6s %-6s %s%s\n' "$K" "$M" "$N" "$ST" "$HL" "${CPU:--}" "${MEM:--}" "$UP" "$AGE" "$IMG" "${F:+  <-$F}"
done | sort -t'|' -k1,1 -k2 | cut -d'|' -f2- > "$T/table"
printf '   %-28s %-11s %-10s %-7s %-7s %-6s %-6s %s\n' NAME STATUS HEALTH CPU MEM UP IMG-AGE IMAGE
cat "$T/table"
echo
echo "$(grep -c '^!!' "$T/table") of $(wc -l < "$T/table") containers need a look. (exited with 0 = a finished job, not a problem)"

h "Deaths and OOM kills in the last 24 hours"
docker events --since 24h --until "$NOW" --filter type=container --filter event=die --filter event=oom \
  --format '{{.Actor.Attributes.name}} {{.Action}} exit={{.Actor.Attributes.exitCode}}' 2>/dev/null \
  | sort | uniq -c | sort -rn | head -15
echo "(a container that died many times = crash loop: run 'Debug a container that crashed' on it)"

h "Disk"
df -h "$(docker info --format '{{.DockerRootDir}}')" | tail -1
rm -rf "$T"
) 2>&1 | tee "docker-snapshot-$(date +%Y%m%d-%H%M%S).txt"
What it checks
  1. All containersstatus, health, CPU, memory % of limit, uptime and image age for every container, problems sorted to the top with the reason
  2. What counts as a problemrestarting, exited non-zero, dead, unhealthy, restarted at least once, OOM-killed, memory above 85% of the limit, or started in the last hour
  3. Deaths and OOM kills in 24 hhow many times each container died or was OOM-killed since yesterday: crash loops stand out
  4. Diskfree space where Docker keeps its data

Errors across all containers in the last N minutes

Read-only

Paste how many minutes to look back (default 15). Counts error lines in every container's logs, shows which containers are the loudest, their most repeated error messages and latest errors, plus every die / OOM / health change in that window.

(
M="<minutes>"; case "$M" in ''|*[!0-9]*) M=15 ;; esac
h() { printf '\n=== %s ===\n' "$*"; }
docker info >/dev/null 2>&1 || { echo "Docker daemon not reachable"; exit 1; }
T=$(mktemp -d)
PAT='error|exception|fatal|panic|traceback|refused|denied|timed? ?out|oom|killed|unhealthy|segfault|[" ]5[0-9]{2}[" ]'

h "Error lines per container, last $M minutes"
for c in $(docker ps -a --format '{{.Names}}'); do
  docker logs --since "${M}m" --timestamps "$c" 2>&1 | grep -iE "$PAT" > "$T/$c"
  n=$(wc -l < "$T/$c"); [ "$n" -gt 0 ] && printf '%7d  %s\n' "$n" "$c"
done | sort -rn | tee "$T/summary"
[ -s "$T/summary" ] || echo "no error-looking lines in any container. Quiet."

for c in $(head -5 "$T/summary" | awk '{print $2}'); do
  h "$c: most repeated errors (numbers, ids and times masked)"
  cut -d' ' -f2- "$T/$c" | sed -E 's/[0-9a-fA-F]{8,}/#/g; s/[0-9]+/N/g' | cut -c1-160 | sort | uniq -c | sort -rn | head -5
  h "$c: latest 5 error lines"
  tail -5 "$T/$c" | cut -c1-300
done

h "Container deaths, OOM kills and health changes in the last $M minutes"
docker events --since "${M}m" --until "$(date +%s)" --filter type=container \
  --filter event=die --filter event=oom --filter event=restart --filter event=health_status \
  --format '{{.Time}} {{.Actor.Attributes.name}} {{.Action}} {{.Actor.Attributes.exitCode}}' 2>/dev/null \
  | while read -r t rest; do echo "$(date -d "@$t" +%H:%M:%S) $rest"; done
rm -rf "$T"
) 2>&1 | tee "docker-errors-$(date +%Y%m%d-%H%M%S).txt"
What it checks
  1. Error lines per containererror, exception, fatal, panic, refused, timeout, OOM and HTTP 5xx lines in every container's logs, loudest first
  2. Most repeated errorsfor the 5 loudest containers: the same error with numbers and ids masked, grouped and counted, so one real problem doesn't hide behind 500 log lines
  3. Latest error linesthe 5 newest error lines of each of those containers, with timestamps
  4. Deaths, OOM kills and health changesevery die, OOM, restart and healthy / unhealthy switch in the same window, with times

Debug a container that crashed, restarts or misbehaves

Read-only

Paste a container name or ID. Shows state, exit code with its meaning, OOM kill, health checks, recent logs and errors, limits, ports, mounts and Docker events.

(
C="<container>"
h() { printf '\n=== %s ===\n' "$*"; }

h "Container state"
docker inspect "$C" --format 'Name={{.Name}}  Image={{.Config.Image}}
Status={{.State.Status}}  Restarting={{.State.Restarting}}  RestartCount={{.RestartCount}}
ExitCode={{.State.ExitCode}}  OOMKilled={{.State.OOMKilled}}  Error={{.State.Error}}
StartedAt={{.State.StartedAt}}  FinishedAt={{.State.FinishedAt}}' || { echo "No container '$C'. List them with: docker ps -a"; exit 1; }

h "What the exit code means"
case "$(docker inspect "$C" --format '{{.State.ExitCode}}')" in
  0)   echo "0: the main process finished normally (did it run in the foreground?)";;
  1)   echo "1: application error, see the logs below";;
  125) echo "125: docker run itself failed (bad flag or option)";;
  126) echo "126: command found but not executable (permissions, wrong architecture)";;
  127) echo "127: command not found (wrong ENTRYPOINT/CMD or missing binary)";;
  137) echo "137: SIGKILL. OOMKilled=true means the memory limit; otherwise docker kill or a stop timeout";;
  139) echo "139: segmentation fault";;
  143) echo "143: SIGTERM from docker stop, usually a normal shutdown";;
  *)   echo "see the logs below";;
esac

h "Health check"
docker inspect "$C" --format '{{if .State.Health}}{{.State.Health.Status}} (failing streak {{.State.Health.FailingStreak}}){{range .State.Health.Log}}
- {{.End}} exit={{.ExitCode}} {{.Output}}{{end}}{{else}}no health check defined{{end}}'

h "Last 50 log lines"
docker logs --tail 50 --timestamps "$C" 2>&1

h "Error lines in the last 2000 log lines"
ERR=$(docker logs --tail 2000 "$C" 2>&1 | grep -inE 'error|exception|fatal|panic|refused|denied|timed? ?out|killed|no such|not found' | tail -25)
[ -n "$ERR" ] && echo "$ERR" || echo "no error-looking lines"

h "Resource usage and limits"
docker stats --no-stream "$C" 2>/dev/null
docker inspect "$C" --format 'MemoryLimit={{.HostConfig.Memory}} bytes (0 = none)  NanoCpus={{.HostConfig.NanoCpus}} (0 = none)  RestartPolicy={{.HostConfig.RestartPolicy.Name}}'

h "Ports, networks and mounts"
docker port "$C" 2>/dev/null || true
docker inspect "$C" --format '{{range $n, $c := .NetworkSettings.Networks}}network {{$n}}: ip={{$c.IPAddress}}{{"\n"}}{{end}}{{range .Mounts}}mount {{.Type}} {{.Source}} -> {{.Destination}} rw={{.RW}}{{"\n"}}{{end}}'

h "Entrypoint, command and user"
docker inspect "$C" --format 'Entrypoint={{json .Config.Entrypoint}}  Cmd={{json .Config.Cmd}}  WorkingDir={{.Config.WorkingDir}}  User={{.Config.User}}'

h "Environment variable names (values hidden)"
docker inspect "$C" --format '{{range .Config.Env}}{{println .}}{{end}}' | cut -d= -f1

h "Docker events for this container in the last hour"
docker events --since 1h --until "$(date +%s)" --filter container="$C" 2>/dev/null | tail -20
) 2>&1 | tee "debug-container-$(date +%Y%m%d-%H%M%S).txt"
What it checks
  1. Container staterunning / exited / restarting, restart count, exit code, OOMKilled flag and Docker's own error message
  2. What the exit code meanstranslates the exit code: 137 = killed (often out of memory), 127 = command not found, 143 = normal stop...
  3. Health checkhealthy / unhealthy and the output of the last health check runs
  4. Last 50 log lineswhat the app printed just before it stopped
  5. Error lineserror, exception, refused, denied, timeout... lines from the recent logs
  6. Resource usage and limitscurrent CPU and memory vs the limits set on the container
  7. Ports, networks and mountspublished ports, container IPs per network, volumes and bind mounts
  8. Entrypoint, command and userwhat the container actually runs, from which folder, as which user
  9. Environment variable nameswhich variables are set (values hidden, so the report is safe to share)
  10. Docker eventsstarts, deaths, OOM and health changes in the last hour

Container is running but unhealthy

Read-only

Paste a container name or ID. Shows the health check and its last results, runs the same check by hand and times it against the timeout, checks the tools it needs exist in the image and that the app listens on the port it probes.

(
C="<container>"
h() { printf '\n=== %s ===\n' "$*"; }
docker inspect "$C" >/dev/null 2>&1 || { echo "No container '$C'. List them with: docker ps -a"; exit 1; }

h "Health check config"
docker inspect "$C" --format '{{if .Config.Healthcheck}}Test={{json .Config.Healthcheck.Test}}
Interval={{.Config.Healthcheck.Interval}}  Timeout={{.Config.Healthcheck.Timeout}}  Retries={{.Config.Healthcheck.Retries}}  StartPeriod={{.Config.Healthcheck.StartPeriod}}{{else}}NONE: this container has no health check{{end}}'
echo "(0s / 0 = Docker's default: interval 30s, timeout 30s, retries 3, start period 0s)"

h "Status and the last results"
docker inspect "$C" --format 'Status={{.State.Status}}  Health={{if .State.Health}}{{.State.Health.Status}}  FailingStreak={{.State.Health.FailingStreak}}{{range .State.Health.Log}}
{{.Start}}  exit={{.ExitCode}}  {{.Output}}{{end}}{{else}}-{{end}}' | cut -c1-300
STARTED=$(docker inspect "$C" --format '{{.State.StartedAt}}')
echo "Up for $(( $(date +%s) - $(date -d "$STARTED" +%s) ))s. Unhealthy only right after start = the app needs a longer start_period."

KIND=$(docker inspect "$C" --format '{{if .Config.Healthcheck}}{{index .Config.Healthcheck.Test 0}}{{end}}')
ARGS=$(docker inspect "$C" --format '{{if .Config.Healthcheck}}{{range $i, $a := .Config.Healthcheck.Test}}{{if $i}}{{$a}}{{"\n"}}{{end}}{{end}}{{end}}')
if [ "$KIND" = CMD ] || [ "$KIND" = CMD-SHELL ]; then
  h "Run the check by hand"
  echo "running: $ARGS"
  S=$(date +%s%N)
  if [ "$KIND" = CMD-SHELL ]; then docker exec "$C" sh -c "$ARGS"; RC=$?
  else OLD=$IFS; IFS='
'; set -- $ARGS; IFS=$OLD; docker exec "$C" "$@"; RC=$?; fi
  MS=$(( ($(date +%s%N) - S) / 1000000 ))
  echo
  echo "exit code $RC after ${MS} ms"
  case $RC in
    0) echo "passes now: the failures are intermittent (slow responses, load) or only at startup";;
    126|127) echo "PROBLEM: the check's command is missing or not executable in the image (slim images often have no curl / wget)";;
    *) echo "fails by hand too: the check itself or the app is broken, see the output above";;
  esac
  TO=$(docker inspect "$C" --format '{{.Config.Healthcheck.Timeout.Seconds}}' 2>/dev/null | cut -d. -f1)
  [ "${TO:-0}" -gt 0 ] 2>/dev/null || TO=30   # 0 = Docker's default timeout
  [ "$MS" -gt $(( TO * 1000 * 8 / 10 )) ] && echo "PROBLEM: took ${MS} ms, close to or over the ${TO}s timeout"
fi

h "Tools available in the image"
docker exec "$C" sh -c 'for t in curl wget nc pg_isready redis-cli mysqladmin; do command -v $t >/dev/null 2>&1 && echo "  $t: yes" || echo "  $t: no"; done' 2>&1
echo "(no curl / wget: use a check the image can run, e.g. the app's own binary, or add the tool to the image)"

h "Ports the app listens on inside the container"
docker run --rm --network container:"$C" busybox:1.36 netstat -ltn 2>&1 | awk 'NR <= 2 || $NF == "LISTEN"'
echo "(the check probes localhost: is that port in the list above?)"

h "Last 30 log lines"
docker logs --tail 30 --timestamps "$C" 2>&1
) 2>&1 | tee "debug-unhealthy-$(date +%Y%m%d-%H%M%S).txt"
What it checks
  1. Health check configthe test command, interval, timeout, retries and start period (0 = Docker's defaults)
  2. Status and last resultshealthy / unhealthy, failing streak and the output of the last checks; how long the container has been up
  3. Run the check by handruns the exact same command inside the container and times it: passes now = intermittent or startup-only; exit 126/127 = the tool is missing in the image; close to the timeout = the app is too slow
  4. Tools in the imagecurl, wget, nc and database clients the check might rely on
  5. Ports inside the containeris the app listening on the port the check probes?
  6. Last 30 log lineswhat the app printed while the check failed

Container won't stop, or always takes 10 seconds to stop

Read-only

Paste a container name or ID. Shows whether PID 1 handles SIGTERM (a shell wrapper usually doesn't), the stop signal and timeout, --init, zombie processes, how recent stops actually ended, and what holds the container's mounts when removal fails.

(
C="<container>"
h() { printf '\n=== %s ===\n' "$*"; }
docker inspect "$C" >/dev/null 2>&1 || { echo "No container '$C'. List them with: docker ps -a"; exit 1; }
PID=$(docker inspect "$C" --format '{{.State.Pid}}'); ID=$(docker inspect "$C" --format '{{.Id}}')

h "State and stop settings"
docker inspect "$C" --format 'Status={{.State.Status}}  Dead={{.State.Dead}}  ExitCode={{.State.ExitCode}}  RestartPolicy={{.HostConfig.RestartPolicy.Name}}
StopSignal={{if .Config.StopSignal}}{{.Config.StopSignal}}{{else}}SIGTERM (default){{end}}  StopTimeout={{if .Config.StopTimeout}}{{.Config.StopTimeout}}s{{else}}10s (default){{end}}  Init={{if .HostConfig.Init}}{{.HostConfig.Init}}{{else}}false{{end}}
Entrypoint={{json .Config.Entrypoint}}  Cmd={{json .Config.Cmd}}'

if [ "$PID" != 0 ]; then
  h "What runs as PID 1"
  P1=$(sudo cat /proc/"$PID"/cmdline 2>/dev/null | tr '\0' ' ')
  echo "PID 1: $P1"
  case "$P1" in
    *tini*|*dumb-init*|*docker-init*|*s6-svscan*|*supervisord*) echo "OK: an init process forwards signals";;
    "sh -c"*|"/bin/sh -c"*|"bash -c"*|"/bin/bash -c"*|"/bin/sh "*|"sh "*|"/bin/bash "*|"bash "*) echo "PROBLEM: a shell is PID 1. It does not pass SIGTERM to your app, so docker stop waits the timeout and then kills it (exit 137). Fix: exec form CMD [\"app\"], 'exec app' at the end of the entrypoint script, or run with --init";;
  esac

  h "Does PID 1 handle SIGTERM?"
  CGT=$(sudo awk '/^SigCgt/ {print $2}' /proc/"$PID"/status 2>/dev/null)
  if [ -n "$CGT" ]; then
    if [ $(( (0x$CGT >> 14) & 1 )) = 1 ]; then echo "yes: PID 1 has a SIGTERM handler"
    else echo "NO: PID 1 has no SIGTERM handler. Inside a container PID 1 ignores signals it does not handle, so SIGTERM does nothing. Use --init or handle SIGTERM in the app."; fi
  else echo "can't read /proc/$PID/status (needs sudo)"; fi

  h "Processes and zombies"
  docker top "$C" -eo pid,ppid,stat,etime,args 2>/dev/null | head -25
  Z=$(docker top "$C" -eo stat 2>/dev/null | grep -c '^Z')
  [ "$Z" -gt 0 ] && echo "PROBLEM: $Z zombie process(es): PID 1 doesn't reap children. Run with --init."
fi

h "How recent stops ended (last 24 h)"
docker events --since 24h --until "$(date +%s)" --filter container="$ID" --filter event=kill --filter event=die --filter event=stop \
  --format '{{.Time}} {{.Action}} signal={{.Actor.Attributes.signal}} exit={{.Actor.Attributes.exitCode}}' 2>/dev/null \
  | while read -r t rest; do echo "$(date -d "@$t" +%H:%M:%S) $rest"; done | tail -20
echo "(kill signal=15 followed by kill signal=9 and exit=137 = SIGTERM was ignored; exit=143 = clean shutdown on SIGTERM)"

h "Processes holding this container's mounts ('device or resource busy' on rm)"
# only processes in some OTHER mount namespace count: the host's own namespace and the container's are expected
HOSTNS=$(sudo readlink /proc/1/ns/mnt); CNS=""; [ "$PID" != 0 ] && CNS=$(sudo readlink /proc/"$PID"/ns/mnt)
N=0
for f in $(sudo grep -l "$ID" /proc/[0-9]*/mountinfo 2>/dev/null); do
  p=$(echo "$f" | cut -d/ -f3); ns=$(sudo readlink /proc/"$p"/ns/mnt 2>/dev/null)
  { [ "$ns" = "$HOSTNS" ] || [ "$ns" = "$CNS" ]; } && continue
  N=$((N + 1)); echo "  pid $p: $(sudo cat /proc/"$p"/cmdline 2>/dev/null | tr '\0' ' ' | cut -c1-120)"
done
[ "$N" = 0 ] && echo "none" || echo "(these keep the container's filesystem mounted: stop them, then docker rm again)"
) 2>&1 | tee "debug-wont-stop-$(date +%Y%m%d-%H%M%S).txt"
What it checks
  1. State and stop settingsstop signal, stop timeout (default 10 s), --init and the entrypoint / command form
  2. What runs as PID 1a shell wrapper (sh -c, bash script without exec) as PID 1 swallows SIGTERM: the #1 cause of slow stops
  3. Does PID 1 handle SIGTERM?reads the signal handler mask: PID 1 in a container ignores any signal it has no handler for
  4. Processes and zombieswhat runs inside and any zombie processes left by a PID 1 that doesn't reap children
  5. How recent stops endedkill / die events with signals and exit codes: SIGTERM then SIGKILL and exit 137 proves the graceful stop failed
  6. Processes holding the mountsother host processes keeping the container's filesystem busy, the cause of 'device or resource busy' when removing it

Container is slow, high CPU or high memory

Read-only

Paste a container name or ID. Samples CPU and memory, shows the limits, CPU throttling and memory pressure from the cgroup, the busiest processes inside, and whether the host itself is the bottleneck.

(
C="<container>"
h() { printf '\n=== %s ===\n' "$*"; }
docker inspect "$C" >/dev/null 2>&1 || { echo "No container '$C'. List them with: docker ps -a"; exit 1; }
PID=$(docker inspect "$C" --format '{{.State.Pid}}')
[ "$PID" = 0 ] && { echo "'$C' is not running. Use 'Debug a container that crashed, restarts or misbehaves' instead."; exit 1; }

h "Usage: 3 samples, 2 seconds apart"
docker stats --no-stream --format 'table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.MemPerc}}\t{{.NetIO}}\t{{.BlockIO}}\t{{.PIDs}}' "$C"
for i in 2 3; do sleep 2; docker stats --no-stream --format '{{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.MemPerc}}\t{{.NetIO}}\t{{.BlockIO}}\t{{.PIDs}}' "$C"; done
echo "(CPU 100% = one full core. Steady near the limit = needs more, or a busy loop.)"

h "Limits set on the container"
docker inspect "$C" --format 'Memory={{.HostConfig.Memory}}  MemorySwap={{.HostConfig.MemorySwap}}  MemoryReservation={{.HostConfig.MemoryReservation}}
NanoCpus={{.HostConfig.NanoCpus}} (1000000000 = 1 CPU)  CpuQuota={{.HostConfig.CpuQuota}}  CpuShares={{.HostConfig.CpuShares}}  CpusetCpus={{.HostConfig.CpusetCpus}}
PidsLimit={{.HostConfig.PidsLimit}}  RestartCount={{.RestartCount}}  OOMKilled={{.State.OOMKilled}}'
echo "(0 = no limit)"

CG=$(awk -F: '$1 == "0" {print $3}' /proc/"$PID"/cgroup 2>/dev/null)
D="/sys/fs/cgroup$CG"
if [ -n "$CG" ] && [ -f "$D/cpu.stat" ]; then
  h "CPU throttling (cgroup v2)"
  grep -E 'usage_usec|nr_periods|nr_throttled|throttled_usec' "$D/cpu.stat"
  awk '/^nr_periods/ {p=$2} /^nr_throttled/ {t=$2} END {if (p > 0) printf "throttled in %.1f%% of CPU periods%s\n", 100*t/p, (t/p > 0.05 ? ": the CPU limit is slowing this container down" : "")}' "$D/cpu.stat"

  h "Memory pressure (cgroup v2)"
  echo "current: $(cat "$D/memory.current" 2>/dev/null)  max: $(cat "$D/memory.max" 2>/dev/null)"
  grep -E '^(anon|file|kernel|sock|shmem) ' "$D/memory.stat" 2>/dev/null
  echo "events:"; cat "$D/memory.events" 2>/dev/null
  echo "(anon = the app's own memory; file = page cache the kernel can drop. 'high' or 'oom' growing = memory pressure.)"
  [ -f "$D/memory.pressure" ] && { echo "PSI:"; cat "$D/memory.pressure"; }
  [ -f "$D/cpu.pressure" ] && { echo "CPU PSI:"; cat "$D/cpu.pressure"; }
else
  h "cgroup details"
  echo "not available (cgroup v1, Docker Desktop, or no access to /proc/$PID). Limits and docker stats above still apply."
fi

h "Busiest processes inside the container"
docker top "$C" -eo pid,ppid,pcpu,pmem,rss,nlwp,etime,args 2>/dev/null | awk 'NR == 1; NR > 1 {print | "sort -k3 -rn"}' | head -15
echo "(nlwp = threads. rss = resident memory in KB.)"

h "Open file descriptors of the main process"
N=$(sudo ls /proc/"$PID"/fd 2>/dev/null | wc -l)
LIM=$(sudo awk '/Max open files/ {print $4}' /proc/"$PID"/limits 2>/dev/null)
echo "open: $N  limit: ${LIM:-unknown}  (close to the limit = 'too many open files', usually a connection leak)"

h "Health check timing"
docker inspect "$C" --format '{{if .State.Health}}{{range .State.Health.Log}}{{.Start}} -> {{.End}}  exit={{.ExitCode}}{{"\n"}}{{end}}{{else}}no health check defined{{end}}'

h "Timeouts and slow-request lines in the last 2000 log lines"
docker logs --tail 2000 "$C" 2>&1 | grep -inE 'timed? ?out|slow|deadline|too many|out of memory|heap|gc overhead|throttl|backpressure|pool exhausted' | tail -20 || true

h "Is the host the bottleneck?"
echo "CPUs: $(nproc)  load: $(cut -d' ' -f1-3 /proc/loadavg)  (load above the CPU count = the host is saturated)"
free -m
grep -E 'some|full' /proc/pressure/cpu /proc/pressure/memory /proc/pressure/io 2>/dev/null
echo "Top containers on this host:"
echo "CPU%    MEM%    NAME"
docker stats --no-stream --format '{{.CPUPerc}}\t{{.MemPerc}}\t{{.Name}}' | sort -rn | head -8
) 2>&1 | tee "debug-slow-container-$(date +%Y%m%d-%H%M%S).txt"
What it checks
  1. Usage samplesCPU %, memory vs limit, network and disk I/O and process count, three times so you see a trend, not a spike
  2. Limitsmemory and CPU limits, restart count and OOMKilled: a container pinned at its limit is slow by design
  3. CPU throttlingshare of CPU periods where the kernel paused the container because it hit its CPU limit
  4. Memory pressureapp memory vs page cache, and high / oom events that show the container is fighting its memory limit
  5. Busiest processeswhich process inside uses the CPU and memory, with thread counts
  6. Open file descriptorsa connection or file leak shows up as a number creeping toward the limit
  7. Health check timinghealth checks taking longer and longer = the app is struggling
  8. Timeouts in the logstimeouts, GC / heap errors, exhausted pools
  9. Host bottleneckload vs CPU count, free memory, pressure stall info and the other heavy containers on the box

Published port not reachable from the host or outside

Read-only

Paste the container and the port the app listens on inside it. Checks the port is published, that the app listens on 0.0.0.0 (not 127.0.0.1), what holds the host port, and tests the connection from the host.

(
C="<container>"; P="<container-port>"
h() { printf '\n=== %s ===\n' "$*"; }

h "Container and network mode"
docker inspect "$C" --format 'Name={{.Name}}  Status={{.State.Status}}  NetworkMode={{.HostConfig.NetworkMode}}' || { echo "No container '$C'. List them with: docker ps -a"; exit 1; }
[ "$(docker inspect "$C" --format '{{.HostConfig.NetworkMode}}')" = host ] && echo "Host network mode: -p is ignored, the app's own port is the host port."

h "Is port $P published?"
docker port "$C" 2>/dev/null || true
HP=$(docker port "$C" "$P/tcp" 2>/dev/null | head -1 | awk -F: '{print $NF}')
BIND=$(docker port "$C" "$P/tcp" 2>/dev/null | head -1 | sed 's/:[0-9]*$//')
if [ -z "$HP" ]; then
  echo "NOT published. EXPOSE in the Dockerfile does not publish a port: add -p HOSTPORT:$P (compose: ports: [\"HOSTPORT:$P\"])"
else
  echo "Published: host $BIND:$HP -> container $P"
  case "$BIND" in 127.0.0.1|::1|\[::1\]) echo "Bound to localhost on the host: reachable from this machine only, not from outside.";; esac
fi

h "Is the app listening on $P inside the container?"
L=$(docker run --rm --network container:"$C" busybox:1.36 netstat -ltn 2>&1)
echo "$L"
# local address column ($4) of LISTEN sockets on port $P
LA=$(echo "$L" | awk -v p="$P" '$NF == "LISTEN" {n = split($4, a, ":"); if (a[n] == p) print $4}')
if [ -z "$LA" ]; then
  echo "NOTHING listens on $P inside the container: wrong port, app not started yet, or it crashed (see logs below)."
elif echo "$LA" | grep -qE '^(0\.0\.0\.0|::|\*):'; then
  echo "OK: listening on all interfaces ($(echo $LA))."
elif echo "$LA" | grep -qE '^(127\.|::1:)'; then
  echo "PROBLEM: listening on localhost only ($(echo $LA)). Docker forwards to the container IP, so bind the app to 0.0.0.0."
else
  echo "Listening on a specific address only: $(echo $LA)"
fi

h "Test from the host"
for IP in $(docker inspect "$C" --format '{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}'); do
  timeout 3 bash -c "echo > /dev/tcp/$IP/$P" 2>/dev/null && echo "container IP $IP:$P  -> TCP OK" || echo "container IP $IP:$P  -> TCP FAILED"
done
if [ -n "$HP" ]; then
  timeout 3 bash -c "echo > /dev/tcp/127.0.0.1/$HP" 2>/dev/null && echo "127.0.0.1:$HP (published) -> TCP OK" || echo "127.0.0.1:$HP (published) -> TCP FAILED"
  curl -sS -m 5 -o /dev/null -w "127.0.0.1:$HP HTTP -> %{http_code} in %{time_total}s\n" "http://127.0.0.1:$HP/" 2>&1
fi

if [ -n "$HP" ]; then
  h "What holds host port $HP"
  sudo ss -ltnp "sport = :$HP" 2>/dev/null
  echo "(docker-proxy or dockerd = Docker owns it. Anything else = another program took the port: 'port is already allocated'.)"

  h "Docker NAT rule for host port $HP"
  sudo iptables -t nat -S DOCKER 2>/dev/null | grep -- "--dport $HP" || echo "no DOCKER NAT rule found (nftables host, rootless Docker, or the port is not published)"

  h "Host firewall"
  sudo ufw status 2>/dev/null | head -5
  sudo firewall-cmd --list-all 2>/dev/null | grep -E 'ports|services'
  echo "Reachable here but not from outside? Check the cloud security group / NACL for port $HP too."
fi

h "Last 30 log lines"
docker logs --tail 30 --timestamps "$C" 2>&1
) 2>&1 | tee "debug-port-$(date +%Y%m%d-%H%M%S).txt"
What it checks
  1. Container and network modehost network mode ignores -p: the app's own port is the host port
  2. Is the port published?EXPOSE alone publishes nothing; also flags a port published on 127.0.0.1 only
  3. Is the app listening inside?the most common cause: the app binds to 127.0.0.1 inside the container instead of 0.0.0.0
  4. Test from the hostTCP to the container IP and to the published port, plus an HTTP status, to see which hop fails
  5. What holds the host portdocker-proxy vs another program that took the port first
  6. Docker NAT rulethe iptables DNAT rule Docker adds for the published port
  7. Host firewallufw / firewalld, and a reminder about cloud security groups
  8. Last 30 log linesdid the app start and print the address it listens on?

Container can't reach another service (DNS / network)

Read-only

Paste the container and the host:port it should reach. Tests DNS and the TCP connection from inside the container's own network, plus its networks and resolver config.

(
C="<container>"; HOST="<target-host>"; PORT="<target-port>"
h() { printf '\n=== %s ===\n' "$*"; }

h "Networks of the container"
docker inspect "$C" --format '{{range $n, $c := .NetworkSettings.Networks}}{{$n}}: ip={{$c.IPAddress}} gateway={{$c.Gateway}} aliases={{$c.Aliases}}{{"\n"}}{{end}}' || exit 1

h "Other containers on the same networks"
for n in $(docker inspect "$C" --format '{{range $n, $c := .NetworkSettings.Networks}}{{$n}} {{end}}'); do
  echo "[$n]"; docker network inspect "$n" --format '{{range .Containers}}  {{.Name}} {{.IPv4Address}}{{"\n"}}{{end}}'
done

h "DNS config inside the container"
docker exec "$C" cat /etc/resolv.conf 2>&1

h "Resolve $HOST from the container's network"
docker run --rm --network container:"$C" busybox:1.36 nslookup "$HOST" 2>&1

h "TCP connect to $HOST:$PORT from the container's network"
docker run --rm --network container:"$C" busybox:1.36 sh -c "nc -zv -w 3 $HOST $PORT" 2>&1 && echo "REACHABLE" || echo "NOT reachable (refused = nothing listening there; timeout = firewall or wrong network)"

h "Is the target a container? Its state and ports"
docker ps -a --filter name="$HOST" --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}\t{{.Networks}}'
) 2>&1 | tee "debug-network-$(date +%Y%m%d-%H%M%S).txt"
What it checks
  1. Networks of the containerwhich Docker networks it is on, with IP, gateway and DNS aliases
  2. Other containers on the same networkscontainers can only reach each other by name when they share a network
  3. DNS configthe resolver the container uses (127.0.0.11 is Docker's embedded DNS)
  4. Resolve the hostruns nslookup inside the container's network namespace (busybox helper), even if the image has no tools
  5. TCP connectnc to host:port from the same network: refused vs timeout tells you which problem it is
  6. Target containerif the target is a container: is it running, which ports and networks

Permission denied on a volume or bind mount

Read-only

Paste the container and the path inside it that fails. Compares the container's user with the owner of the mounted folder on the host, tests a write, and checks read-only mounts, SELinux labels, user namespaces and free space.

(
C="<container>"; P="<path-in-container>"
h() { printf '\n=== %s ===\n' "$*"; }

h "Who the container runs as"
docker inspect "$C" --format 'User={{if .Config.User}}{{.Config.User}}{{else}}(image default){{end}}  ReadonlyRootfs={{.HostConfig.ReadonlyRootfs}}  Privileged={{.HostConfig.Privileged}}  UsernsMode={{.HostConfig.UsernsMode}}  SecurityOpt={{.HostConfig.SecurityOpt}}' || { echo "No container '$C'. List them with: docker ps -a"; exit 1; }
CID=$(docker exec "$C" id 2>&1); echo "inside: $CID"
CU=$(docker exec "$C" id -u 2>/dev/null); CG=$(docker exec "$C" id -g 2>/dev/null)
docker info --format 'Daemon security options: {{.SecurityOptions}}' 2>/dev/null
echo "(userns or rootless in the options above = container uids are shifted on the host)"

h "Mounts"
docker inspect "$C" --format '{{range .Mounts}}{{.Type}}  {{.Source}} -> {{.Destination}}  rw={{.RW}}  mode={{.Mode}}{{"\n"}}{{end}}'
M=$(docker inspect "$C" --format '{{range .Mounts}}{{.Destination}}|{{.Source}}|{{.RW}}{{"\n"}}{{end}}' | awk -F'|' -v p="$P" 'index(p, $1) == 1 && length($1) > l {l = length($1); m = $0} END {print m}')
SRC=$(echo "$M" | cut -d'|' -f2); RW=$(echo "$M" | cut -d'|' -f3)
if [ -z "$M" ]; then echo "$P is not on a mount: it's in the container's own filesystem (image layer)."
else echo "$P is on the mount from $SRC"; [ "$RW" = false ] && echo "PROBLEM: mounted read-only (:ro). Remove :ro or write somewhere else."; fi

h "The path inside the container"
docker exec "$C" ls -ldn "$P" 2>&1
docker exec "$C" sh -c 'd="$1"; [ -d "$d" ] || d=$(dirname "$d"); t="$d/.write-test-$$"; if touch "$t" 2>/dev/null; then rm -f "$t"; echo "write test in $d: OK"; else echo "write test in $d: FAILED"; fi' sh "$P" 2>&1
echo "(no shell in the image? the write test can't run; the host-side checks below still apply)"

if [ -n "$SRC" ]; then
  h "The folder on the host: $SRC"
  sudo ls -ldn "$SRC" 2>&1
  O=$(sudo stat -c '%u:%g %a' "$SRC" 2>/dev/null); OU=${O%%:*}; OG=$(echo "$O" | cut -d: -f2 | cut -d' ' -f1); MODE=${O##* }
  echo "owner uid:gid = $OU:$OG  mode = $MODE   container runs as uid:gid = ${CU:-?}:${CG:-?}"
  OW=no; case "$MODE" in *[2367]) OW=yes ;; esac   # can "others" write?
  if [ -n "$CU" ] && [ "$CU" != 0 ] && [ "$CU" != "$OU" ] && [ "$CG" != "$OG" ] && [ "$OW" = no ]; then
    echo "PROBLEM: the folder belongs to uid $OU, the container writes as uid $CU."
    echo "Fix one of: sudo chown -R $CU:$CG $SRC   |   run the container with --user $OU:$OG   |   set the uid in the Dockerfile to match"
  fi

  h "SELinux"
  if [ "$(getenforce 2>/dev/null)" = Enforcing ]; then
    sudo ls -ldZ "$SRC" 2>&1
    sudo ls -ldZ "$SRC" 2>/dev/null | grep -q container_file_t || echo "PROBLEM: SELinux is enforcing and the folder is not labelled for containers. Add :z (shared) or :Z (private) to the mount."
    sudo ausearch -m avc -ts recent 2>/dev/null | grep -i denied | tail -5
  else
    echo "SELinux not enforcing (or not installed): not the cause"
  fi

  h "Free space and inodes on the host folder"
  df -h "$SRC"; df -i "$SRC"
fi

h "Permission errors in the logs"
docker logs --tail 2000 "$C" 2>&1 | grep -iE 'permission denied|read-only file system|operation not permitted|EACCES|EPERM|no space left' | tail -15 || echo "none in the last 2000 lines"
) 2>&1 | tee "debug-volume-permissions-$(date +%Y%m%d-%H%M%S).txt"
What it checks
  1. Who the container runs asuid / gid inside the container, read-only root filesystem, privileged mode and user namespace remapping
  2. Mountsevery volume and bind mount, which one holds the failing path, and whether it is mounted read-only
  3. The path inside the containernumeric owner and mode as the container sees them, plus a write test that cleans up after itself
  4. The folder on the hosthost owner vs the container's uid, the classic cause, with the exact chown or --user fix
  5. SELinuxon RHEL / Fedora hosts: missing :z / :Z label and recent AVC denials
  6. Free space and inodes'no space left on device' looks like a write failure too
  7. Permission errors in the logsthe exact errors the app reported

Image won't pull or won't run (auth, rate limit, wrong architecture)

Read-only

Paste the full image reference. Checks DNS and HTTPS to the registry, saved logins, the Docker Hub rate limit, the platforms the image is built for vs this host, then pulls it and explains the error.

(
I="<image>"
h() { printf '\n=== %s ===\n' "$*"; }

h "Host and daemon"
echo "Host: $(uname -m)  ->  needs linux/$(uname -m | sed 's/x86_64/amd64/; s/aarch64/arm64/') images"
docker version --format 'Client {{.Client.Version}}  Server {{.Server.Version}}  {{.Server.Os}}/{{.Server.Arch}}' 2>&1
docker info --format 'Mirrors: {{.RegistryConfig.Mirrors}}  HTTPProxy: {{.HTTPProxy}}  HTTPSProxy: {{.HTTPSProxy}}  NoProxy: {{.NoProxy}}' 2>&1

REG=$(echo "$I" | cut -d/ -f1)
case "$REG" in *.*|*:*|localhost) ;; *) REG=docker.io ;; esac
H=$REG; [ "$H" = docker.io ] && H=registry-1.docker.io
h "Registry: $REG"
getent hosts "${H%%:*}" || echo "DNS lookup FAILED for ${H%%:*}: check /etc/resolv.conf or the daemon's dns setting"
curl -sS -m 10 -o /dev/null -w "https://$H/v2/ -> HTTP %{http_code} in %{time_total}s (401 is normal: reachable, login needed)\n" "https://$H/v2/" 2>&1
echo "(TLS / x509 error above = corporate proxy or self-signed registry: add its CA under /etc/docker/certs.d/$H/ca.crt)"

h "Saved logins and credential helpers"
CFG="${DOCKER_CONFIG:-$HOME/.docker}/config.json"
if [ -f "$CFG" ]; then
  grep -oE '"(credsStore|credHelpers)"' "$CFG" | sort -u
  echo "registries in $CFG:"; grep -oE '"(https?://)?[a-z0-9-]+(\.[a-z0-9-]+)+(:[0-9]+)?(/[^"]*)?"' "$CFG" | sort -u
else
  echo "no $CFG: not logged in to any registry as $(id -un)"
fi
case "$REG" in
  *.dkr.ecr.*) echo "ECR login: aws ecr get-login-password --region REGION | docker login --username AWS --password-stdin $REG (token lasts 12 h)";;
  *gcr.io|*-docker.pkg.dev) echo "GCP login: gcloud auth configure-docker $REG";;
  *.azurecr.io) echo "ACR login: az acr login --name ${REG%%.*}";;
esac

if [ "$REG" = docker.io ]; then
  h "Docker Hub pull rate limit for this IP"
  T=$(curl -s "https://auth.docker.io/token?service=registry.docker.io&scope=repository:ratelimitpreview/test:pull" | sed -E 's/.*"token":"([^"]+)".*/\1/')
  curl -s --head -H "Authorization: Bearer $T" https://registry-1.docker.io/v2/ratelimitpreview/test/manifests/latest | grep -iE 'ratelimit-(limit|remaining)' || echo "no rate-limit headers returned"
  echo "(remaining 0 = 'toomanyrequests': log in, use a mirror or a pull-through cache)"
fi

h "Platforms this image is built for"
PL=$(docker buildx imagetools inspect "$I" 2>&1 | grep -E 'Platform:')
[ -n "$PL" ] || PL=$(docker manifest inspect "$I" 2>&1 | grep -E '"(architecture|os|variant)"')
[ -n "$PL" ] && echo "$PL" | sort -u | head -20 || echo "could not read the manifest (see the pull error below)"

h "Pull"
OUT=$(docker pull "$I" 2>&1)
echo "$OUT" | tail -8
case "$OUT" in
  *"pull access denied"*|*"repository does not exist"*) echo "-> wrong name, private repo without login, or no access to it";;
  *"manifest unknown"*|*"not found"*) echo "-> this tag does not exist; check the tag list in the registry";;
  *"no matching manifest"*) echo "-> not built for this host's architecture (see Platforms above)";;
  *toomanyrequests*) echo "-> Docker Hub rate limit (see above)";;
  *unauthorized*|*denied*) echo "-> login missing or expired: docker login $REG";;
  *x509*|*certificate*) echo "-> TLS problem: proxy or private CA (see Registry above)";;
  *timeout*|*"i/o timeout"*|*"connection refused"*) echo "-> network: firewall, proxy or DNS to $H";;
esac

if docker image inspect "$I" >/dev/null 2>&1; then
  h "Local image"
  docker image inspect "$I" --format 'Platform={{.Os}}/{{.Architecture}}{{if .Variant}}/{{.Variant}}{{end}}  Size={{.Size}}  Created={{.Created}}
Entrypoint={{json .Config.Entrypoint}}  Cmd={{json .Config.Cmd}}  User={{.Config.User}}'
  echo "('exec format error' on start = the image platform above does not match this host. Rebuild with --platform, or pull the right one.)"
fi
) 2>&1 | tee "debug-image-pull-$(date +%Y%m%d-%H%M%S).txt"
What it checks
  1. Host and daemonthis host's CPU architecture, Docker version, registry mirrors and proxy settings
  2. RegistryDNS and HTTPS to the registry: 401 means reachable, a timeout or x509 error means network or TLS
  3. Saved loginswhich registries this user is logged in to (no secrets printed) and the login command for ECR / GCR / ACR
  4. Docker Hub rate limitpulls left for this IP: the cause of 'toomanyrequests'
  5. Platformsarchitectures the image is published for: amd64 only on an arm64 host = 'exec format error'
  6. Pullruns the pull and translates the error: access denied, manifest unknown, no matching manifest, unauthorized, x509, timeout
  7. Local imageplatform, entrypoint and user of the image once it is here

Deployed but nothing changed (stale image or old container)

Read-only

No input needed. For every running container: is it running the image its tag points to now, does the registry have a newer build than what was pulled, when was it created, and which Compose project and files it came from.

(
h() { printf '\n=== %s ===\n' "$*"; }
docker info >/dev/null 2>&1 || { echo "Docker daemon not reachable"; exit 1; }

h "Running image vs the tag (local) and the registry"
printf '%-26s %-40s %-17s %s\n' CONTAINER IMAGE CREATED STATUS
docker ps --format '{{.Names}}' | while read -r c; do
  IMG=$(docker inspect "$c" --format '{{.Config.Image}}'); RUN=$(docker inspect "$c" --format '{{.Image}}')
  CR=$(docker inspect "$c" --format '{{.Created}}' | cut -c1-16 | tr T ' ')
  NOW=$(docker image inspect "$IMG" --format '{{.Id}}' 2>/dev/null)
  S=""
  case "$IMG" in sha256:*) S="pinned to an image id";; esac
  if [ -z "$S" ]; then
    if [ -z "$NOW" ]; then S="tag no longer present locally"
    elif [ "$NOW" != "$RUN" ]; then S="STALE: the tag now points to a newer image -> recreate the container"
    else
      LOCAL=$(docker image inspect "$IMG" --format '{{range .RepoDigests}}{{.}} {{end}}' | grep -o 'sha256:[0-9a-f]*' | head -1)
      REMOTE=$(timeout 15 docker buildx imagetools inspect "$IMG" 2>/dev/null | awk '/^Digest:/ {print $2; exit}')
      if [ -z "$LOCAL" ]; then S="OK (built locally, not from a registry)"
      elif [ -z "$REMOTE" ]; then S="OK locally (registry not checked: no access or no buildx)"
      elif [ "$LOCAL" = "$REMOTE" ]; then S="OK: same as the registry"
      else S="REGISTRY NEWER: docker pull, then recreate"; fi
    fi
  fi
  # tag check on the last path part, so registry:5000/app is not mistaken for a tag
  case "${IMG##*/}" in *:latest) TAGNOTE=" (:latest)";; *@*|*:*) TAGNOTE="";; *) TAGNOTE=" (no tag = :latest)";; esac
  printf '%-26s %-40s %-17s %s%s\n' "$c" "$IMG" "$CR" "$S" "$TAGNOTE"
done
echo
echo "STALE = the new image was pulled but the container was only restarted. docker restart keeps the old image and old env: recreate it (docker compose up -d, or docker rm + docker run)."
echo ":latest / no tag = you can't tell which version runs. Deploy with a version tag or digest."

h "Compose projects (where each container was started from)"
docker ps --format '{{.Label "com.docker.compose.project"}}|{{.Label "com.docker.compose.project.working_dir"}}|{{.Label "com.docker.compose.project.config_files"}}|{{.Names}}' \
  | awk -F'|' '$1 != "" {k = $1 "  dir=" $2 "  files=" $3; s[k] = s[k] " " $4} END {for (k in s) print k "\n   containers:" s[k]}'
echo "(edited the compose file or .env? 'docker compose up -d' from that dir recreates only what changed; 'docker compose config' shows the values it actually uses)"

h "Recently created containers (last 10)"
docker ps -a --format '{{.CreatedAt}}\t{{.Names}}\t{{.Image}}\t{{.Status}}' | sort -r | head -10 | cut -c1-19,36-
) 2>&1 | tee "debug-deploy-$(date +%Y%m%d-%H%M%S).txt"
What it checks
  1. Running image vs the tagSTALE = the tag was pulled to a newer image but the container still runs the old one (restarted, never recreated)
  2. Running image vs the registrythe registry has a newer build than what this host pulled, by comparing digests
  3. :latest and untagged imagesflags containers whose version you can't tell
  4. Compose projectsthe project, folder and compose files each container came from, so you redeploy from the right place
  5. Recently created containersdid the deploy actually create new containers, and when?

Compare two containers (works on one, not the other)

Read-only

Paste two container names or IDs. Diffs image and digest, user, entrypoint, limits, env (values hashed, safe to share), mounts, ports, networks and labels, then shows the files changed inside each container. For two hosts: run it on each with the same name twice and diff the reports.

(
A="<container-a>"; B="<container-b>"
h() { printf '\n=== %s ===\n' "$*"; }
for c in "$A" "$B"; do docker inspect "$c" >/dev/null 2>&1 || { echo "No container '$c'. List them with: docker ps -a"; exit 1; }; done
T=$(mktemp -d)

dump() {
  docker inspect "$1" --format 'image {{.Config.Image}}
image-id {{.Image}}
user {{.Config.User}}
entrypoint {{json .Config.Entrypoint}}
cmd {{json .Config.Cmd}}
workdir {{.Config.WorkingDir}}
restart {{.HostConfig.RestartPolicy.Name}}
memory {{.HostConfig.Memory}}
nanocpus {{.HostConfig.NanoCpus}}
pids-limit {{.HostConfig.PidsLimit}}
network-mode {{.HostConfig.NetworkMode}}
read-only {{.HostConfig.ReadonlyRootfs}}
privileged {{.HostConfig.Privileged}}
cap-add {{.HostConfig.CapAdd}}
log {{.HostConfig.LogConfig.Type}} {{.HostConfig.LogConfig.Config}}
{{range .Config.Env}}env {{.}}
{{end}}{{range .Mounts}}mount {{.Destination}} from {{.Type}} {{.Name}}{{if not .Name}}{{.Source}}{{end}} rw={{.RW}}
{{end}}{{range $p, $b := .HostConfig.PortBindings}}port {{$p}} -> {{range $b}}{{.HostIP}}:{{.HostPort}} {{end}}
{{end}}{{range $n, $v := .NetworkSettings.Networks}}network {{$n}}
{{end}}{{range $k, $v := .Config.Labels}}label {{$k}}={{$v}}
{{end}}' | sed 's/^  //' | grep -vE '^label com\.docker\.compose\.(container-number|config-hash|oneoff|replace)=' \
  | while IFS= read -r l; do
      case "$l" in
        env\ *=*) printf '%s=#%s\n' "${l%%=*}" "$(printf %s "${l#*=}" | md5sum | cut -c1-8)";;
        *) printf '%s\n' "$l";;
      esac
    done | sort
}
dump "$A" > "$T/a"; dump "$B" > "$T/b"
docker image inspect "$(docker inspect "$A" --format '{{.Image}}')" --format 'digest {{.RepoDigests}}  created {{.Created}}' >> "$T/a" 2>/dev/null
docker image inspect "$(docker inspect "$B" --format '{{.Image}}')" --format 'digest {{.RepoDigests}}  created {{.Created}}' >> "$T/b" 2>/dev/null

h "Differences ($A = '-', $B = '+')"
if diff -q "$T/a" "$T/b" >/dev/null; then echo "no differences in config"; else diff -u "$T/a" "$T/b" | grep -E '^[-+]([^-+]|$)'; fi
echo "(env values are hashed: same name with a different #hash = different value. Values are never printed.)"

h "Files changed inside $A since it started (first 30)"
docker diff "$A" 2>&1 | head -30
h "Files changed inside $B since it started (first 30)"
docker diff "$B" 2>&1 | head -30
echo "(A = added, C = changed, D = deleted. Edits made by hand inside one container show up here.)"

h "Full config of $A"
cat "$T/a"
h "Full config of $B"
cat "$T/b"
rm -rf "$T"
) 2>&1 | tee "compare-containers-$(date +%Y%m%d-%H%M%S).txt"
What it checks
  1. Differencesonly what differs: image and digest, user, entrypoint, command, limits, restart policy, capabilities, log config, env, mounts, ports, networks and labels
  2. Env values hasheda different #hash for the same variable = a different value, without printing secrets; the report is safe to paste in a ticket
  3. Files changed insidedocker diff of each container: hand edits, generated files or deleted files that exist in only one
  4. Full config of eachthe complete normalized config, so two reports from two hosts can be diffed too

Check a Docker Compose stack and show what's failing

Read-only

Paste the folder with compose.yaml. Validates the file, lists every service, and prints the logs of each service that is not running or not healthy.

(
DIR="<compose-dir>"
h() { printf '\n=== %s ===\n' "$*"; }
cd "$DIR" || exit 1

h "Compose file check"
docker compose config -q && echo "compose file is valid"

h "Services"
docker compose ps -a --format 'table {{.Service}}\t{{.State}}\t{{.Health}}\t{{.ExitCode}}\t{{.Status}}'

h "Logs of services that are not running or not healthy"
BAD=$(docker compose ps -a --format '{{.Service}} {{.State}} {{.Health}}' | awk '$2 != "running" || ($3 != "" && $3 != "healthy") {print $1}' | sort -u)
[ -z "$BAD" ] && echo "all services are running and healthy"
for s in $BAD; do
  h "logs: $s (last 40 lines)"
  docker compose logs --no-color --tail 40 "$s"
done

h "Images in use"
docker compose images
) 2>&1 | tee "debug-compose-$(date +%Y%m%d-%H%M%S).txt"
What it checks
  1. Compose file checksyntax errors, bad indentation and missing variables in compose.yaml / .env
  2. Servicesstate, health, exit code and status of every service
  3. Logs of failing servicesthe last 40 log lines of each service that is exited, restarting or unhealthy
  4. Images in usewhich image and tag each container runs

Image build is slow or the cache never hits

Read-only

Paste the build folder (where the Dockerfile is). Measures the real build context after .dockerignore, finds Dockerfile patterns that break the layer cache, checks base image pull time and the BuildKit cache size. It builds nothing you keep.

(
D="<build-folder>"
h() { printf '\n=== %s ===\n' "$*"; }
cd "$D" 2>/dev/null || { echo "No folder '$D'"; exit 1; }
F=Dockerfile; [ -f "$F" ] || F=$(ls Dockerfile* *.Dockerfile 2>/dev/null | head -1)
[ -f "$F" ] || { echo "No Dockerfile in $D"; exit 1; }
echo "folder: $(pwd)  dockerfile: $F"

h "Build context: what gets sent to the builder"
if [ -f .dockerignore ]; then echo ".dockerignore:"; sed 's/^/  /' .dockerignore
else echo "PROBLEM: no .dockerignore: .git, node_modules, build output, logs and .env are all sent (and .env can end up in the image)"; fi
echo "folder on disk: $(du -sh . 2>/dev/null | cut -f1), biggest entries:"
du -sh ./* ./.[!.]* 2>/dev/null | sort -rh | head -8 | sed 's/^/  /'
echo "measuring the real context after .dockerignore (throwaway build, nothing is kept):"
OUT=$(printf 'FROM busybox:1.36\nCOPY . /ctx\nRUN du -sh /ctx && echo "files: $(find /ctx -type f | wc -l)" && du -sh /ctx/* /ctx/.[!.]* 2>/dev/null | sort -rh | head -5\n' \
  | docker buildx build --no-cache --progress=plain --output type=cacheonly -f - . 2>&1 \
  | grep -E 'transferring context:|[0-9.]+[KMG]?\s+/ctx|files:' | sed -E 's/^#[0-9]+ [0-9.]+ //' | head -10)
[ -n "$OUT" ] && echo "$OUT" || echo "could not measure (needs docker buildx). The 'transferring context' line of your next build shows the size."

h "Dockerfile patterns that break the cache"
grep -nE '^\s*(FROM|COPY|ADD|RUN)' "$F" | cut -c1-150
echo
CP=$(grep -nE '^\s*(COPY|ADD)\s+(--[^ ]+\s+)*\.\s' "$F" | head -1 | cut -d: -f1)
IN=$(grep -nE 'npm (ci|install)|yarn install|pnpm install|pip install|poetry install|go mod download|mvn |gradle|bundle install|composer install|cargo (build|fetch)' "$F" | head -1 | cut -d: -f1)
[ -n "$CP" ] && [ -n "$IN" ] && [ "$CP" -lt "$IN" ] && echo "PROBLEM (line $CP): COPY . comes before installing dependencies (line $IN), so every code change reinstalls them. Copy only the lock / manifest files first, install, then COPY . ."
grep -nE 'apt-get update' "$F" | grep -v 'install' | sed 's/^/PROBLEM: apt-get update in its own RUN (cached forever, installs go stale): line /'
grep -nE '^\s*ADD\s+https?://' "$F" | sed 's/^/NOTE: ADD from a URL is re-downloaded and checked every build: line /'
grep -niE '^\s*FROM\s' "$F" | grep -viE 'FROM\s+(--[^ ]+\s+)*[^ ]+:[^ ]*[0-9]|@sha256|\$|FROM\s+scratch' | sed 's/^/NOTE: base image without a version tag: line /'
grep -qE 'mount=type=cache' "$F" || echo "TIP: RUN --mount=type=cache,target=/root/.npm (or ~/.cache/pip, /go/pkg/mod) keeps package downloads between builds"
[ "$(grep -ciE '^\s*FROM' "$F")" -gt 1 ] || echo "TIP: single-stage build: a multi-stage build keeps compilers and caches out of the final image"

h "Base image pull time"
for I in $(awk 'toupper($1) == "FROM" {for (i = 2; i <= NF; i++) if ($i !~ /^--/) {print $i; break}}' "$F" | grep -v '\$' | sort -u); do
  [ "$I" = scratch ] && continue
  grep -qiE "\sAS\s+$I(\s|$)" "$F" && continue
  S=$(date +%s); docker pull -q "$I" >/dev/null 2>&1 && echo "  $I: $(( $(date +%s) - S ))s" || echo "  $I: pull failed"
done

h "Builder and cache"
docker buildx ls 2>/dev/null | head -5
if docker buildx du >/dev/null 2>&1; then docker buildx du | tail -2; fi
docker buildx history ls 2>/dev/null | head -6
echo "(CI runners start with an empty cache every time: use --cache-from / --cache-to type=registry or type=gha)"
) 2>&1 | tee "debug-build-$(date +%Y%m%d-%H%M%S).txt"
What it checks
  1. Build contextmissing .dockerignore, the biggest folders, and the real context size and file count after .dockerignore, measured with a throwaway build
  2. Cache-breaking patternsCOPY . before installing dependencies, apt-get update in its own layer, ADD from URLs, unversioned base images, no cache mounts, single-stage builds
  3. Base image pull timehow long each FROM image takes to pull (skips build stages and ARG-based images)
  4. Builder and cacheactive builder, BuildKit cache size and recent build history, plus the CI cache flags

What is filling the disk under Docker (logs, images, volumes, cache)

Read-only

No input needed. Breaks down Docker's disk use: the biggest container log files, containers with no log rotation, writable layers, images, volumes and build cache. Prints the cleanup commands but runs none of them.

(
h() { printf '\n=== %s ===\n' "$*"; }
R=$(docker info --format '{{.DockerRootDir}}' 2>/dev/null) || { echo "Docker daemon not reachable"; exit 1; }

h "Disk holding $R"
df -h "$R"; df -i "$R"

h "Docker's own summary"
docker system df

h "Biggest container log files"
sudo find "$R/containers" -name '*-json.log' -printf '%s %p\n' 2>/dev/null | sort -rn | head -10 | while read -r SIZE F; do
  ID=$(basename "$(dirname "$F")")
  printf '%8s MB  %s\n' "$((SIZE / 1048576))" "$(docker inspect --format '{{.Name}}' "$ID" 2>/dev/null || echo "$ID (removed)")"
done
echo "(a log file can be emptied without restarting: sudo truncate -s 0 FILE)"

h "Log rotation"
docker info --format 'Default log driver: {{.LoggingDriver}}'
sudo grep -A4 '"log-opts"' /etc/docker/daemon.json 2>/dev/null || echo "no log-opts in /etc/docker/daemon.json: json-file logs grow forever by default"
echo "Containers with json-file logs and no max-size:"
docker ps -aq | xargs -r docker inspect --format '{{.Name}} {{.HostConfig.LogConfig.Type}} {{index .HostConfig.LogConfig.Config "max-size"}}' 2>/dev/null \
  | awk '$2 == "json-file" && $3 !~ /[0-9]/ {print "  " $1; n++} END {if (!n) print "  none"}'

h "Biggest container writable layers"
docker ps -a --size --format '{{.Size}}\t{{.Names}}\t{{.Status}}' | sort -rh | head -10
echo "(a large writable layer = the app writes data or logs inside the container instead of a volume)"

h "Biggest images"
docker images --format '{{.Size}}\t{{.Repository}}:{{.Tag}}\t{{.CreatedSince}}' | sort -rh | head -10
echo "dangling (untagged) images: $(docker images -qf dangling=true | wc -l)"

h "Volumes"
echo "VOLUME  LINKS  SIZE"
docker system df -v 2>/dev/null | awk '/^VOLUME NAME/ {v = 1; next} /^$/ || /^Build cache/ {v = 0} v' | sort -k3 -rh | head -12
echo "volumes not used by any container: $(docker volume ls -qf dangling=true | wc -l)"

h "Build cache"
if docker buildx du >/dev/null 2>&1; then docker buildx du | tail -3; else docker system df | grep -i 'build cache'; fi

h "Cleanup commands (not run: review first)"
echo "docker container prune                     # stopped containers"
echo "docker image prune                         # dangling images"
echo "docker image prune -a --filter until=168h  # unused images older than 7 days"
echo "docker builder prune --filter until=168h   # build cache older than 7 days"
echo "docker volume prune                        # unused volumes: DELETES DATA, check the list above"
echo 'log rotation in /etc/docker/daemon.json:   {"log-driver": "json-file", "log-opts": {"max-size": "50m", "max-file": "3"}} then restart dockerd; applies to new containers'
) 2>&1 | tee "debug-docker-disk-$(date +%Y%m%d-%H%M%S).txt"
What it checks
  1. Disk holding the Docker rootspace and inodes on the filesystem under /var/lib/docker (or wherever Docker keeps data)
  2. Docker's own summaryimages, containers, volumes and build cache, with how much is reclaimable
  3. Biggest container log filesthe usual culprit: json-file logs with no size limit, by container name
  4. Log rotationdaemon-wide log options and every container that has no max-size
  5. Biggest writable layerscontainers writing data inside themselves instead of to a volume
  6. Biggest imageslarge and dangling images
  7. Volumeslargest volumes and how many are not used by any container
  8. Build cacheBuildKit cache that can grow to tens of GB on CI hosts
  9. Cleanup commandssafe-first prune commands and the log rotation config; nothing is deleted by the script

Docker host health (daemon, disk, broken containers)

Read-only

No input needed. Checks the Docker daemon, its disk usage, containers that are restarting or exited with an error, daemon warnings and kernel OOM kills.

(
h() { printf '\n=== %s ===\n' "$*"; }

h "Daemon"
systemctl is-active docker 2>/dev/null
docker version --format 'client {{.Client.Version}}  server {{.Server.Version}}' || { echo "Cannot talk to the Docker daemon (is it running? are you in the docker group?)"; exit 1; }
docker info --format 'containers={{.Containers}} running={{.ContainersRunning}} stopped={{.ContainersStopped}} images={{.Images}} storage={{.Driver}} logging={{.LoggingDriver}} root={{.DockerRootDir}}'

h "Disk"
df -h "$(docker info --format '{{.DockerRootDir}}')"
docker system df

h "Containers restarting or exited with an error"
docker ps -a --filter status=restarting --format 'table {{.Names}}\t{{.Status}}\t{{.Image}}'
docker ps -a --filter status=exited --format '{{.Names}}\t{{.Status}}\t{{.Image}}' | grep -v 'Exited (0)' || echo "no containers exited with an error"

h "Unhealthy containers"
docker ps --filter health=unhealthy --format 'table {{.Names}}\t{{.Status}}'

h "Daemon warnings and errors (last hour)"
journalctl -u docker --since "1 hour ago" -p warning --no-pager 2>/dev/null | tail -30

h "Kernel OOM kills (last day)"
journalctl -k --since "1 day ago" --no-pager 2>/dev/null | grep -iE 'out of memory|killed process' | tail -10 || true
) 2>&1 | tee "debug-docker-host-$(date +%Y%m%d-%H%M%S).txt"
What it checks
  1. Daemonis Docker running, versions, counts, storage and logging driver, data folder
  2. Diskfree space where Docker keeps its data, and what images, containers, volumes and build cache use
  3. Restarting / exited containerscontainers stuck in a restart loop or that stopped with a non-zero exit code
  4. Unhealthy containersrunning containers whose health check fails
  5. Daemon warningserrors from dockerd itself: pull failures, storage problems, network conflicts
  6. Kernel OOM killsprocesses the kernel killed for lack of memory

My DevOps Playbook by Angelo John Calleja

New runbook

GitHub not connected

Saving is handled by the site: the GitHub token is stored in Cloudflare, not in your browser. Enter the editor password (the EDITOR_PASSWORD secret) to unlock saving in this browser.

Saving commits to gelogrammer/My_DevOps_Playbook. Create a fine-grained token with access to only this repo andContents: Read and write, then paste it here. It is stored only in this browser.

src/content/docs/…