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
$ 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 myappRun a loop of my own and this is what the first two print (Docker Engine 26.1.5, alpine:3.22):
NAMES STATUS
r1 Restarting (2) 2 seconds ago
RestartCount=6 ExitCode=2 OOMKilled=false Status=restarting Policy=always| What you see | Usual meaning | Go to |
|---|---|---|
| ExitCode 1 or 2, logs name a missing variable, file or module | App crashes on startup | Cause 1 |
| ExitCode 0, logs show a normal "started" line | Main process finished or went to the background | Cause 2 |
ExitCode 137 and OOMKilled=true | Memory limit hit | Cause 3 |
ExitCode 127, 126, or exec format error | Wrong command, not executable, no shebang or wrong CPU architecture | Cause 4 |
Logs say Permission denied writing to a mounted path | Non-root user, root-owned volume | Cause 5 |
Logs say connection refused or "db unreachable" | Dependency not ready, app gives up instead of waiting | Cause 6 |
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:
$ 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 setDocker 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:
$ 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=alwaysIf 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:
$ 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 backgroundThe fix is to keep the real service in the foreground as PID 1, using exec in wrapper scripts so signals reach it:
$ 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=alwaysIf 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:
$ 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
allocatingNote 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)
$ 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 found127 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:
$ 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=1Fix 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:
$ 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 rootGive the directory to the container's user and the same command starts:
$ sudo chown 1000:1000 /srv/data
RestartCount=0 ExitCode=0 Status=running
$ cat /srv/data/ready.txt
readyThe 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:
$ 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, exitingi=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 1The 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.
Stop the loop while you investigate
$ 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=noThat 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
$ docker ps --filter name=myapp --format 'table {{.Names}}\t{{.Status}}'
NAMES STATUS
myapp Up 5 minutes
$ docker inspect -f '{{.RestartCount}}' myapp
0Watch 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 logsand the exit code. - Using
restart: alwayson a one-off job, then wondering why it runs forever. - Starting a service with
service x startor a trailing&as the container command. - Reading exit 137 as "Docker bug" without checking
OOMKilled. - Fixing permissions inside the container with
chmod 777on 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



![Four causes of Laravel Route not defined: wrong or missing route name, group name prefix, stale route cache, and Route [login] on API requests](/uploads/1795601210518-930de4b3-cfc3-457b-a172-1a58d403ffea.jpg)
Comments
Join the discussion. Replies load on demand, up to 5 levels.
0 threads
No comments yet
Be the first to start the conversation.