docker: automatically restart a container

Say you need to restart a VM or restart Docker. How do you restart a container?

E.g. you have:

then restarting Docker (e.g. on the Mac you can click the Docker icon in the toolbar and select Docker > Restart) you get:

whilst Docker is restarting and:

after the restart (i.e. no containers).


You can use --restart always

docker container run --restart always -d <image id> sleep 1d

to restart after a docker reboot.




See also


More on Restart Policies

There are 4 restart policies: no, on-failure, unless-stopped, always.

no is the default. i.e. don’t restart if a container stops.

The others are:


We’ve seen this before. E.g. let’s say we have a script:

Note: exit 1 indicates an error (exit 0 would indicate success).

which we use as follows:


We can build and run with:

This will exit.

To restart with always restart policy use:

docker container run --restart always -d testing_restarts

Now, when it crashes, under docker ps you’ll see:



Here we can restart a container if it exits with a non-zero exit code. We can also specify a number of retries. E.g.

--restart on-failure:3

docker container run --restart on-failure:3 -d testing_restarts


  • the container will not restart if you do a docker stop <container id>
  • the container (and oddly even any containers that have stopped as a result of completing the on-failure number of retries – although only the first time the daemon was restarted) WILL restart if you restart the docker daemon



Behaves the same as always except if a container is stopped.

Note: if you manually stop a container its restart policy is ignored until the Docker daemon restarts.


Ensuring Containers Are Always Running with Docker’s Restart Policy


Live Restore

Lets you keep containers alive when the daemon becomes unavailable,.

However, doing this on my installation of Docker gave:

because I was running a swarm service.


I had to restore to Factory Defaults which means signing in to again.


Leave a Reply

Your email address will not be published. Required fields are marked *