Docker – which images dockerd starts automatically


Once I have restarted the docker service on Ubuntu box with service docker restart it started some of the containers I didn't expect it to start.

Why is that? Which config file/storage/whatever holdw information about which images should be started?

I have a lot of images (~50) when listing them with docker images. But only 8 of them start when I start the dockerd. Why? How do I chage this?


Best Answer

For individual containers, there is a restart policy you can apply. That's set with docker run --restart=... when starting the container, or a restart: ... line in the compose yml file. You can change the restart policy in an existing container with:

$ docker update --restart=... ${container_name_or_id}

To list all containers and their restart policies, you can run this from bash:

$ docker container ls -q | \
  xargs docker container inspect --format \
          '{{ .Name }}: {{.HostConfig.RestartPolicy.Name}}'

The restart policies you can use are:

no Do not automatically restart the container when it exits. This is the default.

on-failure[:max-retries] Restart only if the container exits with a non-zero exit status. Optionally, limit the number of restart retries the Docker daemon attempts.

always Always restart the container regardless of the exit status. When you specify always, the Docker daemon will try to restart the container indefinitely. The container will also always start on daemon startup, regardless of the current state of the container.

unless-stopped Always restart the container regardless of the exit status, but do not start it on daemon startup if the container has been put to a stopped state before.

A restart policy of always would result in an unexpected container restart after the docker daemon restarts like you are seeing, even if you had intentionally stopped the container. For this reason, I typically create standalone containers with a unless-stopped restart policy.

If you are using docker swarm mode, then services will automatically start up a new container any time the target state doesn't match the current state. For a single node swarm cluster often seen with laptops, this means the container will restart when you restart docker, but also if you just stop or delete the running container.

The permanently stop and remove a service:

$ docker service ls # to show the running services
$ docker service rm ${service_id_or_name}

If a service is configured with replicated mode, and you simply want to stop it temporarily without deleting the service, you can update the target replicas to 0:

$ docker service update --replicas=0 ${service_id_or_name}

And services may be deployed as part of a stack. To remove the entire stack:

$ docker stack ls # to show the defined stacks
$ docker stack rm ${stack_id_or_name}