Platform Engineering · Lesson 23

Backup and Restore on Linux

A backup is only as good as the last restore you tested. Backing up a Linux server well means deciding how much data you can lose (RPO) and how long you can be down (RTO), capturing data in a consistent state, keeping encrypted copies off the host where an attacker with root cannot delete them, and proving every month that a restore works. This lesson loses one server at 03:00 and follows the backups that bring it back, and the two ways they turn out not to exist.

Difficulty: Intermediate · Know this first: Lesson 16, Lesson 17

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up hours from losing the server to running again. It is a worked example, not a measurement. The off-site and monitor hops are where backups turn out not to exist.

Try it: how much would you lose?

Set how often backups run, how often they are monitored and restore-tested, and whether the host can delete them. Then the server dies.

up to 24 hdata lost (normal failure)
about 1 dayif the job breaks silently
survivesif an attacker gets root

Good: a broken job is caught within a day, and an attacker cannot delete history

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Backups grow in four levels: copies, real backups, protected and monitored backups, and backup as a tested practice across a fleet.

Basic — Make a copy you can restore

At the basic level you can archive and restore files.

  • tar -czf etc-$(date +%F).tgz /etc and tar -tzf to list it.
  • rsync -a src/ dest/ to copy, preserving permissions and times.
  • Restore a single file and compare: diff or sha256sum.

Where it breaks: keeping the only copy on the same disk as the original.

Try it: Basic

You back up /srv to /backup on the same disk. What does it protect against?

Now do it: Archive /etc with tar, then restore one file from it into /tmp.

Intermediate — Real backups with restic or Borg

At the intermediate level backups are snapshots, consistent, and scheduled.

  • restic init, restic backup, restic snapshots, restic restore, restic forget --keep-....
  • Database dumps with the database's tool, in a script with set -euo pipefail.
  • A systemd timer with Persistent=true; the key in the team vault.

Try it: Intermediate

pg_dump db | gzip > db.gz exits 0 even when pg_dump fails. What fixes the script?

Now do it: Run false | true; echo $? with and without set -o pipefail.

Advanced — Out of reach, and watched

At the advanced level backups survive an attacker and failures are noticed.

  • Append-only repositories or object lock; host credentials that can add but not delete; pruning from a separate machine.
  • Alerts on snapshot age and size; a heartbeat for the job itself.
  • restic check --read-data-subset=5% to verify the stored data.

Try it: Advanced

Where should restic forget --prune run if hosts may not delete backups?

Now do it: List which credentials could delete your backups today.

Master — Backup as a practice

At the master level restores are routine and measured.

  • RPO and RTO per system, with restore methods that meet them (dumps, log archiving, replicas, images).
  • Automated monthly restore tests that start the app and check recent data, with durations recorded.
  • Disaster recovery exercises that restore a whole service in another region.

Trade-off: immutable, off-site, frequently tested backups cost storage and engineering time; their value appears only on the worst day, which is why the tests must be scheduled, not hoped for.

Try it: Master

What best proves you can meet a 4-hour RTO?

Now do it: Schedule a restore test for one system and time it.

Go deeper

A complete backup you can practise with restic against a local repository, then the pieces for production.

Back up, list, and restore

sudo apt install -y restic
export RESTIC_REPOSITORY=/tmp/restic-repo RESTIC_PASSWORD=change-me   # in production: the vault
restic init
restic backup /etc --tag etc
echo "changed" | sudo tee -a /etc/motd >/dev/null; restic backup /etc --tag etc
restic snapshots
restic diff $(restic snapshots --json | python3 -c "import sys, json; s = json.load(sys.stdin); print(s[0]['short_id'], s[-1]['short_id'])")
restic restore latest --target /tmp/restore --include /etc/motd && diff /etc/motd /tmp/restore/etc/motd
restic forget --keep-daily 7 --keep-weekly 4 --keep-monthly 12 --prune

A database dump that fails loudly

#!/usr/bin/env bash
set -euo pipefail
out=/var/backups/db-$(date -u +%F).dump
pg_dump -Fc --dbname="$DATABASE_URL" > "$out"
size=$(stat -c %s "$out")
[ "$size" -gt 1000000 ] || { echo "dump too small: $size bytes" >&2; exit 1; }
pg_restore -l "$out" >/dev/null                  # proves it is readable
restic backup "$out" --tag db

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. Backups existed until the moment they were needed.

Timeline

  • 01:30An attacker with a stolen admin key logs into a file server and finds the backup script, with full-access cloud credentials in it.
  • 02:10The attacker deletes every snapshot in the bucket, which has no versioning or object lock, then encrypts the server's disks.
  • 09:00The team finds both the encrypted server and the empty bucket. Some files are recovered from laptops; the rest are gone.

What changed after

Buckets use versioning and object lock, hosts get put-only credentials, pruning runs from an isolated account, the backup age alert pages on-call, and restores are tested monthly with the duration recorded.

Try it yourself, from scratch

Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.

Before you start: restic: sudo apt install -y restic.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. A local repository, two backups, and the snapshot list.

    export RESTIC_REPOSITORY=/tmp/lab-repo RESTIC_PASSWORD=change-me
    mkdir -p lab-data; echo "v1" > lab-data/notes.txt
    restic init -q; restic backup -q lab-data; echo "v2" > lab-data/notes.txt; restic backup -q lab-data; restic snapshots
  2. Restore the older version of one file and compare.

    FIRST=$(restic snapshots --json | python3 -c "import sys, json; print(json.load(sys.stdin)[0]['short_id'])")
    restic restore -q "$FIRST" --target /tmp/lab-restore; cat /tmp/lab-restore/*/lab-data/notes.txt 2>/dev/null || find /tmp/lab-restore -name notes.txt -exec cat {} \;
  3. A pipeline that fails loudly: pipefail turns a failed dump into a failed script.

    bash -c "false | gzip > /dev/null; echo exit without pipefail: \$?"
    bash -c "set -o pipefail; false | gzip > /dev/null; echo exit with pipefail: \$?"
  4. Check the repository, then clean up.

    restic check -q && echo "repository OK"; rm -rf lab-data /tmp/lab-repo /tmp/lab-restore

2. Python: backup_monitor.py

This program is the monitor a backup job needs: it checks the newest snapshot's age and compares its size with the previous ones, which catches both a job that stopped and a job that "succeeds" with an empty dump. Save it as backup_monitor.py, then run it.

# backup_monitor.py
import statistics

snapshots = [  # (hours ago, size in MB), newest last
    (170, 2_410), (146, 2_415), (122, 2_420), (98, 2_431), (74, 2_438), (50, 2_445), (26, 0.02),
]
MAX_AGE_H, DROP = 26, 0.5

age, size = snapshots[-1]
recent = statistics.median(s for _, s in snapshots[-6:-1])
alerts = []
if age > MAX_AGE_H:
    alerts.append(f"newest snapshot is {age} h old (limit {MAX_AGE_H} h)")
if size < recent * DROP:
    alerts.append(f"newest snapshot is {size} MB vs a usual {recent:,.0f} MB: the dump is probably empty")
print("exit code of the job: 0 (it 'succeeded')")
print("monitor:", "ALERT - " + "; ".join(alerts) if alerts else "ok")
good = [h for h, s in snapshots if s >= recent * DROP]
print(f"newest usable backup: {min(good)} hours ago")

Run it, and you should see this output:

$ python3 backup_monitor.py
exit code of the job: 0 (it 'succeeded')
monitor: ALERT - newest snapshot is 0.02 MB vs a usual 2,431 MB: the dump is probably empty
newest usable backup: 50 hours ago

3. What to notice

4. Advanced: every step as one Bash script

The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/linux-backup-and-restore && cd ~/labs/linux-backup-and-restore) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "Backup and Restore on Linux", as one script (save it as lab.sh).
#
#   ./lab.sh          run every step, in order
#   ./lab.sh 2 4      run only steps 2 and 4
#   ./lab.sh --list   list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.

STEPS=(
  'A local repository, two backups, and the snapshot list.'
  'Restore the older version of one file and compare.'
  'A pipeline that fails loudly: pipefail turns a failed dump into a failed script.'
  'Check the repository, then clean up.'
)

step_1() {
export RESTIC_REPOSITORY=/tmp/lab-repo RESTIC_PASSWORD=change-me
mkdir -p lab-data; echo "v1" > lab-data/notes.txt
restic init -q; restic backup -q lab-data; echo "v2" > lab-data/notes.txt; restic backup -q lab-data; restic snapshots
}

step_2() {
FIRST=$(restic snapshots --json | python3 -c "import sys, json; print(json.load(sys.stdin)[0]['short_id'])")
restic restore -q "$FIRST" --target /tmp/lab-restore; cat /tmp/lab-restore/*/lab-data/notes.txt 2>/dev/null || find /tmp/lab-restore -name notes.txt -exec cat {} \;
}

step_3() {
bash -c "false | gzip > /dev/null; echo exit without pipefail: \$?"
bash -c "set -o pipefail; false | gzip > /dev/null; echo exit with pipefail: \$?"
}

step_4() {
restic check -q && echo "repository OK"; rm -rf lab-data /tmp/lab-repo /tmp/lab-restore
}

# print a step that has to be run by hand, instead of running it
by_hand() {
  echo "  (run this one yourself: $1)"
  sed 's/^/    /'
}

RESULTS=()
run_step() {
  local n=$1 start=$SECONDS code
  printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
  "step_$n"
  code=$?
  RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}

summary() {
  echo
  echo "== summary"
  local r
  for r in "${RESULTS[@]}"; do echo "  $r"; done
}

case "${1:-}" in
  -h|--help) sed -n '2,6p' "$0"; exit 0 ;;
  --list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac

[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
  if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
    echo "there is no step '$n'; try --list" >&2
    exit 2
  fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done

Then make it executable and run it:

chmod +x lab.sh
./lab.sh --list     # the steps
./lab.sh            # every step, then a summary of exit codes and times
./lab.sh 2 3        # only steps 2 and 3

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Design backups for a small company: a PostgreSQL database, a file server with 2 TB of documents, and 15 Linux app servers built from configuration management.

Clarifying questions to ask

What are the RPO and RTO of each? What do you back up from each, and what do you rebuild? Where do the copies live, and who can delete them? How do you know tonight's backup worked? When did you last restore?

Rough sizing

Say the database is 200 GB and changes 5 GB a day, documents change 10 GB a day, the database RPO is 15 minutes, and the RTO is 4 hours for everything.

Shape of the answer

Database: nightly pg_dump plus WAL archiving for a 15-minute RPO, to object storage with object lock. Documents: restic nightly with deduplication to two destinations, one immutable. App servers: no backups, rebuilt from code, with /etc in Git. Host credentials put-only, pruning from an isolated account, alerts on age and size, monthly timed restore tests of each.

Trade-offs to name

Object lock protects history and makes mistakes permanent for the lock period, so size it carefully. WAL archiving meets a tight RPO and adds a restore procedure to practise. Rebuilding app servers instead of backing them up requires configuration management to be complete.

Saved on this device, in this browser.
Next in this series · Lesson 24
Git

Git is a save system for code. You change a file, you save a snapshot of that change with a short note, and Git remembers every snapshot forever. If a deploy breaks at 2 AM, you can look back through the snapshots, find the exact…

Go to Lesson 24 →

Or browse the full course from the Lessons index.