Be Your Own Cloud code · PART 4 — MAKING IT RESILIENT

Chapter 18 Backups Done Right: The 3-2-1 Rule With Restic

6 blocks · pp. 80–82 in the paperback

Restic: One Tool, Encrypted by Default

# p. 80

Run Terminal, on the server
sudo apt install restic

# Initialize a repository (example: Backblaze B2)
export B2_ACCOUNT_ID=your_key_id
export B2_ACCOUNT_KEY=your_application_key
export RESTIC_REPOSITORY=b2:your-bucket-name:/backups
export RESTIC_PASSWORD=your-long-encryption-password

restic init

# p. 81

Run Terminal, same shell as the block above
restic -r /mnt/backup/restic init

What to Actually Back Up

# p. 81

Run Terminal, same shell as above
restic backup /opt/stacks --exclude-caches
restic backup /mnt/media/nextcloud-data
restic backup /mnt/media/photos

Automate It, Then Prune It

# p. 82

File /opt/scripts/restic.env
# /opt/scripts/restic.env
export B2_ACCOUNT_ID=your_key_id
export B2_ACCOUNT_KEY=your_application_key
export RESTIC_REPOSITORY=b2:your-bucket-name:/backups
export RESTIC_PASSWORD=your-long-encryption-password

# p. 82

File /opt/scripts/backup.sh
#!/bin/bash
# /opt/scripts/backup.sh
set -euo pipefail   # stop at the first failed command
source /opt/scripts/restic.env

# Consistent database copies first -- live database files can be
# caught mid-write
docker exec immich_postgres pg_dump --clean --if-exists \
  --dbname=immich --username=postgres \
  | gzip > /opt/stacks/immich/db-dump.sql.gz
sqlite3 /opt/stacks/vaultwarden/data/db.sqlite3 \
  ".backup '/opt/stacks/vaultwarden/db-backup.sqlite3'"

# The same backup to both repositories: off-site first, then the local
# drive
for repo in "$RESTIC_REPOSITORY" /mnt/backup/restic; do
  restic -r "$repo" backup /opt/stacks --exclude-caches \
    --exclude /opt/stacks/immich/pgdata \
    --exclude '/opt/stacks/vaultwarden/data/db.sqlite3*'
  restic -r "$repo" backup /mnt/media/nextcloud-data
  restic -r "$repo" backup /mnt/media/photos
  restic -r "$repo" forget --prune \
    --keep-daily 7 --keep-weekly 4 --keep-monthly 6
done

# p. 82

Run Terminal, on the server
sudo chmod 600 /opt/scripts/restic.env
sudo chmod 700 /opt/scripts/backup.sh
Crontab sudo crontab -e (root's crontab)
# sudo crontab -e   (root's crontab: much of /opt/stacks is owned by
# container users)
0 3 * * * /opt/scripts/backup.sh >> /var/log/restic-backup.log 2>&1

Reproduced exactly from Be Your Own Cloud, Chapter 18. The book explains what each line does and what to do when it doesn't work. About the book

Something here not working as the book describes? Tell the author.