How to Disable Autostart for All Containers in Docker?

To disable autostart for all containers in Docker, you can use the [code]--restart[/code] flag when running or creating containers and set it to "no" or "on-failure". Note, however, that this only affects new containers, and you will need to manually update existing containers if you want to disable their autostart.

To disable autostart for new containers:

1. Stop and remove all existing containers:

docker stop $(docker ps -aq)  && docker rm $(docker ps -aq)

2. Set the default restart policy to "no" or "on-failure":

docker update --restart=no $(docker ps -aq)

or

docker update --restart=on-failure $(docker ps -aq)

The --restart flag with the value "no" disables autostart for new containers, and "on-failure" enables autostart only when the container fails.

3. Verify that the restart policy has been updated:

docker inspect --format '{{.Name}} - RestartPolicy={{.HostConfig.RestartPolicy.Name}}' $(docker ps -aq)

This command displays the container names and their restart policies. Make sure the restart policy for all containers is set to "no" or "on-failure".

From now on, when you create new containers, they will not start automatically unless you explicitly start them. Existing containers will still have their previous restart policies, so you may need to update them manually.

To disable autostart for existing containers in Docker, you can do the following:

#!/bin/bash
 
# Get a list of running containers
container_ids=$(docker ps -q)
 
# Disable autostart on each container
for container_id in $container_ids; do
docker update --restart=no $container_id
done
 
echo "Autostart disabled for all containers."

Save the script to a file, for example disable_autostart.sh. Make sure to give it execute permissions:

chmod +x disable_autostart.sh

Then you can run the script:

./disable_autostart.sh

The script retrieves a list of running containers and loops through each container ID to disable autostart using the docker update command with the --restart=no flag. After disabling autostart for all containers, it outputs a message confirming that autostart has been disabled.

Please note that this script only affects containers that are currently running. If you have stopped containers for which you want to disable autostart, you will need to modify the script to include those containers as well.


Need support with your Docker or container infrastructure? Contact me for a no-obligation consultation.