>_ IzzyLab

Hands-on task

This task is step 7 of the course “Docker: everyday work”

Restart on failure: --restart

medium~8 min

There are two containers on the server, and both stay down after a failure:

  • worker sometimes crashes with an error. Docker should bring it back after a crash with an error — but no more than 5 times in a row; if worker exits normally (code 0), it shouldn't be restarted.
  • web should come back always — after a failure and after Docker restarts — except when it was stopped by hand with docker stop.

Give both of them suitable restart policies. Don't change the containers' images or commands.

What you'll practise:
  • docker run --restart
  • docker update
  • restart policy

Topic breakdown

When a container's main process exits, the container stays stopped — it won't come back up by itself. To have Docker do that, you set a restart policy with the --restart flag:

| Policy | When Docker starts the container again | |---|---| | no | never (the default) | | on-failure[:N] | only after exiting with a non-zero code; N is the maximum number of attempts in a row | | always | after any exit; one stopped by hand comes back up the next time Docker starts | | unless-stopped | like always, but a container you stopped with docker stop stays stopped after Docker restarts |

docker run -d --restart always --name cron busybox:1.36 crond -f

For an existing container docker update --restart … changes the policy — without recreating it. The current one is shown in docker inspect, in the HostConfig.RestartPolicy section, and the restart counter is in the RestartCount field.

What's checked

  1. worker restarts only after an error, no more than 5 attempts
  2. web restarts always, except after a manual stop, and web is running

What it looks like