Docker Container Exits Right After Starting

The container starts, runs for a second, and dies with no obvious error. Almost always one of three things: the app needs a foreground process, the command is wrong, or PID 1 is misbehaving.

What you'll see

Root causes

The main process daemonizes itself

nginx, sshd, and many daemons fork to background by default. PID 1 exits, the container dies. Docker containers need the process to stay in the foreground.

Wrong command or missing arguments

The image's default CMD does not match what you passed; the entrypoint exits 1 or 127 (command not found). Exit 127 = the binary path is wrong.

PID 1 signal/zombie problems

The app as PID 1 doesn't reap zombies or handle SIGTERM; behavior looks fine at first then degrades. Use an init process.

Fix it

  1. Read the exit logs before anything else
    docker logs --tail 50 <container>
  2. For daemons, run the foreground variant
    CMD ["nginx", "-g", "daemon off;"]   # or sshd -D, httpd -D FOREGROUND
  3. Let Docker's built-in init handle PID 1 duties
    docker run --init myapp   # compose: init: true
  4. For a crash loop, see what exits and when
    docker inspect <container> --format '{{.State.ExitCode}} {{.State.OOMKilled}}'

Field note

Exit 0 with instant death almost always means 'daemonized itself'. Exit 1 with a stack trace in the logs is an app-level crash — fix the app, not the container.

Common questions

Why does my container exit with code 0 immediately?

The main process finished — for service images it's usually a command override or entrypoint misconfiguration that runs a short-lived command instead of the daemon. docker logs shows what ran; the fix is the right CMD/entrypoint for a foreground process.

Is restarting the container a fix?

With restart=always it just crash-loops faster — the process exits for a reason (crash, config error, missing env). Read the logs of the exited container and fix the exit cause; restart policy is recovery, not repair.

Ship it right the first time

A production-shaped compose stack: healthchecks, resource limits, log rotation. Never debug a boot race again.

Docker Production Starter — $19 →

One-time. Yours to modify. Instant download from the NinjaOps template store.