Linux and servers · Intermediate · 22 min
Back up a server with rsync and hard-link snapshots
By Padding · Updated 18 Nov 2026
Ubuntu 26.04.1 LTS · rsync 3.4.1
You will push dated, space-saving rsync snapshots from a server to a backup host over a key that can only run rrsync, prune old snapshots safely, and time a restore of one file and of a whole directory.
On this page
rsync copies only what changed, which makes it a good engine for backups. On its own it gives you a mirror: one copy that follows the live server, mistakes included. Add --link-dest and every run becomes a dated snapshot that looks like a full copy, while files that did not change are hard links to the previous snapshot and take no extra space. You can keep two weeks of daily snapshots for little more than the size of one.
In this tutorial you will learn the rsync flags that matter on a laptop-sized example, then set up a second server as a backup host, push snapshots to it over SSH with a key that can do nothing except write into one directory, prune old snapshots without breaking newer ones, and restore. The commands use rsync 3.4.1, the version in the Ubuntu 26.04 archive.
Two machines are involved and every command says where it runs: the web server (web1, the machine being backed up) and the backup host (backup1, the machine that stores the snapshots).
Step 1 · Install rsync and see what -aHAX keeps
On the web server, install rsync and the ACL tools:
sudo apt-get update
sudo apt-get install -y rsync acl openssh-client
rsync --version | sed -n 1pThe first line of the version output reads rsync version 3.4.1 protocol version 32.
Now make a small practice directory with the things a careless copy loses: a file owned by another user, a file with an ACL, a pair of hard links, a cache and a temporary file.
sudo install -d /srv/rsync-demo/reports /srv/rsync-demo/cache
echo '<h1>Demo site</h1>' | sudo tee /srv/rsync-demo/index.html >/dev/null
echo 'Things to keep' | sudo tee /srv/rsync-demo/notes.txt >/dev/null
echo '<p>Old page</p>' | sudo tee /srv/rsync-demo/old-page.html >/dev/null
echo 'month,total' | sudo tee /srv/rsync-demo/reports/2026-11.csv >/dev/null
sudo ln /srv/rsync-demo/reports/2026-11.csv /srv/rsync-demo/reports/latest.csv
echo 'thumbnail' | sudo tee /srv/rsync-demo/cache/thumb-1.dat >/dev/null
echo 'session' | sudo tee /srv/rsync-demo/session.tmp >/dev/null
sudo dd if=/dev/urandom of=/srv/rsync-demo/archive.bin bs=1M count=5 status=none
sudo chown www-data:www-data /srv/rsync-demo/index.html
sudo setfacl -m u:www-data:r /srv/rsync-demo/notes.txtCopy it twice, once with a trailing slash on the source and once without:
sudo rsync -aHAX /srv/rsync-demo /tmp/rsync-practice/
sudo rsync -aHAX /srv/rsync-demo/ /tmp/rsync-practice/copy/
ls /tmp/rsync-practice /tmp/rsync-practice/copyThe trailing slash on the source is the rule to remember. /srv/rsync-demo means "this directory", so rsync creates rsync-demo inside the destination. /srv/rsync-demo/ means "what is inside this directory", so the files land directly in copy/. A slash on the destination makes no difference.
The flags:
-a(archive) keeps permissions, owners, groups, timestamps and symlinks, and recurses into directories. Owners are only kept when the receiving side runs as root.-Hkeeps hard links as hard links. Without it, two names for one file become two separate files, and the backup grows.-Akeeps ACLs and-Xkeeps extended attributes.-adoes not include either.
Check it worked
stat -c '%h links, inode %i: %n' /tmp/rsync-practice/copy/reports/*.csv
ls -l /tmp/rsync-practice/copy/index.html
sudo getfacl -p /tmp/rsync-practice/copy/notes.txtBoth CSV names show 2 links and the same inode number, index.html is owned by www-data, and getfacl lists user:www-data:r--. To see what -H saves you, run sudo rsync -a /srv/rsync-demo/ /tmp/rsync-practice/no-h/ and the same stat on no-h/reports/*.csv: each name now has 1 links and its own inode.
Step 2 · Use --delete only after a dry run
A plain rsync never removes anything from the destination. Files you delete on the source stay in the copy for ever. --delete removes them, which is what a mirror needs, and is also the flag that destroys data when a path is wrong: swap the source and the destination, or point the destination at the wrong directory, and rsync deletes everything there that the source does not have.
So every new --delete command runs once with --dry-run (-n) and -v first. Remove a page from the source, then preview:
sudo rm /srv/rsync-demo/old-page.html
sudo rsync -aHAX --delete --dry-run -v /srv/rsync-demo/ /tmp/rsync-practice/copy/The output lists deleting old-page.html and ends with (DRY RUN). Nothing has changed yet. Read the list: if it names files you expected to keep, stop and fix the paths. When the list is right, run the same command without --dry-run:
sudo rsync -aHAX --delete -v /srv/rsync-demo/ /tmp/rsync-practice/copy/Check it worked
ls /tmp/rsync-practice/copyold-page.html is gone from the copy and everything else is still there. The snapshots later in this tutorial write into a new directory each time, so they never need --delete. Keep it for mirrors.
Step 3 · Write an excludes file
Some files are not worth backing up: caches the application rebuilds, editor swap files, temporary files. Keep the list in one file so every rsync command uses the same rules.
On the web server:
sudo install -d /etc/rsync-backup
sudo tee /etc/rsync-backup/excludes >/dev/null <<'EOF'
# One pattern per line. Lines starting with # are comments.
# No leading slash, so each pattern matches at any depth.
cache/
*.tmp
*.swp
lost+found/
EOFA trailing slash (cache/) matches directories only. A leading slash would anchor a pattern to the top of the transfer, and the top changes when you use --relative as the snapshot script does, so unanchored patterns are the safer habit here.
Try the rules with a dry run and -i (itemise), which prints one line per file rsync would send:
sudo rsync -aHAX --dry-run -i --exclude-from=/etc/rsync-backup/excludes /srv/rsync-demo/ /tmp/rsync-practice/filtered/Check it worked
The list includes index.html, notes.txt, archive.bin and both CSV files. cache/ and session.tmp are missing, which is what you want. Only exclude what can be rebuilt: anything excluded will not come back in a restore.
Step 4 · Give the web server a key that can only run rrsync
The web server will push to the backup host as an unprivileged user called rbackup. Its SSH keys will be limited with rrsync, a small script shipped with rsync that refuses any command except rsync and keeps every path inside one directory. Ubuntu installs it as /usr/bin/rrsync.
You need two keys, both owned by root on the web server, because root is the user that can read every file:
- a backup key with no passphrase, for unattended runs, allowed to write only (
rrsync -wo); - a restore key with a passphrase, which you use by hand, allowed to read only (
rrsync -ro).
On the web server, create the backup key:
sudo install -d -m 700 /root/.ssh
sudo ssh-keygen -q -t ed25519 -N "" -C "rsync-backup@web1" -f /root/.ssh/backup_ed25519Then the restore key. ssh-keygen asks for a passphrase; set one.
sudo ssh-keygen -t ed25519 -C "rsync-restore@web1" -f /root/.ssh/restore_ed25519Print both public keys. You will paste them on the backup host in a moment.
sudo cat /root/.ssh/backup_ed25519.pub /root/.ssh/restore_ed25519.pubOn the backup host, install rsync, Python (rrsync is a Python script) and the attribute tools, then create the user and a private directory for this server's snapshots:
sudo apt-get update
sudo apt-get install -y rsync python3 openssh-server attrsudo adduser --disabled-password --gecos "" rbackup
sudo install -d -m 700 -o rbackup -g rbackup /srv/backups/web1
sudo install -d -m 700 -o rbackup -g rbackup /home/rbackup/.ssh
sudo install -m 600 -o rbackup -g rbackup /dev/null /home/rbackup/.ssh/authorized_keysSnapshots of /etc include password hashes and private keys, which is why the directory is mode 700.
Still on the backup host, add the two keys. Each line starts with the options that restrict it, then the public key you printed on the web server. Replace the AAAA... parts with your keys:
sudo tee -a /home/rbackup/.ssh/authorized_keys >/dev/null <<'KEYS'
command="/usr/bin/rrsync -wo -no-del /srv/backups/web1",restrict ssh-ed25519 AAAA...your-backup-key... rsync-backup@web1
command="/usr/bin/rrsync -ro /srv/backups/web1",restrict ssh-ed25519 AAAA...your-restore-key... rsync-restore@web1
KEYScommand=makes SSH run rrsync whatever the client asked for. rrsync then checks the rsync request it was sent.restrictturns off port forwarding, agent forwarding and terminals for this key.-wolets the key write but never read.-no-delalso refuses--delete, so the web server cannot use it to empty a snapshot./srv/backups/web1is the only directory the key can touch. A path that starts with/means the top of that directory, and any path containing..is refused.
Back on the web server, give each key a short name in root's SSH config. Replace 203.0.113.20 with your backup host's address:
sudo tee -a /root/.ssh/config >/dev/null <<'CONF'
Host backup1
HostName 203.0.113.20
User rbackup
IdentityFile /root/.ssh/backup_ed25519
IdentitiesOnly yes
Host backup1-restore
HostName 203.0.113.20
User rbackup
IdentityFile /root/.ssh/restore_ed25519
IdentitiesOnly yes
CONFCheck it worked
On the web server, try to use the backup key for an ordinary command:
sudo ssh backup1 ls /The first connection asks you to confirm the backup host's fingerprint. After that, instead of a directory listing you get an error from rrsync and nothing runs. Now a harmless rsync that does nothing:
sudo rsync -av --dry-run /etc/hostname backup1:/It prints hostname and ends with (DRY RUN), so the key works for rsync and only for rsync.
Step 5 · Take dated snapshots with --link-dest
The snapshot script runs on the web server. Each run creates a new directory on the backup host named after the time in UTC, such as 2026-11-26-020000, so names sort in date order. It passes the previous snapshot to --link-dest: rsync compares each file with its copy there, and if nothing changed it makes a hard link instead of sending the file again.
Because the backup key cannot list the backup host, the script remembers the last good snapshot in /var/lib/rsync-snapshot/last on the web server. It only writes that file after rsync succeeds, so a failed run is never used as the base for the next one.
On the web server:
sudo tee /usr/local/sbin/rsync-snapshot >/dev/null <<'EOF'
#!/bin/bash
# Push a dated, hard-linked snapshot of this server to backup1.
set -euo pipefail
sources=(/etc /srv)
state=/var/lib/rsync-snapshot/last
name=$(date -u +%Y-%m-%d-%H%M%S)
mkdir -p "$(dirname "$state")"
link_dest=()
if [[ -s $state ]]; then
# A leading slash is the top of the rrsync directory on backup1.
link_dest=(--link-dest="/$(cat "$state")")
fi
rc=0
rsync -aHAX --numeric-ids --relative -M--fake-super \
--exclude-from=/etc/rsync-backup/excludes \
"${link_dest[@]}" \
"${sources[@]}" "backup1:/$name/" || rc=$?
# 24 means some files vanished while rsync ran, which is normal on a live server.
if (( rc != 0 && rc != 24 )); then
echo "rsync failed with exit code $rc; $name is incomplete" >&2
exit "$rc"
fi
echo "$name" > "$state"
echo "snapshot $name complete"
EOF
sudo chmod 755 /usr/local/sbin/rsync-snapshotThe flags new to this step:
--relativekeeps the full source path, so/etclands in<snapshot>/etcand/srvin<snapshot>/srv.-M--fake-superis passed to the rsync on the backup host. That side runs asrbackup, which cannot create files owned by root orwww-data. With--fake-superit stores the real owner, mode, ACLs and attributes in an extended attribute on each file instead.--numeric-idsrecords user and group numbers rather than names, so a restore does not depend on the backup host having the same users.
Change sources to the directories your server needs, for example /etc /home /srv /var/www. Do not rely on copying a running database's data directory; dump it first, as in /tutorials/back-up-and-restore-postgresql-with-pg-dump, and back up the dump.
Take the first snapshot. It sends everything, so on a large server it is the slow one.
sudo rsync-snapshotNow change one file and take a second snapshot:
echo 'Changed after the first snapshot' | sudo tee -a /srv/rsync-demo/notes.txt >/dev/null
sudo rsync-snapshotIf the backup host sits behind a slow or metered link, as with many servers on prepaid mobile data, add --bwlimit=2m to the rsync line to cap it at about 2 MB a second. Only the first snapshot is large; later ones send only the changes.
Check it worked
On the backup host, list the snapshots and measure them together. du counts a hard-linked file once, in the first directory it meets:
sudo ls /srv/backups/web1
sudo du -sh /srv/backups/web1/*
sudo sh -c 'stat -c "%h links: %n" /srv/backups/web1/*/srv/rsync-demo/archive.bin'There are two directories. The first is several megabytes; the second is a small fraction of that, because only notes.txt and the directories themselves are new. Each archive.bin shows 2 links: both snapshots point at one copy on disk.
Every file on the backup host belongs to rbackup. The real details live in an attribute; read one:
sudo sh -c 'getfattr -n user.rsync.%stat /srv/backups/web1/*/srv/rsync-demo/index.html'The value is something like "100644 0,0 33:33": the file mode, a device number field, and the owner and group as numbers (33 is www-data on Ubuntu).
To run the script every night, schedule sudo /usr/local/sbin/rsync-snapshot with a systemd timer as in /tutorials/replace-cron-jobs-with-systemd-timers. rrsync holds a lock on the directory while it receives, so a second run that starts before the first finishes is refused instead of mixing two snapshots.
Step 6 · Prune old snapshots safely
Hard links make pruning simple: a file's data is only freed when its last name is deleted, so removing an old snapshot never damages a newer one. What can go wrong is the command around it, such as an empty variable in an rm -rf, or a pattern that also matches something else. Run pruning on the backup host, where the backup key cannot reach, and make the script refuse anything odd.
On the backup host:
sudo tee /usr/local/sbin/prune-rsync-snapshots >/dev/null <<'EOF'
#!/bin/bash
# Usage: prune-rsync-snapshots DIR KEEP [--delete]
# Keeps the newest KEEP snapshots in DIR. Without --delete it only prints.
set -euo pipefail
if (( $# < 2 )); then echo "usage: $0 DIR KEEP [--delete]" >&2; exit 2; fi
dir=$(realpath -e -- "$1")
keep=$2
mode=${3:-}
[[ $dir == /srv/backups/?* ]] || { echo "refusing: $dir is not under /srv/backups" >&2; exit 2; }
[[ $keep =~ ^[0-9]+$ ]] && (( keep >= 1 )) || { echo "KEEP must be 1 or more" >&2; exit 2; }
# Take the same lock rrsync holds while a snapshot is arriving.
exec 9<"$dir"
flock -n 9 || { echo "a snapshot is being written to $dir; try later" >&2; exit 1; }
# Only directories whose names look like snapshots, oldest first.
mapfile -t snaps < <(find "$dir" -mindepth 1 -maxdepth 1 -type d \
-regextype posix-extended -regex '.*/[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{6}' \
-printf '%f\n' | sort)
count=${#snaps[@]}
if (( count <= keep )); then echo "$count snapshots, keeping all"; exit 0; fi
for old in "${snaps[@]:0:count-keep}"; do
if [[ $mode == --delete ]]; then
rm -rf -- "${dir:?}/${old:?}"
echo "deleted $old"
else
echo "would delete $old"
fi
done
EOF
sudo chmod 755 /usr/local/sbin/prune-rsync-snapshotsThe script resolves the directory and refuses anything outside /srv/backups, never keeps fewer than one snapshot (so the one the web server links against survives), only considers names in the snapshot format, and deletes nothing unless you add --delete.
On your server, 14 keeps two weeks of daily snapshots. Here keep 1 so you can watch the oldest go. Preview first:
sudo prune-rsync-snapshots /srv/backups/web1 1It prints would delete and the name of the first snapshot. When that is the one you expect, delete it:
sudo prune-rsync-snapshots /srv/backups/web1 1 --deleteCheck it worked
sudo ls /srv/backups/web1
sudo sh -c 'stat -c "%h links: %n" /srv/backups/web1/*/srv/rsync-demo/archive.bin'
sudo sh -c 'sha256sum /srv/backups/web1/*/srv/rsync-demo/archive.bin /srv/rsync-demo/archive.bin'One snapshot is left, the newer one. archive.bin in it now has 1 links, and its checksum still matches the live file: deleting the old snapshot removed a name, not the data.
Step 7 · Time a restore of one file and of a directory
A backup you have never restored is a guess. Restore once now, time it, and write the time down, so you know what to expect when it matters.
On the web server, list the snapshots through the read-only restore key. SSH asks for the restore key's passphrase:
sudo rsync backup1-restore:/You see one line for the directory itself (.) and one per snapshot. Pick one. Here, use the newest, which the web server has on record:
snap=$(sudo cat /var/lib/rsync-snapshot/last)
echo "$snap"To restore from an older snapshot, set snap to a name from the list instead.
Restore one file
Restore to a separate place first, never straight over the live file, so you can compare before you replace anything:
sudo install -d -m 700 /root/restore
time sudo rsync -aHAX --numeric-ids -M--fake-super "backup1-restore:/$snap/srv/rsync-demo/notes.txt" /root/restore/
sudo diff /root/restore/notes.txt /srv/rsync-demo/notes.txt
sudo getfacl -p /root/restore/notes.txt-M--fake-super matters on the way back too: it tells the backup host to send the owner, mode and ACL it stored, rather than its own rbackup ownership. Leave it out and the file comes back with the backup host's ownership (rbackup's user number) instead of the owner, mode and ACL it had on web1.
Restore a whole directory
Warning: the next command deletes /srv/rsync-demo. Run it only on the practice directory, never on a directory you have not restored somewhere else first.
sudo rm -rf /srv/rsync-demo
time sudo rsync -aHAX --numeric-ids -M--fake-super "backup1-restore:/$snap/srv/rsync-demo/" /srv/rsync-demo/The trailing slash on the source copies the directory's contents into /srv/rsync-demo/, as in the first step.
Check it worked
ls -l /srv/rsync-demo
stat -c '%h links: %n' /srv/rsync-demo/reports/*.csvindex.html is owned by www-data again, the two CSV names are hard links (2 links), and notes.txt has the line you added before the second snapshot. cache/ and session.tmp did not come back, because they were never backed up. Each time printed a real line, well under a second for this directory; on your server, note it with the size of the directory.
When you have finished practising, remove the practice files on the web server. The next snapshot no longer includes them.
sudo rm -rf /srv/rsync-demo /tmp/rsync-practice /root/restoreNext steps
You now have dated snapshots that cost little space, a backup key that cannot read or delete, a pruning script that refuses mistakes, and a restore you have timed.
- The backup key can still write into old snapshots. For backups that a compromised server cannot touch, or that are encrypted before they leave it, use /tutorials/back-up-a-server-with-restic.
- Run the snapshot script every night with /tutorials/replace-cron-jobs-with-systemd-timers, and the pruning script on the backup host the same way at a different hour.
- Add database dumps to what you back up with /tutorials/back-up-and-restore-postgresql-with-pg-dump.
- Review how the two servers authenticate in /tutorials/log-in-to-a-server-with-ssh-keys.
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