Linux and servers · Intermediate · 22 min
Automate restic backups with a systemd timer and test the restores
By Padding · Updated 18 Nov 2026
Ubuntu 26.04.1 LTS · restic 0.20.0 · systemd 259 · PostgreSQL 18
You will have a nightly restic backup of /etc, /srv and PostgreSQL that runs from a systemd timer, pings a heartbeat, alerts on failure and proves once a month that it can be restored.
On this page
A backup job can fail in three quiet ways. It runs and errors, and nobody reads the log. It stops running at all, because the timer was disabled during an upgrade, so there is no error to read. Or it runs every night and writes snapshots that cannot be restored. This tutorial guards against all three: OnFailure= reports a run that errors, a heartbeat ping lets an outside service notice when runs stop, and a monthly restore test reads the data back and compares checksums.
You build one job that backs up /etc, /srv and every PostgreSQL database on the server. It dumps the databases first, because copying PostgreSQL's data files while the server is running does not give you a backup you can trust. The job runs at night from a systemd timer, at low CPU and disk priority, and prunes old snapshots as it goes.
This builds on /tutorials/back-up-a-server-with-restic, which covers installing restic 0.20 from the official release, repositories, excludes and restores. For the timer basics (OnCalendar=, Persistent=, the journal) see /tutorials/replace-cron-jobs-with-systemd-timers.
Step 1 · Keep the repository settings in one private file
Every script in this tutorial reads the same settings file, so the repository address and password live in one place. Start by checking the restic version:
restic versionThe output is something like restic 0.20.0 compiled with go1.26.10 on linux/amd64. If you see 0.18, that is Ubuntu's package; install the official release as the restic tutorial shows.
Create a private folder and a private password file. The file is created empty with mode 600 first, so the password is never readable by other users, even for a moment:
sudo install -d -m 700 /etc/nightly-backup
sudo install -m 600 /dev/null /etc/nightly-backup/restic-password
sudo sh -c 'head -c 32 /dev/urandom | base64 > /etc/nightly-backup/restic-password'Copy that password into your password manager now. Without it, nobody can read the backups, including you, and a backup that only exists on the server it protects is gone with the server:
sudo cat /etc/nightly-backup/restic-passwordNow the settings file, created private the same way. The scripts load it as shell code, so keep to NAME=value lines and put values that contain spaces or & in single quotes:
sudo install -m 600 /dev/null /etc/nightly-backup/env
sudo tee /etc/nightly-backup/env > /dev/null <<'EOF'
# Settings for the nightly-backup scripts. Shell syntax: quote values with spaces.
RESTIC_REPOSITORY=/var/backups/restic-repo
RESTIC_PASSWORD_FILE=/etc/nightly-backup/restic-password
RESTIC_CACHE_DIR=/var/cache/restic
BACKUP_PATHS='/etc /srv /var/backups/postgres'
# Your heartbeat service's ping URL, in single quotes. Empty means no ping.
HEARTBEAT_URL=''
EOFRESTIC_REPOSITORY here is a local folder so you can follow along. Replace it with your off-site repository, an sftp: or s3: address as in the restic tutorial, before you rely on this job. If you already have a repository from that tutorial, point RESTIC_REPOSITORY and RESTIC_PASSWORD_FILE at it and skip the init command below.
Add an excludes file for things not worth keeping:
sudo install -m 600 /dev/null /etc/nightly-backup/excludes
sudo tee /etc/nightly-backup/excludes > /dev/null <<'EOF'
# One pattern per line, as in restic backup --exclude.
/srv/**/tmp
*.swp
EOFThen a small wrapper, so you can run any restic command by hand with these settings:
sudo tee /usr/local/bin/backup-restic > /dev/null <<'EOF'
#!/bin/sh
# Run restic with the settings in /etc/nightly-backup/env.
set -eu
set -a
. /etc/nightly-backup/env
set +a
exec /usr/local/bin/restic "$@"
EOF
sudo chmod 755 /usr/local/bin/backup-resticCreate the repository:
sudo backup-restic initCheck it worked
init prints something like created restic repository 5f3c1a9e2b at /var/backups/restic-repo. Then:
sudo ls -l /etc/nightly-backup
sudo backup-restic snapshotsAll three files show -rw------- and owner root, and snapshots reports no snapshots yet. A wrong password error (exit code 12) means RESTIC_PASSWORD_FILE points at a different password from the one the repository was created with.
Step 2 · Write the backup script
The script does four things in order, and stops at the first failure: dump PostgreSQL, back up the paths, prune old snapshots, and ping the heartbeat. Because the ping comes last, it only goes out when everything before it worked.
If your server has no database yet, create a small one to practise with:
sudo -u postgres createdb shop
sudo -u postgres psql -d shop -c "CREATE TABLE orders (id serial PRIMARY KEY, total_cents integer NOT NULL); INSERT INTO orders (total_cents) SELECT g * 100 FROM generate_series(1, 200) AS g;"Write the script:
sudo tee /usr/local/bin/nightly-backup > /dev/null <<'EOF'
#!/bin/bash
# Nightly backup: dump PostgreSQL, back up with restic, prune, ping the heartbeat.
# Run by nightly-backup.service. Settings: /etc/nightly-backup/env
set -euo pipefail
set -a
. /etc/nightly-backup/env
set +a
cd /
dump_dir=/var/backups/postgres
install -d -m 700 -o postgres -g postgres "$dump_dir"
rm -f "$dump_dir"/*.tmp
echo "Dumping PostgreSQL roles and databases into $dump_dir"
runuser -u postgres -- pg_dumpall --globals-only --file="$dump_dir/globals.sql"
dbs=$(runuser -u postgres -- psql -Atc "SELECT datname FROM pg_database WHERE datallowconn AND NOT datistemplate")
for db in $dbs; do
runuser -u postgres -- pg_dump --format=custom --file="$dump_dir/$db.dump.tmp" "$db"
mv "$dump_dir/$db.dump.tmp" "$dump_dir/$db.dump"
echo "Dumped $db"
done
(cd "$dump_dir" && sha256sum globals.sql ./*.dump > SHA256SUMS)
read -r -a paths <<< "$BACKUP_PATHS"
echo "Backing up ${paths[*]}"
restic backup --retry-lock 30m --tag nightly --exclude-caches \
--exclude-file /etc/nightly-backup/excludes "${paths[@]}"
echo "Removing old nightly snapshots"
restic forget --retry-lock 30m --tag nightly \
--keep-daily 7 --keep-weekly 5 --keep-monthly 12 --prune
if [ -n "${HEARTBEAT_URL:-}" ]; then
curl -fsS --max-time 10 --retry 3 -o /dev/null "$HEARTBEAT_URL" \
|| echo "Warning: heartbeat ping failed" >&2
fi
echo "Backup finished"
EOF
sudo chmod 755 /usr/local/bin/nightly-backupA few choices worth knowing:
- Each database is dumped to a
.tmpfile and renamed only whenpg_dumpsucceeds, so a half-written dump never replaces a good one.globals.sqlholds the roles and passwords thatpg_dumpleaves out. If you drop a database, delete its old.dumpfile by hand. SHA256SUMSrecords the checksum of every dump at backup time. The restore test compares against it later.- restic exits with code 3 when it could not read some files. A snapshot is still written, but it is incomplete, so
set -etreats it as a failure and you get an alert rather than a quiet gap. --retry-lock 30mmakes restic wait for another restic run on the same repository, such as the restore test, instead of failing at once.- The
forgetline keeps 7 daily, 5 weekly and 12 monthly snapshots. Adjust it to your own policy; the restic tutorial explains each flag.
Run it once by hand:
sudo /usr/local/bin/nightly-backupCheck it worked
The script prints Dumped postgres and Dumped shop, restic's summary with the number of files and bytes added, and ends with Backup finished. Check what landed in the repository:
sudo backup-restic snapshots --tag nightly
sudo backup-restic ls latest /var/backups/postgressnapshots lists one snapshot tagged nightly with the paths /etc, /srv and /var/backups/postgres. ls lists globals.sql, postgres.dump, shop.dump and SHA256SUMS under /var/backups/postgres.
Step 3 · Send a heartbeat so a missing run is noticed
An alert on failure only fires if the job runs. If the timer is disabled, the server is off for a week, or the disk with the repository is unmounted so the unit never starts, nothing fails and nothing alerts. A heartbeat, sometimes called a dead man's switch, turns that silence into an alarm: an outside service expects a ping every day and alerts you when one does not arrive.
Healthchecks.io works this way and is open source, so you can use the hosted service or run it yourself; many monitoring tools have the same feature under names such as push or cron monitors. Create a check with a period of 1 day and a grace time of a few hours, so the random start delay and a slow night do not trigger it. Copy the check's unique ping URL.
The URL is a secret: anyone who has it can ping your check and hide a failure. Put it in the private settings file. Open the file and fill in the HEARTBEAT_URL='' line, keeping the single quotes:
sudo nano /etc/nightly-backup/envRun the backup again so it sends its first ping:
sudo /usr/local/bin/nightly-backupThe script only pings on success. Healthchecks.io also accepts a ping to the same URL with /fail on the end to report a failure straight away; the alert unit in the next step covers that, so this script does not use it.
Check it worked
The script ends with Backup finished and no Warning: heartbeat ping failed line. In your heartbeat service, the check shows a ping received a few seconds ago and its status changes to up. If you see the warning, test the URL on its own with curl -fsS followed by the address; a firewall that blocks outgoing HTTPS is the usual cause.
Step 4 · Create the alert unit for failed runs
OnFailure= starts another unit when a service fails. Use one template unit for every job on the server, with the failed unit's name after the @. If you kept notify-failure@.service and its script from the timers tutorial, you already have this; the commands below write the same thing again.
sudo tee /usr/local/bin/notify-failure > /dev/null <<'EOF'
#!/bin/sh
# Report a failed systemd service. Usage: notify-failure <unit name without .service>
set -u
unit="$1.service"
msg="$unit failed on $(uname -n) at $(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo "$msg"
journalctl -u "$unit" -n 20 --no-pager 2>/dev/null || true
if [ -n "${ALERT_WEBHOOK_URL:-}" ]; then
curl -fsS --max-time 10 -H 'Content-Type: application/json' \
-d "{\"text\": \"$msg\"}" "$ALERT_WEBHOOK_URL"
fi
EOF
sudo chmod 755 /usr/local/bin/notify-failure
sudo tee /etc/systemd/system/notify-failure@.service > /dev/null <<'EOF'
[Unit]
Description=Report a failed run of %i
[Service]
Type=oneshot
EnvironmentFile=-/etc/notify-failure.env
ExecStart=/usr/local/bin/notify-failure %i
EOFThe alert lands in the journal. To send it to a chat channel as well, create /etc/notify-failure.env private first and add one line, ALERT_WEBHOOK_URL= followed by your incoming webhook address:
sudo install -m 600 /dev/null /etc/notify-failure.env
sudo nano /etc/notify-failure.envCheck it worked
systemd-analyze verify /etc/systemd/system/notify-failure@.service
/usr/local/bin/notify-failure demo-jobsystemd-analyze verify prints nothing, and the script prints a line such as demo-job.service failed on backup1 at 2026-11-26T09:14:02Z. It runs fine as your own user because it only reads the journal.
Step 5 · Run the backup from a service and a timer
The service runs the script once, at low priority, and starts the alert unit if it fails:
sudo tee /etc/systemd/system/nightly-backup.service > /dev/null <<'EOF'
[Unit]
Description=Nightly restic backup of /etc, /srv and PostgreSQL
Wants=network-online.target
After=network-online.target postgresql.service
OnFailure=notify-failure@%N.service
[Service]
Type=oneshot
ExecStart=/usr/local/bin/nightly-backup
Nice=10
IOSchedulingClass=best-effort
IOSchedulingPriority=7
CacheDirectory=restic
TimeoutStartSec=6h
EOFWhat the less common lines do:
Nice=10gives the backup less CPU time than your app when both want it. Compressing and encrypting a large tree is CPU work.IOSchedulingClass=best-effortwithIOSchedulingPriority=7puts the job's disk reads at the back of the normal queue; the kernel default is priority 4. Theidleclass goes further and only reads when nothing else does, but on a disk that is never quiet the backup may then never finish. How much either setting helps depends on the disk's I/O scheduler.CacheDirectory=resticcreates/var/cache/restic, which matchesRESTIC_CACHE_DIR. restic keeps a local copy of the repository index there, so it does not download it every night.TimeoutStartSec=6hmatters because aType=oneshotservice has no start timeout by default. A backup stuck on a dead network link would otherwise hang for ever without failing, and you would never get an alert.After=network-online.targetwaits for the network, which an off-site repository needs.After=postgresql.serviceonly orders the start when both happen at boot.
The timer:
sudo tee /etc/systemd/system/nightly-backup.timer > /dev/null <<'EOF'
[Unit]
Description=Run nightly-backup every night
[Timer]
OnCalendar=*-*-* 01:30:00
RandomizedDelaySec=30min
Persistent=true
[Install]
WantedBy=timers.target
EOFPersistent=true runs a missed backup soon after the next boot, which matters on servers that lose power overnight. If the repository is off-site and the server's data is metered, as on many prepaid business links, only new and changed data is uploaded after the first run, so nightly traffic is usually small. Run the first, full backup when data is cheapest, and add --limit-upload 1024 (KiB/s) to the restic backup line if the upload would crowd out daytime users.
Check it worked
systemd-analyze verify /etc/systemd/system/nightly-backup.service /etc/systemd/system/nightly-backup.timer
systemd-analyze calendar --iterations=3 '*-*-* 01:30:00'verify prints nothing; any message is a fault to fix, since systemd skips a line it cannot read. calendar lists the next three nights at 01:30. The timer adds up to 30 minutes on top of that.
Step 6 · Turn the timer on and rehearse a failure
Load the new units, enable the timer, and run the service once through systemd:
sudo systemctl daemon-reload
sudo systemctl enable --now nightly-backup.timer
sudo systemctl start nightly-backup.service
journalctl -u nightly-backup.service -n 30 --no-pager
systemctl list-timers nightly-backup.timerThen check that a failure reaches you. The next commands stop PostgreSQL for a few seconds, so your applications lose their database while it is down. Do this on a practice server or in a quiet moment:
sudo systemctl stop postgresql
sudo systemctl start nightly-backup.service
sudo systemctl start postgresql
journalctl -u notify-failure@nightly-backup.service -n 30 --no-pagerCheck it worked
The first run's journal ends with Backup finished, and list-timers shows nightly-backup.timer with a NEXT time tonight between 01:30 and 02:00. In the rehearsal, systemctl start reports that the job failed, and the alert unit's journal holds a line such as nightly-backup.service failed on backup1 at ... followed by the pg_dumpall connection error, something like pg_dumpall: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed. Your heartbeat service shows no new ping for the failed run. Clear the failed state with sudo systemctl reset-failed nightly-backup.service.
Step 7 · Check how old the newest snapshot is
The heartbeat tells you a run finished. It does not tell you the repository holds a recent snapshot: a settings change can point the job at the wrong repository and still succeed. Ask the repository itself. This script uses Python 3, which Ubuntu Server includes:
sudo tee /usr/local/bin/restic-latest-age > /dev/null <<'EOF'
#!/usr/bin/env python3
"""Fail if the newest nightly restic snapshot is older than a limit in hours (default 36)."""
import datetime, json, re, subprocess, sys
limit = float(sys.argv[1]) if len(sys.argv) > 1 else 36
out = subprocess.run(["/usr/local/bin/backup-restic", "snapshots", "--tag", "nightly", "--json"],
check=True, capture_output=True, text=True).stdout
snapshots = json.loads(out) or []
if not snapshots:
sys.exit("No nightly snapshot found")
# restic writes up to 9 decimal places; keep 6 so older Pythons parse it too.
times = [datetime.datetime.fromisoformat(re.sub(r"(\.\d{6})\d+", r"\1", s["time"])) for s in snapshots]
newest = max(times)
hours = (datetime.datetime.now(datetime.timezone.utc) - newest).total_seconds() / 3600
print(f"Newest nightly snapshot: {newest.isoformat(timespec='seconds')}, {hours:.1f} hours old (limit {limit:g})")
if hours > limit:
sys.exit("Newest nightly snapshot is too old")
EOF
sudo chmod 755 /usr/local/bin/restic-latest-age
sudo restic-latest-ageThe default limit of 36 hours allows for one late or slow night. A nightly job that has missed two nights in a row fails it.
Check it worked
The script prints something like Newest nightly snapshot: 2026-11-26T09:20:41+00:00, 0.1 hours old (limit 36) and exits 0. Now make it fail on purpose with a limit of zero hours:
sudo restic-latest-age 0
echo "exit code: $?"It prints Newest nightly snapshot is too old and the exit code is 1. The restore test in the next step runs this check first, and you can also call it from a monitoring agent.
Step 8 · Test a restore every month
A snapshot is only useful if it restores. Once a month, this script checks the snapshot age, reads back a random tenth of the repository's data to catch damaged files, restores the database dumps into a temporary folder and compares them with the checksums taken at backup time:
sudo tee /usr/local/bin/restic-restore-test > /dev/null <<'EOF'
#!/bin/bash
# Monthly restore test for the nightly-backup repository. Run by restore-test.service.
set -euo pipefail
set -a
. /etc/nightly-backup/env
set +a
cd /
/usr/local/bin/restic-latest-age 36
echo "Reading back 10% of the repository data"
restic check --retry-lock 1h --read-data-subset=10%
target=$(mktemp -d /var/tmp/restore-test.XXXXXX)
trap 'rm -rf "$target"' EXIT
echo "Restoring /var/backups/postgres from the latest nightly snapshot into $target"
restic restore latest --tag nightly --retry-lock 1h --target "$target" --include /var/backups/postgres
cd "$target/var/backups/postgres"
sha256sum -c SHA256SUMS
for f in *.dump; do
pg_restore --list "$f" > /dev/null
echo "$f: readable by pg_restore"
done
echo "Restore test passed"
EOF
sudo chmod 755 /usr/local/bin/restic-restore-testThe checksums prove the bytes came back unchanged; pg_restore --list proves each file is a dump PostgreSQL can read. For a deeper test a few times a year, restore one dump into a scratch database and count its rows, as in /tutorials/back-up-and-restore-postgresql-with-pg-dump. The trap line deletes the restored copy when the script exits, pass or fail, so database dumps are not left in /var/tmp.
The service and timer. Sun *-*-01..07 means a Sunday that falls on day 1 to 7 of the month, so the test runs on the first Sunday, well after the night's backup has finished:
sudo tee /etc/systemd/system/restore-test.service > /dev/null <<'EOF'
[Unit]
Description=Monthly restore test of the nightly restic backup
Wants=network-online.target
After=network-online.target
OnFailure=notify-failure@%N.service
[Service]
Type=oneshot
ExecStart=/usr/local/bin/restic-restore-test
Nice=10
IOSchedulingClass=best-effort
IOSchedulingPriority=7
CacheDirectory=restic
TimeoutStartSec=6h
EOF
sudo tee /etc/systemd/system/restore-test.timer > /dev/null <<'EOF'
[Unit]
Description=Run restore-test on the first Sunday of each month
[Timer]
OnCalendar=Sun *-*-01..07 06:00:00
Persistent=true
[Install]
WantedBy=timers.target
EOF
systemd-analyze verify /etc/systemd/system/restore-test.service /etc/systemd/system/restore-test.timer
systemd-analyze calendar --iterations=3 'Sun *-*-01..07 06:00:00'Run the test once by hand, then enable the timer:
sudo /usr/local/bin/restic-restore-testsudo systemctl daemon-reload
sudo systemctl enable --now restore-test.timer
systemctl list-timers 'nightly-backup*' 'restore-test*'Check it worked
calendar lists three dates, each a Sunday between the 1st and 7th of its month. The test prints the snapshot age, no errors were found from restic check, an OK line for globals.sql, postgres.dump and shop.dump, a readable by pg_restore line per dump, and Restore test passed. ls /var/tmp shows no restore-test. folder afterwards. list-timers shows both timers with their next run. Put a reminder in your calendar to read the restore test's journal after the first Sunday, journalctl -u restore-test.service, so you see it pass on its own at least once.
Step 9 · Remove the demo
Stop both timers first, so nothing starts while you delete files:
sudo systemctl disable --now nightly-backup.timer restore-test.timerThe next command deletes the repository and every snapshot in it. Run it only if RESTIC_REPOSITORY still points at the practice folder /var/backups/restic-repo; if you pointed the job at your real repository, leave that path out:
sudo rm -rf /var/backups/restic-repo /var/backups/postgres /var/cache/restic /etc/nightly-backup
sudo rm -f /etc/systemd/system/nightly-backup.service /etc/systemd/system/nightly-backup.timer
sudo rm -f /etc/systemd/system/restore-test.service /etc/systemd/system/restore-test.timer
sudo rm -f /usr/local/bin/nightly-backup /usr/local/bin/backup-restic /usr/local/bin/restic-latest-age /usr/local/bin/restic-restore-testRemove the alert unit too, unless other jobs on the server use it, and drop the practice database if you created it:
sudo rm -f /etc/systemd/system/notify-failure@.service /usr/local/bin/notify-failure /etc/notify-failure.env
sudo -u postgres dropdb shopsudo systemctl daemon-reload
sudo systemctl reset-failedCheck it worked
systemctl list-timers --all lists neither nightly-backup.timer nor restore-test.timer, ls /var/backups shows no restic-repo or postgres folder, and sudo -u postgres psql -l no longer lists shop. Delete the check in your heartbeat service as well, or it will alert tomorrow night.
Next steps
- Go back over repositories, excludes,
forgetpolicies and off-site SFTP and S3 targets:/tutorials/back-up-a-server-with-restic. - Restore a dump into a scratch database and compare row counts:
/tutorials/back-up-and-restore-postgresql-with-pg-dump. - Learn more timer settings, interval timers and when cron is still simpler:
/tutorials/replace-cron-jobs-with-systemd-timers. - Harden the backup service with systemd's sandbox options:
/tutorials/sandbox-a-systemd-service-with-security-options.
Related tutorials
- Write safer Bash scripts with strict mode and trapsYou will build a small Bash release script that stops on the first error, says which line failed, survives file names with spaces and always removes its temporary files.
- Write least-privilege sudo rules with visudoYou will replace blanket sudo access with checked rule files in /etc/sudoers.d that let two operators restart one service and edit one file, give an automation account a password-free command list, and audit what every account can run.
- Upgrade a server from Ubuntu 24.04 LTS to 26.04 LTSYou will take a backed-up Ubuntu 24.04 server through do-release-upgrade to 26.04 LTS over SSH with a fallback login, then confirm services, repositories and language runtimes work on the new release.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials