Skip to content
|By Muhammad Wilayat Shah|33 views • 33 unique IPs

Why Docker Containers Keep Restarting (and How to Fix It)

A school ERP export worker looped on staging and the team wanted to rebuild the image. The exit code and logs showed a missing variable in two minutes. Here is how to find the real cause of any Docker restart loop.

ShareLinkedInX
Four exit code checks for a Docker container that keeps restarting: exit 1 or 2 for a startup crash such as a missing variable, exit 0 for a main process that ended, exit 137 with OOMKilled true for memory, and exit 126 or 127 for a command that is missing or not executable
Four exit code checks for a Docker container that keeps restarting: exit 1 or 2 for a startup crash such as a missing variable, exit 0 for a main process that ended, exit 137 with OOMKilled true for memory, and exit 126 or 127 for a command that is missing or not executable

Last reviewed: 24 Nov 2026

The week before a school ERP term start, our results-export worker on the staging server went into a loop: docker ps showed Restarting (2) 4 seconds ago, over and over. The container never lived long enough to docker exec into, and the first instinct in the team was "Docker is broken, rebuild the image". Rebuilding would have changed nothing. A container is just its main process, and that process kept exiting. Once I read the exit code and the last log lines, it took two minutes: a DATABASE_URL variable that existed in production's .env and not on staging.

A restart loop is never Docker's fault. The container lives exactly as long as PID 1. When PID 1 exits, for any reason, the container stops, and a restart policy (--restart always, unless-stopped, on-failure, or restart: in Compose) starts it again. So the only real question is: why does the main process exit? The exit code answers most of it.

Quick diagnosis: three commands

Code
$ docker ps -a --filter name=myapp --format 'table {{.Names}}\t{{.Status}}'
$ docker inspect -f 'RestartCount={{.RestartCount}} ExitCode={{.State.ExitCode}} OOMKilled={{.State.OOMKilled}} Status={{.State.Status}} Policy={{.HostConfig.RestartPolicy.Name}}' myapp
$ docker logs --tail 50 myapp

Run a loop of my own and this is what the first two print (Docker Engine 26.1.5, alpine:3.22):

Code
NAMES     STATUS
r1        Restarting (2) 2 seconds ago
RestartCount=6 ExitCode=2 OOMKilled=false Status=restarting Policy=always
What you seeUsual meaningGo to
ExitCode 1 or 2, logs name a missing variable, file or moduleApp crashes on startupCause 1
ExitCode 0, logs show a normal "started" lineMain process finished or went to the backgroundCause 2
ExitCode 137 and OOMKilled=trueMemory limit hitCause 3
ExitCode 127, 126, or exec format errorWrong command, not executable, no shebang or wrong CPU architectureCause 4
Logs say Permission denied writing to a mounted pathNon-root user, root-owned volumeCause 5
Logs say connection refused or "db unreachable"Dependency not ready, app gives up instead of waitingCause 6
Animated checklist of Docker restart loop exit codes: exit 1 or 2 means the app crashed on startup such as a missing environment variable, exit 0 means the main process ended or was backgrounded, exit 137 with OOMKilled true means the memory limit was hit, 127 and 126 mean command not found or not executable, a permission denied log means a non-root user cannot write the mounted volume, and connection refused means the dependency was not ready
Exit code first, logs second. Together they point at one of six causes.

One practical note: all lab containers below ran with --network none, because the Docker bridge network on this lab box was not usable. None of the causes needs a network except Cause 6, where "unreachable" is exactly the point.

Fixes by cause

1. The app crashes at startup (exit 1 or 2)

Typical triggers are a missing environment variable, a config file that is not mounted, or a dependency not installed in the image. I used a start script that insists on DATABASE_URL:

Code
$ docker run -d --name r1 --restart always -v $PWD/app:/app:ro alpine:3.22 /app/start.sh
$ docker logs --tail 4 r1
/app/start.sh: line 2: DATABASE_URL: DATABASE_URL is not set
/app/start.sh: line 2: DATABASE_URL: DATABASE_URL is not set
/app/start.sh: line 2: DATABASE_URL: DATABASE_URL is not set
/app/start.sh: line 2: DATABASE_URL: DATABASE_URL is not set

Docker keeps the logs across restarts, so even a container that lives for two seconds leaves the reason behind. The exit code was 2 here because that is what busybox sh returns for a failed ${VAR:?} check; other shells and runtimes use 1. Fix the cause, recreate the container, and the loop stops:

Code
$ docker rm -f r1
$ docker run -d --name r1 --restart always -e DATABASE_URL=postgres://db:5432/hms -v $PWD/app:/app:ro alpine:3.22 /app/start.sh
$ docker ps --filter name=r1 --format 'table {{.Names}}\t{{.Status}}'
NAMES     STATUS
r1        Up 3 seconds
RestartCount=0 ExitCode=0 OOMKilled=false Status=running Policy=always

If the logs are empty, the process died before printing anything. Run the same image with the entrypoint replaced so you can look around: docker run --rm -it --entrypoint sh myimage (written from the Docker CLI reference, not run for this post). In Compose, remember that docker compose restart does not re-read a changed .env; recreate with docker compose up -d --force-recreate.

2. The command exits cleanly (exit 0)

This one confuses people because nothing "failed". A script that starts a worker in the background and then ends, service php-fpm start, or nginx without daemon off; all return exit code 0 immediately, and --restart always dutifully starts them again:

Code
$ docker run -d --name r2 --restart always alpine:3.22 sh -c 'sleep 600 & echo started worker in background'
$ docker inspect -f 'RestartCount={{.RestartCount}} ExitCode={{.State.ExitCode}} OOMKilled={{.State.OOMKilled}} Status={{.State.Status}} Policy={{.HostConfig.RestartPolicy.Name}}' r2
RestartCount=6 ExitCode=0 OOMKilled=false Status=restarting Policy=always
$ docker logs --tail 3 r2
started worker in background
started worker in background
started worker in background

The fix is to keep the real service in the foreground as PID 1, using exec in wrapper scripts so signals reach it:

Code
$ docker run -d --name r2 --restart always alpine:3.22 sh -c 'echo started worker; exec sleep 600'
RestartCount=0 ExitCode=0 OOMKilled=false Status=running Policy=always

If the container really is a one-off job (a migration, a report), it should not have a restart policy at all.

3. Out of memory (exit 137, OOMKilled=true)

I gave a container a 20 MB limit and let a process allocate more:

Code
$ docker run -d --name r3 --restart unless-stopped --memory 20m --memory-swap 20m alpine:3.22 sh -c 'echo allocating; tail /dev/zero'
$ docker inspect -f 'RestartCount={{.RestartCount}} ExitCode={{.State.ExitCode}} OOMKilled={{.State.OOMKilled}} Status={{.State.Status}} Policy={{.HostConfig.RestartPolicy.Name}}' r3
RestartCount=6 ExitCode=137 OOMKilled=true Status=restarting Policy=unless-stopped
$ docker logs --tail 3 r3
allocating
allocating
allocating

Note that the logs show nothing wrong: the kernel killed the process, so there was no error message to print. OOMKilled=true is the proof. Exit 137 on its own can also mean docker stop timed out or someone sent SIGKILL, so check that flag. Raise the limit only if the app genuinely needs more, otherwise fix the leak or the batch size. The full story, including host-level OOM kills, is in my Docker exit code 137 guide.

4. Wrong command, not executable, or wrong format (127, 126, exec format error)

Code
$ docker run -d --name r4 --restart on-failure:3 alpine:3.22 sh -c 'node server.js'
RestartCount=3 ExitCode=127 OOMKilled=false Status=exited Policy=on-failure
$ docker logs --tail 2 r4
sh: node: not found
sh: node: not found

127 means the program is not in the image. With on-failure:3 Docker gave up after three retries and left the container exited, which is the safer policy while you debug. A script without the execute bit gives 126, and one without a shebang gives exec format error:

Code
$ docker run --rm -v $PWD/app:/app:ro alpine:3.22 /app/noexec.sh; echo code=$?
docker: Error response from daemon: failed to create task for container: ... exec: "/app/noexec.sh": permission denied: unknown.
code=126
$ docker run --rm -v $PWD/app:/app:ro alpine:3.22 /app/noshebang.sh; echo code=$?
exec /app/noshebang.sh: exec format error
code=1

Fix with chmod +x and a first line such as #!/bin/sh. The same "exec format error" also appears when an image built for ARM (an Apple Silicon laptop) runs on an x86 server; that case I did not reproduce, so treat it as documented behaviour and check docker image inspect -f '{{.Architecture}}' myimage.

5. A non-root user cannot write to a mounted volume

The image runs as UID 1000 but the host directory is owned by root. With set -e in the entrypoint, the failed write ends the container:

Code
$ docker run -d --name r6 --restart on-failure:3 --user 1000:1000 -v /srv/data:/data alpine:3.22 sh -c 'set -e; echo ready > /data/ready.txt; exec sleep 600'
RestartCount=3 ExitCode=1 Status=exited
$ docker logs --tail 2 r6
sh: can't create /data/ready.txt: Permission denied
sh: can't create /data/ready.txt: Permission denied
$ ls -ld /srv/data | awk '{print $1, $3, $4}'
drwxr-xr-x root root

Give the directory to the container's user and the same command starts:

Code
$ sudo chown 1000:1000 /srv/data
RestartCount=0 ExitCode=0 Status=running
$ cat /srv/data/ready.txt
ready

The first time I ran this lab, I forgot set -e and the container simply stayed up after the failed write, with the error in the log. That is worth remembering: a shell wrapper that ignores errors can hide a broken container until the first request.

6. The dependency is not ready, so the app exits instead of waiting

Many apps connect to PostgreSQL or Redis once at boot and exit if it is not there yet. On a server reboot the app often starts before the database. A quick loop that gives up immediately restarts forever; a bounded wait is better:

Code
$ docker run -d --name r7 --restart always alpine:3.22 sh -c 'nc -z -w1 10.255.255.1 5432 || { echo "db unreachable, exiting"; exit 1; }; exec sleep 600'
RestartCount=6 ExitCode=1 OOMKilled=false Status=restarting Policy=always
$ docker logs --tail 2 r7
db unreachable, exiting
db unreachable, exiting
Code
i=0; until nc -z -w1 10.255.255.1 5432; do
  i=$((i+1)); [ $i -ge 3 ] && { echo gave-up-after-3; exit 1; }
  echo waiting-for-db $i; sleep 1
done
$ docker logs r7 | tail -4
waiting-for-db 1
waiting-for-db 2
gave-up-after-3
waiting-for-db 1

The tail shows the loop starting a second time after giving up, which is the right behaviour: wait a bit, exit non-zero, and let the restart policy and its growing delay do the retrying. In Compose, add a healthcheck to the database and depends_on: condition: service_healthy to the app (from the Compose documentation, not run here). For connection-refused details on the database side, see Redis connection refused.

Animated terminal session of a Docker restart loop triage: docker ps shows Restarting, docker inspect prints RestartCount 6 and ExitCode 2, docker logs shows DATABASE_URL is not set, then the container is recreated with the variable and docker ps shows Up
Triage of the missing-variable loop, run for real in the lab.

Stop the loop while you investigate

Code
$ docker update --restart=no myapp
$ docker stop myapp
$ docker inspect -f 'RestartCount={{.RestartCount}} ExitCode={{.State.ExitCode}} OOMKilled={{.State.OOMKilled}} Status={{.State.Status}} Policy={{.HostConfig.RestartPolicy.Name}}' myapp
RestartCount=9 ExitCode=137 OOMKilled=true Status=exited Policy=no

That output is from my OOM container. Stopping the churn first keeps the last exit code and logs stable, so you read one failure rather than a moving target. Remember to put the policy back (docker update --restart=unless-stopped myapp) once it is fixed. Also note that docker update only changes the policy; it does not change environment variables or mounts, so those need a recreate.

Verify the fix

Code
$ docker ps --filter name=myapp --format 'table {{.Names}}\t{{.Status}}'
NAMES     STATUS
myapp     Up 5 minutes
$ docker inspect -f '{{.RestartCount}}' myapp
0

Watch it for longer than the restart delay: Docker backs off between restarts, so a container that looks "Up 10 seconds" may be only one cycle into a loop. A steady uptime and a RestartCount that stays put are the real signs. If the daemon itself is what is failing, that is a different error; see cannot connect to the Docker daemon.

Common mistakes

  • Rebuilding the image before reading docker logs and the exit code.
  • Using restart: always on a one-off job, then wondering why it runs forever.
  • Starting a service with service x start or a trailing & as the container command.
  • Reading exit 137 as "Docker bug" without checking OOMKilled.
  • Fixing permissions inside the container with chmod 777 on a bind mount instead of matching the UID.
  • Leaving the restart policy on while debugging, so every look at the container is a different run.

Questions I get asked

Is restart: always the same as unless-stopped?

Almost. The difference is that a container you stopped by hand comes back after a daemon restart with always but not with unless-stopped.

Why is the restart delay getting longer?

Per the Docker documentation, the delay between restarts of a failing container starts at 100 ms and doubles each time (I did not time it). I saw the count climb to six within a few seconds in each lab case.

Can I see why it died if there are no logs?

Look at docker inspect for State.Error, ExitCode and OOMKilled, and on the host check dmesg for OOM messages (the last one I did not run here).

Does this apply to Docker Compose and Swarm?

Compose uses the same engine and the same exit codes. Swarm and Kubernetes have their own restart logic, which I did not test for this post.


About the author. Muhammad Wilayat Shah is a senior full-stack engineer and team lead based in Islamabad, with 13+ years shipping ERP, HMS, SaaS and property-portal products on Laravel, PHP, React, Next.js and PostgreSQL, and deploying them with Docker on Linux servers. He wrote this after a staging worker looped through a missing environment variable before a school ERP term start. More at wilayats.com/about.

Last reviewed: 24 Nov 2026

ShareLinkedInX
Back to blog

Keep reading

Four causes of Laravel Route not defined: wrong or missing route name, group name prefix, stale route cache, and Route [login] on API requests

11/14/2026

How to Fix Laravel Route Not Defined Error

A route-group refactor broke every admin page of a school-chain ERP with Route [fees.index] not defined. Here are the four causes, reproduced in a Laravel 13 lab: names, group prefixes, stale route cache and Route [login].

Newsletter

Occasional notes on Laravel, React, and shipping production systems — no spam.

Comments

Join the discussion. Replies load on demand, up to 5 levels.

0 threads

Loading editor…
Reviewed before publishing

No comments yet

Be the first to start the conversation.