Search code examples
linuxdockersystemddocker-machine

How to run the docker commands before exiting docker-machine with systemd?


I run my containers on system boot with this systemd config:

[Unit]
After=docker.service
Requires=docker.service

[Service]
User=sterzhakov
Group=sterzhakov
ExecStart=/home/sterzhakov/conatiners-start.sh
ExecStop=/home/sterzhakov/containers-stop.sh
RemainAfterExit=true

[Install]
WantedBy=multi-user.target

and everything starts great

but on reboot I need to run another script to clean up volumes, containers inside my docker-machine

But this does not happen, here is the log of this script:

2021-02-07 02:35:09 | start VTB stop
Error checking TLS connection: Host is not running
Removing network docker_default
Network docker_default not found.
Removing network docker_default
Network docker_default not found

How to properly run the script inside the docker-machine before reboot | shutdown?


Solution

  • This is difficult because you cannot guarantee a clean shutdown. Machines freeze and crash sometimes. You're better off cleaning up at startup.

    You can create another systemd-service to clean up and place a dependency on it from the service that starts your containers.

    Or, it may be better to simply put a 'restart always' policy on your containers and docker will just restart them for you automatically when the system reboots.