Skip to main content

Docker Container Keeps Restarting: Exit Codes, Logs, Fixes

Docker container keeps restarting? Read the exit code, check logs from the failed run, stop the loop safely, and fix the usual causes, including Caddy in Compose.

When a Docker container keeps restarting, its main process keeps exiting and the restart policy keeps starting it again. Read the exit code and the OOMKilled flag with docker inspect, then read the logs from the run that failed. Those two things tell you whether the cause is an app error, a missing command, memory, or a process that finishes on purpose. We debug this a lot on our own servers, usually with a terminal and DockLab's Docker Assistant open side by side.

Quick answer

  • Find the loop: docker ps -a --filter status=restarting
  • Get the facts: docker inspect -f 'exit={{.State.ExitCode}} oom={{.State.OOMKilled}} restarts={{.RestartCount}}' NAME
  • Read why it died: docker logs --tail 100 -t NAME (with the default json-file driver, logs survive restarts until you recreate the container)
  • Stop the loop while you debug: docker update --restart=no NAME && docker stop NAME
  • Match the exit code: 1 means an app error, 126 or 127 means the command can't run or can't be found, 137 with oom=true means memory, and 0 means the process finished and restart: always started it again

How Docker's restart loop actually works

A restart policy is just the daemon reacting to an exit. Docker's restart policy documentation defines four values:

PolicyRestarts on non-zero exitRestarts on exit 0After manual docker stopAfter daemon restart
no (default)NoNoStays downStays down
on-failure[:N]Yes, up to N times if setNoStays downNot restarted
alwaysYesYesStays down until you start itStarts again
unless-stoppedYesYesStays downStays down

Two details matter when you debug. First, the docker run reference says the daemon adds "an increasing delay (double the previous delay, starting at 100 milliseconds)" before each restart. So a container that crashes instantly ends up restarting slowly, and docker ps shows Restarting (1) 3 seconds ago most of the time you look at it. Second, a restart policy only takes effect after the container has stayed up for at least 10 seconds once. That's why a container that is broken from its first start can look different from one that ran fine for a week and then started crashing.

The table also tells you which policy fits the job. A long-running service wants unless-stopped. A one-shot job such as a migration wants no or on-failure:3. Putting restart: always on a job that is meant to exit is one of the most common restart loops we see.

Read the exit code first

Run this before anything else. It gives you the whole picture on one line:

docker inspect -f 'status={{.State.Status}} exit={{.State.ExitCode}} oom={{.State.OOMKilled}} restarts={{.RestartCount}} started={{.State.StartedAt}} finished={{.State.FinishedAt}} err={{.State.Error}}' myapp

If started and finished are a second apart, the process dies during startup. If they are hours apart, something at runtime is killing it: memory growth, a dependency going away, or a scheduled job.

Docker's container run guide reserves three codes. Everything else comes from your process, and codes above 128 follow the Unix convention of 128 plus the signal number.

Exit codeMeaningUsual causeFirst thing to check
0Process finished normallyOne-shot command, or a server that daemonized itself into the backgroundIs restart: always set on something meant to exit?
1 (or other small numbers)App reported an errorMissing env var, bad config, can't reach the database, no write permission on a volumedocker logs
125Docker daemon errorInvalid run options, failed mount or port binding.State.Error, daemon logs
126Command can't be invokedEntrypoint script not executablels -l on the script inside the image
127Command not foundTypo in command:, binary missing from a slim image, wrong PATHdocker inspect -f '{{.Config.Entrypoint}} {{.Config.Cmd}}'
137SIGKILL (128+9)Memory limit hit, or killed after the stop timeoutOOMKilled flag, kernel log
139SIGSEGV (128+11)Native crash, wrong-architecture librariesLogs, image architecture
143SIGTERM (128+15)Something stopped it on purposeDeploy scripts, cron, update tools

Read the logs from the run that failed

docker logs reads the container's log stream, and with the default json-file driver that stream covers every run since the container was created. So the crash output from the previous attempt is still there, mixed in with the current one. Timestamps keep the runs apart:

docker logs --tail 100 -t myapp
docker logs --since 15m -t myapp 2>&1 | grep -iE 'error|fatal|panic|denied|not found'

The flags (--tail, --since, -t, --until) are documented on the docker logs reference. With Compose, use the service name instead: docker compose logs --tail 100 -t app.

One catch: docker compose up -d after a config change recreates the container, and that throws away the old container's logs. Capture them before you redeploy.

To see how often it dies, and whether the kernel was involved, watch the event stream. The docker events reference lists die, oom and restart as container events:

docker events --since 30m --filter type=container --filter container=myapp \
  --format '{{.Time}} {{.Action}} exit={{.Actor.Attributes.exitCode}}'

If you see oom events, or the inspect line shows oom=true, check the kernel log too:

sudo journalctl -k --since "1 hour ago" | grep -iE 'out of memory|oom-kill|killed process'

Stop the loop before you debug

A container that restarts every few seconds is hard to examine: docker exec fails half the time and the logs keep moving. Pause it first.

  1. Disable the restart policy

    docker update --restart=no myapp changes the policy on the existing container without recreating it, so the logs stay where they are.

  2. Stop it

    docker stop myapp. Docker's documentation notes that a manually stopped container ignores its restart policy until you start it again or the daemon restarts, so this alone usually breaks the loop.

  3. Open a shell in the same image

    Bypass the entrypoint so you can look around: docker run --rm -it --entrypoint sh myimage:tag, or for Compose, docker compose run --rm --entrypoint sh app. The Compose version keeps the service's env vars, volumes and networks, which is usually what you want.

  4. Run the real command by hand

    Inside that shell, run the original entrypoint and command. You'll see the error directly instead of piecing it together from logs, and you can test fixes before you rebuild.

The usual causes, by exit code

Exit 0: the process ends and Docker restarts it

A container lives exactly as long as its main process. If that process is a shell script that starts a server in the background and then exits, or a server that daemonizes itself, the container exits with 0 and restart: always brings it back, over and over. The fix is to run the server in the foreground (nginx -g 'daemon off;', exec node server.js at the end of the entrypoint script). For real one-shot jobs, set restart: "no".

Exit 1: the app is failing on its own terms

This is usually the most readable case, because the app tells you what went wrong. The usual messages:

  • Missing configuration. An env var isn't set because the .env file isn't next to compose.yaml, or a secret mount path is wrong. Run docker compose config to see the fully resolved file, including which variables ended up empty.
  • Dependency not ready. The app starts before Postgres accepts connections, exits, and keeps restarting until the database is up. Plain depends_on only orders startup. The Compose services reference explains that condition: service_healthy waits for the dependency's healthcheck to pass.
  • Volume permissions. The image runs as a non-root UID and the bind-mounted host directory belongs to root. Compare docker exec myapp id with ls -ln on the host directory.
  • Disk full. Databases and anything that writes logs or temp files will crash at startup. Check df -h /var/lib/docker, and if it's tight, see our guide on what to delete when a Linux server disk is full.

Here is the healthcheck pattern that fixes the dependency case:

services:
  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 3s
      retries: 10
      start_period: 10s
    restart: unless-stopped

  app:
    build: .
    depends_on:
      db:
        condition: service_healthy
    restart: unless-stopped

Your app should still retry its database connection. depends_on only covers first startup, not a database that restarts later.

Exit 126 and 127: the command can't run

127 means the binary isn't in the image or isn't on PATH. This is common after switching to an Alpine or distroless base where bash doesn't exist. Check what Docker is actually trying to run with docker inspect -f '{{.Config.Entrypoint}} {{.Config.Cmd}}' myapp. 126 almost always means an entrypoint script is missing its execute bit. Add RUN chmod +x /entrypoint.sh to the Dockerfile, or COPY --chmod=755.

Two related errors show up in the logs rather than in a distinct exit code. exec format error means the image was built for a different CPU architecture (compare docker image inspect -f '{{.Architecture}}' myimage with uname -m). And no such file or directory for a script that clearly exists usually means Windows CRLF line endings in the shebang line.

Exit 137: killed, usually for memory

If OOMKilled is true, the container hit its memory limit, or the host ran out of memory. Either raise the limit (mem_limit in Compose, --memory on docker run) or find out why usage grows. A JVM or Node process sized for the whole host, rather than the container limit, is a classic cause. If OOMKilled is false and the code is 137, something sent SIGKILL. Most often that's docker stop killing a process that ignored SIGTERM for longer than the stop timeout.

Exit 143: someone asked it to stop

SIGTERM loops come from outside the container: a deploy script on a cron, an auto-update tool, a systemd unit that runs docker compose up repeatedly. The docker events output from earlier, together with journalctl and crontab -l, will show who is sending it.

A note on healthchecks

Standalone Docker Engine does not restart a container just because its healthcheck reports unhealthy. That only marks the status. If you see restarts lined up with healthcheck failures, look for an external tool that acts on health status, or for the app exiting on its own.

Caddy in docker-compose: the restart loops we see most

Caddy in front of an app is the setup from our guide on deploying a Docker Compose app to a VPS behind Caddy, and it has its own failure modes.

  • Caddyfile syntax error. Caddy refuses to start with an invalid config and exits non-zero. Validate before restarting: docker compose run --rm caddy caddy validate --config /etc/caddy/Caddyfile.
  • Caddyfile mounted as a single file. The official Caddy image page says not to mount the Caddyfile directly at /etc/caddy/Caddyfile. When an editor saves by replacing the file, the container keeps the old inode, so edits don't apply and reloads can fail. Mount the directory instead.
  • Port 80 or 443 already taken. A host Nginx or Apache still holds the port, so the container can't bind. Check with sudo ss -tlnp | grep -E ':(80|443)\b'.
  • Lost /data volume. Without a persistent /data, every recreate asks Let's Encrypt for new certificates, and repeated restarts can hit rate limits. The image docs say this directory "must not be treated as a cache".

A setup that avoids all four:

services:
  caddy:
    image: caddy:2
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
      - "443:443/udp"
    volumes:
      - ./conf:/etc/caddy
      - caddy_data:/data
      - caddy_config:/config

volumes:
  caddy_data:
  caddy_config:

After editing ./conf/Caddyfile, reload without restarting the container: docker compose exec -w /etc/caddy caddy caddy reload. If Caddy is fine but the app behind it keeps restarting, visitors get a 502, and our Nginx 502 diagnostic order applies almost step for step.

Tools for watching a restart loop

You can do everything above with the Docker CLI over SSH, and for a one-off incident that's all you need. Where tools help is in seeing status, logs and config together while you change things.

ToolWhere it runsGood atWeaker at
Docker CLI over SSHAny terminalComplete, scriptable, nothing to installJuggling several commands and windows
lazydockerTerminal UI on the serverFast keyboard view of containers and logsEditing files, multiple hosts
PortainerWeb UI deployed on the hostBrowser access, many container featuresOne more service to run and secure
DockLab Docker AssistantDesktop app over SSHLive container status, compose detection, start/stop/restart next to the terminal, SFTP and editorNot a replacement for full container platforms, and needs a DockLab account

Our own setup: one pane runs docker logs -f, the Docker Assistant sidebar shows the container flipping between running and restarting, and the remote editor has compose.yaml open. If you paste logs into an AI assistant, our notes on using AI to debug server errors cover what to redact. To see how DockLab compares with Termius, Warp and MobaXterm, including where those tools are stronger, see the comparison page. Plugins are listed by plan on pricing.

Frequently Asked Questions

Why does docker ps show "Restarting" but docker logs is empty?

The process is probably failing before it writes anything, which is typical for exit codes 126 and 127 or a daemon-side error (125). Check .State.Error and the exit code with docker inspect. Then run the image with --entrypoint sh and start the command by hand to see the error directly.

How do I stop a container that keeps restarting without deleting it?

Run docker update --restart=no NAME and then docker stop NAME. This keeps the container, its logs and its inspect data, so you can still investigate. Turn the policy back on later with docker update --restart=unless-stopped NAME.

Does docker compose restart a container when its healthcheck fails?

Not on standalone Docker Engine: an unhealthy status is only a label. Compose uses healthchecks to order startup through depends_on with condition: service_healthy. If you need automatic recovery, make the app exit on fatal errors and let the restart policy handle it.

What does exit code 137 mean if OOMKilled is false?

The process got SIGKILL from something other than the memory limit. The most common case is docker stop or docker compose down killing a process that didn't exit within the stop timeout after SIGTERM. Check whether your app handles SIGTERM, and use docker events to see what stopped it.

Should I use restart: always or unless-stopped?

For long-running services, unless-stopped is usually the better default because a container you stopped by hand stays stopped after a reboot or daemon restart. Use always only if you want the container back even after you stopped it manually. For one-shot jobs, use no or on-failure with a retry limit.

Try it on your own servers

SSH, SFTP, a remote editor, a browser and AI in one desktop workspace.

DockLab runs on macOS, Windows and Linux. Start free and keep your whole server workflow in one window.

About the author

· Co-founder, Legacies

Horia builds DockLab and spends most days on remote servers, deploy pipelines and the tooling around them.