Linux Labs

Containers: Docker and compose / Stage 2 of 11

Ports, variables and restart

Not running Starting usually ~20 s
Leave the lesson

Step 4 of 8 · theory · 6 min

Restart policy

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>.

Check yourself 1 question

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-stopped remembers a manual docker stop: c stays Exited after the service restart as well.

  • Docker does not bring back a container with no policy: a stays Exited after the service restart.

  • always starts the container when the docker service starts, even if it was stopped by hand: b will be Up.

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.
  • always brings a container back even after a manual docker stop, as soon as the docker service restarts; unless-stopped leaves it stopped.
  • docker update --restart changes the policy, while the port and the environment change only by re-creating the container.
Ubuntu 24.04
Loading…