A container that stopped by itself or together with the docker service can come back without you.
When the main process ends, Docker leaves the container stopped. Restarting the docker service or the whole server stops all containers, and afterwards they stay stopped as well. This behaviour is changed by the restart policy, the --restart option of docker run:
--restart |
Process crashed (code ≠ 0) | Process ended with code 0 | Stopped with docker stop, then the docker service restarted |
|---|---|---|---|
no — the default |
stays stopped | stays stopped | stays stopped |
on-failure |
comes back | stays stopped | comes back if the process stopped with a code ≠ 0 |
always |
comes back | comes back | comes back |
unless-stopped |
comes back | comes back | stays stopped |
No policy brings back a container stopped by hand until the docker service restarts. Running containers with always and unless-stopped also come back after a restart of the docker service or the server. The RestartCount field in docker inspect keeps how many times Docker has brought a container back.
Unlike the port and the environment, the policy can be changed on an existing container: sudo docker update --restart <policy> <name>.
Three containers are running: a with no policy, b with --restart always, c with --restart unless-stopped. b and c were stopped with docker stop, then sudo systemctl restart docker was run. Which containers will be Up?
-
unless-stoppedremembers a manualdocker stop:cstaysExitedafter the service restart as well. -
Docker does not bring back a container with no policy:
astaysExitedafter the service restart. -
alwaysstarts the container when the docker service starts, even if it was stopped by hand:bwill beUp.
The service restart stops a, and with no policy it stays stopped. always brings b back even though it was stopped by hand, while unless-stopped remembers the manual docker stop and leaves c in Exited.
Key points
- With no policy a container comes back neither after a process crash nor after a docker service restart.
-
alwaysbrings a container back even after a manualdocker stop, as soon as the docker service restarts;unless-stoppedleaves it stopped. -
docker update --restartchanges the policy, while the port and the environment change only by re-creating the container.