Sub topic 8
Restart Policies and Crash Loops
This chapter assumes you can run containers with docker run, read docker logs output, and interpret exit codes as covered in the earlier chapters. It also assumes you know what ENTRYPOINT and CMD do. Here you will learn how restart policies change what you see when a container fails, how to recognize a crash loop, and how to find the cause of one.
What a restart policy does
A restart policy tells the Docker daemon what to do when a container's main process exits. Without a policy, the container moves to exited and stays there. With a policy, the daemon starts it again, and the container's history becomes harder to read.
You set a policy with --restart on docker run, or with restart: in a Compose file.
| Policy | Behavior |
|---|---|
| `no` | Never restart. This is the default. |
| `on-failure[:max]` | Restart only if the exit code is non-zero. Optionally give up after `max` attempts. |
| `always` | Restart whatever the exit code. If you stop the container by hand, it stays stopped until the daemon restarts. |
| `unless-stopped` | Like `always`, but a container you stopped by hand stays stopped even after the daemon restarts. |
Two details cause confusion:
on-failuredoes not restart a container that exits with code 0. A short-lived job that finishes cleanly will stay inexited.- A restart policy applies only after the container has been up for a short time. Docker waits at least 10 seconds before it treats a start as successful, so a container that dies faster than that is counted as a failed start and the policy's back-off keeps applying.
What a crash loop looks like
A crash loop is a container that starts, fails, is restarted by the policy, and fails again. The daemon increases the delay between restarts, starting at 100 ms and doubling each time, up to a limit of one minute. The delay resets once the container has stayed up for 10 seconds.
The state of a looping container alternates between running and restarting. In docker ps you see a status like this:
Restarting (1) 12 seconds agoThe number in parentheses is the exit code of the last run. The time is how long ago that run ended. If you see Restarting in docker ps, treat the container as failing, even though it sometimes appears as Up.
Seeing the loop
Start with the commands from the earlier chapters, and add the restart count. docker inspect exposes it, along with the exit code and the OOM flag.
docker inspect --format 'exit={{.State.ExitCode}} oom={{.State.OOMKilled}} restarts={{.RestartCount}} error={{.State.Error}}' webRead the output this way:
- A
restartsvalue that keeps growing between two runs of the command confirms a loop. exitis the exit code of the most recent run only. Earlier runs may have ended differently, so check the logs.oom=truepoints to memory limits. See the chapter on out-of-memory kills.- A non-empty
errormeans the daemon could not start the process at all, for example because the executable was not found.
To list every container that is currently restarting, filter by status:
docker ps -a --filter status=restarting --format 'table {{.Names}}\t{{.Status}}\t{{.Image}}'Why the logs seem to vanish
A common mistake is to run docker logs web during a loop and see only a few lines or nothing useful. The logs of earlier runs are kept, because the container is the same one each time. Log output from all runs is joined together, so the last run's output is mixed with the earlier ones.
Use timestamps and a narrow window to separate the runs:
docker logs --timestamps --tail 100 web
docker logs --follow --since 5m webLook for the same first error line repeating at regular intervals. The gap between repeats will grow as the back-off increases, which is another sign of a loop. The first error after each start is usually the cause. Later lines are often consequences.
If the output is empty, the process may be dying before it writes anything. That points to a startup problem such as a wrong command, a missing file, or a permission error. Check error in docker inspect and continue to the technique below.
Catching the failure while it is happening
Because the container restarts, docker exec often fails with an error saying the container is restarting, or the shell closes within seconds. There are three ways around this.
Stop the loop first
Change the policy so the container stays down after its next failure, and then examine it as a normal exited container:
docker update --restart=no web
docker stop web
docker inspect --format '{{.State.Status}} exit={{.State.ExitCode}}' webdocker update changes the policy on an existing container without recreating it. After this, the container stays in exited, and the state is stable enough to read.
Reproduce it without the policy
Run a throwaway container from the same image, with the same environment and mounts, but no restart policy and a shell instead of the normal entrypoint:
docker run --rm -it --entrypoint sh myimage:latestFrom the shell, run the original command by hand and watch the error appear in your terminal. This is the same technique used for failed starts in an earlier chapter. It works well here because you control when the process runs and when it ends.
Watch the daemon
docker events shows each start and death as it happens, including the exit code:
docker events --filter container=web --filter event=dieEach die event carries an exitCode attribute. A steady series of events with the same code, and the intervals between them, tells you whether the cause is deterministic (same code every time) or intermittent (codes differ, for example 1 and 137).
Common causes of crash loops
| Symptom | Likely cause | Next step |
|---|---|---|
| Exit 1 within a second, error in logs | Application error, such as a bad config or a missing environment variable | Read the first error line, then run `docker exec web env` if it stays up long enough, or compare with `docker inspect` |
| Exit 127 or 126 | Command not found or not executable | Check ENTRYPOINT and CMD, file permissions, and line endings in scripts |
| Exit 137 with `oom=true` | Memory limit reached | Raise the limit or reduce memory use |
| Exit 137 with `oom=false` | Something sent SIGKILL, such as `docker kill`, or a health check orchestrator | Check `docker events` for who stopped it |
| Exit 0, restarted by `always` | A process that finishes normally is under a policy meant for services | Remove the policy, or run a long-lived process |
| Exit code varies | Dependency not ready, such as a database that is still starting | Check the order of startup and add retries or a health check |
The exit 0 case deserves attention. With restart: always, a container running a one-shot script restarts forever, and looks like a crash loop even though nothing is failing. Match the policy to the workload: on-failure or no for jobs, unless-stopped or always for services.
Dependencies that are not ready
Many loops are timing problems. An application starts before its database accepts connections, exits with an error, and is restarted. After a few cycles the database is ready and the loop ends by itself. This can look like a flaky container rather than a real failure.
The fix belongs in the application or in the orchestration, not in a longer restart delay. Make the application retry its connection, or use a health check on the dependency so that dependents wait for it. The next chapter covers health checks.
Limiting the damage
A tight loop wastes CPU, fills the log, and can hide a real problem behind noise. Two measures help:
- Use
on-failure:5instead ofalwaysin places where an endless loop is worse than a stopped container. After five failed attempts the container stays inexited, and its exit code stays available. - Set a log rotation limit so a loop cannot fill the disk:
docker run -d --name web \
--restart on-failure:5 \
--log-opt max-size=10m --log-opt max-file=3 \
myimage:latestNote that RestartCount is reset when you recreate the container. If you replace it on every deploy, the count shows only the current container's history.
A procedure for a looping container
- Confirm the loop:
docker ps -ashowsRestarting, orRestartCountgrows. - Record
ExitCode,OOMKilled, andErrorfromdocker inspect. - Read the first error line in
docker logs --timestamps. - Decide whether the cause is the same on every run (configuration, command, image) or varies (timing, resources, dependencies).
- Stop the loop with
docker update --restart=no webfollowed bydocker stop web, and reproduce the failure with an overridden entrypoint. - Fix the cause, then restore the policy you want.
Exercise
A container named report runs a script that prints a summary and ends with exit code 0. It was started with --restart always, and docker ps shows it as Restarting (0) 3 seconds ago. Is this a crash? What would you change, and which command would you use to stop the cycle while you decide?
Show answer
It is not a crash. The script succeeds, but always restarts the container whatever the exit code, so it runs again and again. The policy does not match the workload. Use docker update --restart=no report and then docker stop report to stop the cycle. For a job, run it with no or on-failure, which does not restart after exit code 0. If it should run on a schedule, use a scheduler such as cron or an orchestrator instead of a restart policy.
Exercise
You run docker inspect --format '{{.RestartCount}}' web twice, one minute apart, and get 14 and then 15. The last exit code is 1 and the logs show a database connection error each time. What does the slowing rate of restarts tell you, and where should the fix go?
Show answer
The count of 14 then 15 means one restart in a minute, which matches the back-off reaching its one-minute maximum. The loop has been running for a while. The repeated connection error suggests the application starts before its database is reachable, or the address is wrong. Check that the database is running and that the hostname and port in the configuration are correct. If it is only a timing issue, add connection retries in the application or make startup wait on a health check for the database. Increasing the restart delay does not fix the cause.