When managing Docker containers, it’s crucial to ensure they automatically restart after a failure or system reboot. This can prevent downtime and ensure your applications remain available. In this post, set the restart policy for all Docker containers to “always.”
Enable Docker Service at Startup:
First, make sure that the Docker service itself is enabled to start on system boot. This can be done using the systemctl
command:
systemctl enable docker
Set Restart Policy for All Containers:
To ensure all running Docker containers are set to always restart, you can use the following command. This command lists all running containers, then iteratively sets their restart policy to “always”:
docker ps --format "" | xargs -I % sh -c 'echo %; docker update % --restart=always'
This command does the following:
docker ps --format ""
: Lists all running Docker containers by their names.
xargs -I % sh -c 'echo %; docker update % --restart=always'
: Takes each container name and applies the docker update
command to set the restart policy.
Confirm Restart Policy:
After setting the restart policy, you can confirm that it has been applied correctly by inspecting each container’s restart policy configuration:
docker ps --format "" | xargs -I % sh -c 'echo %; docker inspect % -f ""'
This command inspects each container and prints out its current restart policy to ensure it is set to “always”.