CodeBlanks Logo Icon CodeBlanks

Restart policy

Learn container restart policy with --restart.

Restart policy

--restart decides what Docker does when the container stops or the server reboots:

  • no (default): don't restart
  • on-failure[:5]: only on a non-zero exit code, at most 5 times
  • always: always; even if stopped by hand it starts when the daemon starts
  • unless-stopped: like always, but doesn't start if it was stopped by hand
docker run -d --name web --restart unless-stopped nginx

Updating an existing container

The policy can also be changed after the container is created. The current policy and the restart count are seen with docker inspect:

docker update --restart on-failure:3 worker
docker inspect -f '{{.HostConfig.RestartPolicy.Name}} {{.RestartCount}}' worker
# on-failure 2

Practice Resilient services

Write two commands: run a container named web from nginx in the background so it restarts unless stopped by hand; then update the existing worker container's policy to restart at most 3 times on failure.

Starter code

terminal
# buraya yaz

Sample solution

terminal
docker run -d --name web --restart unless-stopped nginx
docker update --restart on-failure:3 worker

Expected output

2c3d4e5f6a7b
worker

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which policy keeps a container you stopped by hand from starting when the server reboots?

  • always
  • on-failure
  • no and always together
  • unless-stopped Correct answer

Explanation: always forgets the manual stop when the daemon restarts.

2 Restart only on failure, at most 5 times.

Question
docker run -d --restart ____ worker
Answer
docker run -d --restart on-failure:5 worker

Explanation: on-failure:N retries N times on a non-zero exit.

3 Match the policies.

Term Meaning
no Never restart
on-failure On an error exit
always Always
unless-stopped Unless stopped by hand

All lessons in Beginner