Why Containers Stop
A container can exit for several reasons:- Normal completion
The primary process finishes successfully (exit code 0), for example, a script completes its task. - Failure
The process crashes or throws an error, exiting with a non-zero code (e.g., bad input). - Manual intervention
Runningdocker container stopsends a SIGTERM, then a SIGKILL after a timeout:- If the process traps SIGTERM and exits cleanly, it may return code 0.
- If it’s killed with SIGKILL, it usually exits with a non-zero code.
Docker Restart Policies
Specify a restart policy with--restart when you run a container:
| Policy | Behavior | CLI Flag |
|---|---|---|
| no (default) | Never restart automatically. | --restart=no |
| on-failure | Restart only if exit code ≠ 0. Optionally limit retries: on-failure[:<max-retries>]. | --restart=on-failure:5 |
| always | Always restart regardless of exit status. If you manually stop the container, it will restart on daemon reboot. | --restart=always |
| unless-stopped | Like always, but honors manual stops across daemon restarts. | --restart=unless-stopped |
Use
on-failure[:<max-retries>] to prevent infinite restart loops. Docker immediately retries with no backoff delay.Quick Reference
- no: No auto-restart.
- on-failure: Auto-restart only on errors (non-zero exit).
- always: Auto-restart on any exit.
- unless-stopped: Auto-restart on any exit, but not after a manual stop.
Examples
1. Default (no)
2. On Failure
3. Always
- After
sleep 5finishes (exit 0), Docker restarts immediately. docker stop test-alwaysprevents restart only until the next Docker daemon reboot.
4. Unless-Stopped
- Behaves like
alwayson crashes or normal exit. - Honors manual
docker stopeven if the daemon restarts later.
Live Restore of Containers
By default, stopping the Docker daemon halts all containers. With live restore, containers remain running when the daemon is down.- Edit or create
/etc/docker/daemon.json: - Restart the Docker service:
Verifying Live Restore
Without live restore:Live restore requires compatible Docker versions and proper permissions. Check the Docker daemon.json reference before enabling.