Ditch Manual Starts: Automate Docker-Compose with Systemd
Intro
I finally got tired of having to SSH into one of my service virtual machines to start the Docker-Compose file after every reboot. This frustration led me down a rabbit hole of researching the best methods to automate this. Along the way, I discovered a lot controversy over the best method to launch and manage services at system initialization.. A lot of developers seem to have issue with `systemd` over other methods, and even if you should use a task scheduler like `cron` or not. While I don't have an answer to settle that debate for you, I can share what ended up working for me.
Background
I ventured down this path because I've been developing an open-source artifact gathering tool and I needed to automate more of my services to help testing. I've found a ton of uses for redcloud, modified Portainer instance for red teaming. It allows easily spinning up redteam tools in a container. I found this useful because I have been frequently restarting hosts in my homelab while testing my artifact tool.
Creating the Systemd Service File
To automate the startup of my Docker-Compose services, I created a systemd service file. Here’s how I did it:
Create the service file:
sudo nano /etc/systemd/system/redcloud.service
Contents of the service file:
[Unit] Description=Redcloud Docker Compose Service Requires=docker.service After=docker.service BindsTo=docker.service ReloadPropagatedFrom=docker.service [Service] Type=oneshot RemainAfterExit=yes ExecStart=/bin/bash -c "docker-compose -f /path/to/compose/redcloud/redteam-compose.yml up -d --build" ExecStop=/bin/bash -c "docker-compose -f /path/to/compose/redcloud/redteam-compose.yml down" [Install] WantedBy=multi-user.target RequiredBy=network.target Also=docker.service
I won't claim this is the best way to do it, and I welcome any recommendations. However, this configuration worked for me quickly after a couple of other attempts.
Enabling and Testing the Service
Here we enable the service and then just quickly test it worked.
Reload the systemd daemon:
sudo systemctl daemon-reload
Start the service:
sudo systemctl start redcloud
Check the service status:
sudo systemctl status redcloud
Reboot host:
sudo reboot
Confirm the service ran and container is running:
sudo systemctl status redcloud sudo docker ps
Conclusion
That's it! Setting up the service was pretty straightforward. While there may be different or better ways to automate Docker-Compose startups, this method worked reliably for my needs. If you have any suggestions or improvements, I'd love to hear them!