Backing Up Services with Systemd Timers and Custom Backup Services

First I create a script to rsync the container folder that is mapped to the host to another location on the same host. I am syncing to a local spot just to simulate a backup. Next, I create a systemd template file which allows me to avoid creating a backup .service file for each service I want to backup. Lastly, I put together the timer unit file that determines what service to run and at what time to run it.

Script for Backup Service

Very simply I am just having the backup service run an rsync on the directories mapped to the host for each container I want to backup. The below rsync command is put into a actual-backup.sh file and made executable with chmod. In the future, I plan on setting up a NAS and using something like restic for an actual backup.

#!/bin/bash
rsync -a /var/lib/containers/storage/volumes/systemd-actual-app/ /home/admin/backup/actual

Systemd Template File Named as [email protected]

The template file is named this way so that I can pass an argument that becomes usable with %i inside the template file. For example, once this file gets called like [email protected], each spot in the template file that references %i will get replaced with actual.

[Unit]
Description=Backup for %i-app
Requires=%i-app.service
	
[Service]
Type=simple
	
ExecStart=/usr/local/bin/%i-backup.sh
	
Restart=on-failure
RestartSec=5s
StandardOutput=journal
StandardError=journal

In order to run a custom script I set the service type to simple and provide the path to the script I want to run to the parameter ExecStart.

Systemd Timer

Now I can create the systemd timer that will run the above service whenever I schedule it to.

[Unit]
Description=Run backup for actual budget every night

[Timer]
OnCalendar=daily
Unit=[email protected]

[Install]
WantedBy=multi-user.target

This timer will now run the backup@actual service every night at 12:00am.

Also, although I specifically reference the [email protected], which backs up my actual-app.service, systemd timers can be templated out. As more and more services get added, I will consider templating the timer so it is reusable.