Skip to main content

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:

Bash
sudo apt-get update
sudo apt-get install -y rsync acl openssh-client
rsync --version | sed -n 1p

The 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.

Bash
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.txt

Copy it twice, once with a trailing slash on the source and once without:

Bash
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/copy

The 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.
  • -H keeps hard links as hard links. Without it, two names for one file become two separate files, and the backup grows.
  • -A keeps ACLs and -X keeps extended attributes. -a does not include either.

Check it worked

Bash
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.txt

Both 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:

Bash
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:

Bash
sudo rsync -aHAX --delete -v /srv/rsync-demo/ /tmp/rsync-practice/copy/

Check it worked

Bash
ls /tmp/rsync-practice/copy

old-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:

Bash
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/
EOF

A 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:

Bash
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:

Bash
sudo install -d -m 700 /root/.ssh
sudo ssh-keygen -q -t ed25519 -N "" -C "rsync-backup@web1" -f /root/.ssh/backup_ed25519

Then the restore key. ssh-keygen asks for a passphrase; set one.

Bash
sudo ssh-keygen -t ed25519 -C "rsync-restore@web1" -f /root/.ssh/restore_ed25519

Print both public keys. You will paste them on the backup host in a moment.

Bash
sudo cat /root/.ssh/backup_ed25519.pub /root/.ssh/restore_ed25519.pub

On 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:

Bash
sudo apt-get update
sudo apt-get install -y rsync python3 openssh-server attr
Bash
sudo 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_keys

Snapshots 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:

Bash
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
KEYS
  • command= makes SSH run rrsync whatever the client asked for. rrsync then checks the rsync request it was sent.
  • restrict turns off port forwarding, agent forwarding and terminals for this key.
  • -wo lets the key write but never read. -no-del also refuses --delete, so the web server cannot use it to empty a snapshot.
  • /srv/backups/web1 is 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:

Bash
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
CONF

Check it worked

On the web server, try to use the backup key for an ordinary command:

Bash
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:

Bash
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:

Bash
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-snapshot

The flags new to this step:

  • --relative keeps the full source path, so /etc lands in <snapshot>/etc and /srv in <snapshot>/srv.
  • -M--fake-super is passed to the rsync on the backup host. That side runs as rbackup, which cannot create files owned by root or www-data. With --fake-super it stores the real owner, mode, ACLs and attributes in an extended attribute on each file instead.
  • --numeric-ids records 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.

Bash
sudo rsync-snapshot

Now change one file and take a second snapshot:

Bash
echo 'Changed after the first snapshot' | sudo tee -a /srv/rsync-demo/notes.txt >/dev/null
sudo rsync-snapshot

If 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:

Bash
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:

Bash
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:

Bash
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-snapshots

The 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:

Bash
sudo prune-rsync-snapshots /srv/backups/web1 1

It prints would delete and the name of the first snapshot. When that is the one you expect, delete it:

Bash
sudo prune-rsync-snapshots /srv/backups/web1 1 --delete

Check it worked

Bash
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:

Bash
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:

Bash
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:

Bash
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.

Bash
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

Bash
ls -l /srv/rsync-demo
stat -c '%h links: %n' /srv/rsync-demo/reports/*.csv

index.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.

Bash
sudo rm -rf /srv/rsync-demo /tmp/rsync-practice /root/restore

Next 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.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.