Back up a Linux VPS to S3 storage: restic, timer, restore test

To back up a VPS to S3, dump the databases to files, let restic encrypt and upload those files together with your configuration, run the job from a systemd timer, and restore a copy once a month. At Cloudraft, backups of a VPS are not included automatically, so this job is yours; it takes about half an hour to set up.

Updated:

What needs a copy and what does not

You do not need an image of the whole machine. The operating system reinstalls from the panel, and packages come back with apt. What nobody can give you back is this:

DataTypical pathHow to copy it
Databases/var/lib/postgresql, /var/lib/mysqlDump first; never copy the live files
Uploads and site files/var/www, /srvDirect file backup
Configuration/etc, cron jobs, unit filesDirect file backup
Certificates and keys/etc/letsencrypt, /homeDirect, encrypted
Container volumes/var/lib/docker/volumesDump databases inside, then copy the rest

Decide two numbers before touching a command: how many hours of work you can afford to lose (that sets the schedule) and how long you can stay offline (that tells you how much to rehearse).

Prepare the bucket and install the tools

Create a bucket for backups only, in S3-compatible storage, and note the endpoint, access key and secret key shown in the panel. Do not reuse the key your application uses for uploads: a leak in the app should not open the backups. Any other S3 provider works the same way; only the endpoint changes.

Work in a root shell on Ubuntu or Debian:

sudo -i
apt update && apt install -y restic rclone
umask 077
mkdir -p /etc/restic /var/backups/db
openssl rand -base64 32 > /etc/restic/password
nano /etc/restic/env

Put this in /etc/restic/env, with your own values:

RESTIC_REPOSITORY=s3:https://S3-ENDPOINT/BUCKET/web1
RESTIC_PASSWORD_FILE=/etc/restic/password
RESTIC_CACHE_DIR=/var/cache/restic
AWS_ACCESS_KEY_ID=ACCESS-KEY
AWS_SECRET_ACCESS_KEY=SECRET-KEY

Then load it and create the repository:

set -a; . /etc/restic/env; set +a
restic init

The backup script

Dumps are written uncompressed on purpose: restic compresses and deduplicates by itself, and a gzip file changes completely every night. Delete the database lines you do not use and replace appdb.

cat > /usr/local/sbin/vps-backup <<'EOF'
#!/bin/bash
set -euo pipefail
umask 077
cd /
D=/var/backups/db

# PostgreSQL
runuser -u postgres -- pg_dumpall --globals-only > "$D/globals.sql"
runuser -u postgres -- pg_dump -Fc -Z0 appdb > "$D/appdb.dump"
# MySQL or MariaDB
mysqldump --single-transaction --routines --events --all-databases > "$D/mysql.sql"

restic backup --tag nightly --exclude-caches \
  --exclude node_modules \
  /etc /home /root /var/www "$D"
restic forget --tag nightly --group-by host,tags \
  --keep-daily 7 --keep-weekly 4 --keep-monthly 6 --prune
EOF
chmod 700 /usr/local/sbin/vps-backup
/usr/local/sbin/vps-backup

Because of set -e, a failed dump stops the script instead of uploading half a database in silence. --single-transaction gives a consistent copy of InnoDB tables without locking the site. For SQLite use sqlite3 app.db ".backup '/var/backups/db/app.db'". If the databases are large, the dump needs free disk space; the database server guide covers sizes.

Run it every night with a systemd timer

cat > /etc/systemd/system/vps-backup.service <<'EOF'
[Unit]
Description=Backup to S3
Wants=network-online.target
After=network-online.target

[Service]
Type=oneshot
EnvironmentFile=/etc/restic/env
ExecStart=/usr/local/sbin/vps-backup
Nice=10
EOF

cat > /etc/systemd/system/vps-backup.timer <<'EOF'
[Unit]
Description=Nightly backup

[Timer]
OnCalendar=*-*-* 03:15:00
RandomizedDelaySec=20m
Persistent=true

[Install]
WantedBy=timers.target
EOF

systemctl daemon-reload
systemctl enable --now vps-backup.timer
systemctl start vps-backup.service
journalctl -u vps-backup.service -n 40 --no-pager

Persistent=true runs a missed job after a reboot. Check the age of the newest snapshot from your monitoring: a job that stopped weeks ago sends no error.

How long to keep copies

The numbers in the script are a starting point: seven daily, four weekly and six monthly snapshots. Think about how late you would notice a problem. A deleted file is missed within days; a quietly corrupted table may surface at the end of the quarter.

SituationDailyWeeklyMonthly
Personal project740
Company site, shop1486
Accounting data301224 (ask your accountant)

Deduplication means that a longer history costs much less than the same number of full copies. restic stats --mode raw-data shows what is really stored.

Simpler option: rclone for files only

If all you need is an off-server copy of uploads, rclone is easier to understand. Create the folder with mkdir -p /root/.config/rclone and put this in /root/.config/rclone/rclone.conf:

[s3]
type = s3
provider = Other
access_key_id = ACCESS-KEY
secret_access_key = SECRET-KEY
endpoint = https://S3-ENDPOINT
no_check_bucket = true
rclone sync /var/www/uploads s3:BUCKET/uploads \
  --backup-dir "s3:BUCKET/removed/$(date +%F)"
rclone check /var/www/uploads s3:BUCKET/uploads --one-way

Without --backup-dir, sync repeats your deletions in the bucket, which makes it a mirror rather than a backup. Files are stored as they are, so add an rclone crypt remote if they are private.

Test the restore

Do this now and then once a month, preferably on a second small server:

set -a; . /etc/restic/env; set +a
restic snapshots
restic check --read-data-subset=5%
restic restore latest --target /srv/restore --include /etc/nginx --include /var/backups/db
cd /
runuser -u postgres -- createdb restore_test
runuser -u postgres -- pg_restore --no-owner --no-privileges -d restore_test < /srv/restore/var/backups/db/appdb.dump
runuser -u postgres -- psql -d restore_test -c '\dt+'

Open a few rows, count the orders of yesterday, then run runuser -u postgres -- dropdb restore_test and remove /srv/restore. Write down how long it took: that is your real recovery time.

What this setup does not protect from

  • Stolen root access. Whoever controls the server can use its key to wipe the bucket. Pull a copy from another machine with rclone copy, and harden the server first.
  • Loss of one location. If server and storage are in the same city, keep one more copy elsewhere or ask about disaster recovery, which is arranged individually.
  • Long downtime. A backup is not a standby server; rebuilding takes hours.

VPS backup questions

Does Cloudraft back up my VPS automatically?

No. Automatic backups and snapshots are not included with a VPS, so plan your own job as described here or agree on one with your administrator.

Is restic or rclone better for server backups?

Use restic when you need history, encryption and databases. Use rclone when you want plain files in the bucket that can be opened without a special tool.

How much S3 storage do I need for backups?

As a starting point, take twice the size of the data you back up, not the size of the server disk, then look at the real figure after a month of snapshots.

Can I copy /var/lib/mysql instead of making a dump?

Not while the database is running: files change during the copy and the result may not start. Dump it, or stop the service for the copy.

Does restic work on Windows Server?

Yes, there is a Windows build, and the --use-fs-snapshot option reads open files through VSS. Use Task Scheduler instead of a systemd timer.

Read next

All VPS pages

This page in other languages: Azərbaycanca · Русский

Servers in Baku, prices in manat

Create an account, top up your balance and order the plan you need.