TExcelTAD
Home › Docker Compose › Logs & Debugging

Logs & Debugging

Something is wrong: a service keeps restarting, the API answers 502, a container exits right after up. With several containers involved, the first job is to find which one is unhappy and why. Compose gives you a small, consistent toolkit for that. This lesson walks through it in the order you'd usually reach for each tool. For the single-container commands underneath (docker logs, docker inspect), see Logs, Exec & Inspect and Debugging Containers.

1. What's running? ps

bash
$ docker compose ps -a
NAME            IMAGE                  COMMAND                  SERVICE   CREATED          STATUS                       PORTS
demo-api-1      ghcr.io/acme/api:3.1   "gunicorn app:app"       api       2 minutes ago    Restarting (1) 8 seconds ago
demo-db-1       postgres:17            "docker-entrypoint.s…"   db        2 minutes ago    Up 2 minutes (healthy)       5432/tcp
demo-worker-1   ghcr.io/acme/api:3.1   "celery -A app worker"   worker    2 minutes ago    Exited (137) 1 minute ago

(sample output) -a includes stopped containers, which is where the interesting ones hide. Read the STATUS column carefully: Restarting (1) is a crash loop with exit code 1; Exited (137) means the process was killed; (unhealthy) means the healthcheck fails while the process still runs.

Exit codes follow a convention: values above 128 mean "killed by signal number code − 128".

python · try it yourself
import signal

def explain(code):
    if code == 0:
        return "finished successfully (a one-off job, or a command that doesn't stay in the foreground)"
    if code > 128:
        sig = code - 128
        name = signal.Signals(sig).name
        hints = {"SIGKILL": "killed: out of memory (check `docker inspect` State.OOMKilled) or `docker kill`",
                 "SIGTERM": "stopped on request (docker stop / compose down), app didn't exit 0",
                 "SIGSEGV": "crashed: segmentation fault in native code"}
        return f"killed by {name} ({sig}): {hints.get(name, 'signal')}"
    if code in (126, 127):
        return "command could not run: 127 = not found (typo, missing binary, wrong PATH), 126 = not executable"
    return "the application exited with an error: read its logs"

for code in [0, 1, 127, 137, 139, 143]:
    print(f"exit {code:>3}: {explain(code)}")
exit   0: finished successfully (a one-off job, or a command that doesn't stay in the foreground)
exit   1: the application exited with an error: read its logs
exit 127: command could not run: 127 = not found (typo, missing binary, wrong PATH), 126 = not executable
exit 137: killed by SIGKILL (9): killed: out of memory (check `docker inspect` State.OOMKilled) or `docker kill`
exit 139: killed by SIGSEGV (11): crashed: segmentation fault in native code
exit 143: killed by SIGTERM (15): stopped on request (docker stop / compose down), app didn't exit 0

2. What did it say? logs

bash
$ docker compose logs api                  # one service
$ docker compose logs -f --tail 50         # follow all services, last 50 lines each
$ docker compose logs --since 10m worker   # time window
$ docker compose logs -t api               # with timestamps
$ docker compose logs --no-log-prefix api  # without the "api-1 | " prefix (for grep, jq)

Compose merges the logs of all containers of all selected services, prefixed with the container's name and coloured per service. For a crash loop, the first lines after a start are usually the useful ones; --tail and --since keep the noise down.

Logs only exist if the container writes to stdout/stderr. An app that logs to /var/log/app.log inside the container shows nothing here: configure it to log to the console (the Twelve-Factor way).

Log drivers and rotation

By default Docker stores logs as JSON files on the host, without rotation unless the daemon is configured otherwise. A chatty service can fill the disk. Set limits per service, ideally through a fragment:

compose · try it yourself
x-logging: &logging
  driver: local
  options:
    max-size: 20m
    max-file: "5"

services:
  api:
    image: ghcr.io/acme/api:3.1
    logging: *logging
  worker:
    image: ghcr.io/acme/api:3.1
    command: ["celery", "-A", "app", "worker"]
    logging: *logging
name: demo
services:
  api:
    image: ghcr.io/acme/api:3.1
    logging:
      driver: local
      options:
        max-file: "5"
        max-size: 20m
    networks:
      default: null
  worker:
    command:
      - celery
      - -A
      - app
      - worker
    image: ghcr.io/acme/api:3.1
    logging:
      driver: local
      options:
        max-file: "5"
        max-size: 20m
    networks:
      default: null
networks:
  default:
    name: demo_default
x-logging:
  driver: local
  options:
    max-file: "5"
    max-size: 20m

The local driver is compact and rotates; json-file is the default and what most log shippers expect. Drivers like syslog, journald, fluentd, gelf or awslogs send logs elsewhere; with most of them docker compose logs can still read the logs, because Docker keeps a local copy (the "dual logging" cache).

3. What is it doing? exec, top, events

bash
$ docker compose exec api sh                       # look around inside
$ docker compose exec api env | sort               # the environment it really got
$ docker compose exec api wget -qO- http://db:5432 # can it reach db? (connection refused = reachable)
$ docker compose top                               # processes in every container
$ docker compose events --json                     # live stream: create, start, die, health_status…
$ docker compose stats                             # CPU / memory per container

exec needs a running container. For a container that crashes immediately, override its command so it stays up, and investigate:

bash
$ docker compose run --rm --entrypoint sh api      # same image, env, networks, volumes; a shell instead of the app

4. Is the configuration what I think? config

Many "bugs" are configuration: a variable that didn't interpolate, an override file that wasn't loaded, a port mapping on the wrong service. docker compose config shows the effective configuration, after merging every file and resolving every variable. When in doubt, read it before reading code.

Two flags help with "why was my container recreated?". --images lists what will run, and --hash prints the configuration hash Compose stores in a label on each container (com.docker.compose.config-hash). On up, a service whose hash differs from its container's label is recreated:

compose · try it yourself
# $ docker compose config --images
# $ docker compose config --hash api,db
services:
  api:
    image: ghcr.io/acme/api:3.1
    environment:
      LOG_LEVEL: info
  db:
    image: postgres:17
$ docker compose config --images
ghcr.io/acme/api:3.1
postgres:17
$ docker compose config --hash api,db
api 03a138109a9879e40bf34bad4a35655de39625690150b128f29db826514003bc
db 116352783c1b67f7d1688ae9e461c4198c0d5d905f3e30389f95bb47aea3efca
bash
$ docker inspect demo-api-1 --format '{{index .Config.Labels "com.docker.compose.config-hash"}}'

If that value differs from the one config --hash api prints, the next up recreates api. Change one environment variable and only that service's hash changes, which is why up -d after a small edit restarts only one container.

A debugging checklist

python · try it yourself
symptoms = {
    "Exited (127)":                      "typo in command/entrypoint, or binary missing in the image -> run --entrypoint sh, check PATH",
    "Restarting (1), 'connection refused' to db": "started before db was ready -> depends_on: condition: service_healthy + a healthcheck",
    "Exited (137), OOMKilled true":      "memory limit too low or a leak -> raise deploy.resources.limits.memory, check docker compose stats",
    "(unhealthy) but app works":         "healthcheck command wrong or missing in image (curl not installed?) -> docker inspect .State.Health",
    "502 from proxy":                    "proxy points to wrong name/port -> use service name + container port, check both share a network",
    "works locally, variable empty here": "interpolation: variable not in .env/shell -> docker compose config, config --variables",
    "old code still running":            "image not rebuilt or volume hides new files -> up --build, check volumes over app paths",
}
for symptom, fix in symptoms.items():
    print(f"- {symptom}\n    {fix}")
- Exited (127)
    typo in command/entrypoint, or binary missing in the image -> run --entrypoint sh, check PATH
- Restarting (1), 'connection refused' to db
    started before db was ready -> depends_on: condition: service_healthy + a healthcheck
- Exited (137), OOMKilled true
    memory limit too low or a leak -> raise deploy.resources.limits.memory, check docker compose stats
- (unhealthy) but app works
    healthcheck command wrong or missing in image (curl not installed?) -> docker inspect .State.Health
- 502 from proxy
    proxy points to wrong name/port -> use service name + container port, check both share a network
- works locally, variable empty here
    interpolation: variable not in .env/shell -> docker compose config, config --variables
- old code still running
    image not rebuilt or volume hides new files -> up --build, check volumes over app paths

Debugging startup order

When the API logs could not connect to server once and then works, it's a race: the API started before Postgres accepted connections. depends_on with condition: service_healthy fixes the start, but connections can still drop later (database restart, failover). Robust apps retry. See depends_on & Startup Order and Healthchecks.

Learn more: A Development Workflow · Swarm Logging & Monitoring · Kubernetes Troubleshooting

Test yourself

A container shows Exited (137). What does that most often mean?

  1. The command was not found
  2. It was killed with SIGKILL, often by the OOM killer
  3. It finished successfully
  4. A segmentation fault

A service crashes right after start, so exec fails. How do you get a shell with the same image and settings?

  1. docker compose logs --shell
  2. docker compose run --rm --entrypoint sh <service>
  3. docker compose restart --debug
  4. docker attach

How does Compose decide that up -d must recreate a service?

  1. Every service is always recreated
  2. It compares the service's configuration hash with the label on the existing container
  3. It checks the image size
  4. Only when the image tag changes