Reputation: 3336
I often deploy docker containers for development on my laptop and then shutdown my computer forgetting to shut down the docker containers. To my surprise, many reboots later these containers are still running.
How can I change this behavior so that any docker container, regardless of whether the container has a restart policy attached to it, will not be restarted on the next boot?
I am running Linux and docker is running via systemd.
Upvotes: 0
Views: 902
Reputation: 3336
You can do this by creating a oneshot systemd service that depends on docker (setting the order via After=
) and then run a script on shutdown to stop and remove all containers.
Systemd service (ie. place in /etc/systemd/system/shutdown-docker-containers.service
):
[Unit]
Description="Service to prevent restarting docker containers on next bootup"
After=docker.service
[Service]
Type=oneshot
RemainAfterExit=true
ExecStop=/opt/docker-container-shutdown.sh
[Install]
WantedBy=docker.service
Script for removing docker containers (/opt/docker-container-shutdown.sh
):
#!/usr/bin/env bash
containers=$(docker ps -q)
[ -z "$containers" ] || {
docker stop $containers
docker rm $containers
}
Finally, make the script executable, reload systemd, and enable the service:
sudo chmod +x /opt/docker-container-shutdown.sh
sudo systemctl daemon-reload
sudo systemctl enable --now /etc/systemd/system/shutdown-docker-containers.service
Upvotes: 3