Tutorials

Automate backups to object storage with restic

Create encrypted, deduplicated backups of your server to any S3-compatible object storage with restic, and schedule them with systemd timers.

restic makes fast, encrypted, deduplicated backups. Pointing it at S3-compatible object storage keeps a copy of your data off the server – which is what protects you when a disk or the whole server fails.

1. Install restic

sudo apt install -y restic
restic version

2. Store your credentials

Create /root/.restic-env with permissions 600:

export AWS_ACCESS_KEY_ID="your-access-key"
export AWS_SECRET_ACCESS_KEY="your-secret-key"
export RESTIC_REPOSITORY="s3:https://s3.example-provider.com/your-bucket/server1"
export RESTIC_PASSWORD="a-long-random-passphrase"
sudo chmod 600 /root/.restic-env

Save the RESTIC_PASSWORD somewhere safe. Without it the backups cannot be restored.

3. Initialise the repository and run a first backup

sudo -i
source /root/.restic-env
restic init
restic backup /etc /var/www /home --exclude-caches
restic snapshots

For databases, dump them first (for example mysqldump --all-databases > /root/db.sql) and include the dump in the backup.

4. Schedule it with systemd

/etc/systemd/system/restic-backup.service:

[Unit]
Description=restic backup

[Service]
Type=oneshot
ExecStart=/bin/bash -c 'source /root/.restic-env && restic backup /etc /var/www /home --exclude-caches && restic forget --keep-daily 7 --keep-weekly 4 --keep-monthly 6 --prune'

/etc/systemd/system/restic-backup.timer:

[Unit]
Description=Daily restic backup

[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true

[Install]
WantedBy=timers.target
systemctl daemon-reload && systemctl enable --now restic-backup.timer

5. Test a restore

restic restore latest --target /tmp/restore-test --include /etc/hostname

A backup you have never restored is only a hope – test restores regularly and run restic check monthly.

Back to the blog

3 comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Imagined it.
Now deploy it.

No setup fee on Linux & SSD VPS. Free migration help from our in-house engineers.

Get started
Small business owner smiling at a laptop after launching a website
yourproject.com
Server onlineDeployed in 38 seconds
Deploy a VPS in London