Introduction
Backing up data to Backblaze B2 using Restic provides an encrypted, deduplicated, and incremental storage solution. This setup avoids vendor lock-in and protects against ransomware through immutable snapshots.
Prerequisites
- A Backblaze B2 bucket.
- Application Key ID and Application Key with
readWritepermissions. - Restic installed (
sudo apt install restic).
1. Initialize the Repository
Export your B2 credentials to the environment to avoid manual entry. Do not store these in plain text in your crontab.
export B2_ACCOUNT_ID="your-id"export B2_ACCOUNT_KEY="your-key"export RESTIC_PASSWORD="a-strong-random-password"export B2_BUCKET_NAME="your-bucket-name"
restic -r b2:${B2_BUCKET_NAME}:/ init2. Create the Backup Script
Create a script at /usr/local/bin/backup-to-b2.sh. This script handles the environment variables and the backup execution.
#!/bin/bashexport B2_ACCOUNT_ID="your-id"export B2_ACCOUNT_KEY="your-key"export RESTIC_PASSWORD="your-password"export RESTIC_REPOSITORY="b2:your-bucket-name:/"
# Backup filesrestic backup /home/user/data --tag system-backup
# Prune old snapshots (keep last 7 days, 4 weeks, 6 months)restic forget --tag system-backup --keep-daily 7 --keep-weekly 4 --keep-monthly 6 --pruneSet permissions: sudo chmod +x /usr/local/bin/backup-to-b2.sh.
3. Automate with systemd
Instead of cron, use a systemd timer for better logging and failure tracking. Create /etc/systemd/system/restic-backup.service:
[Unit]Description=Restic Backup Service
[Service]ExecStart=/usr/local/bin/backup-to-b2.shCreate the timer at /etc/systemd/system/restic-backup.timer:
[Unit]Description=Daily Restic Backup
[Timer]OnCalendar=dailyPersistent=true
[Install]WantedBy=timers.targetEnable the timer:
sudo systemctl daemon-reloadsudo systemctl enable --now restic-backup.timerTroubleshooting
- Error:
repository is already locked: If a previous backup was interrupted, runrestic unlockto remove stale lock files. - Slow performance: If backing up millions of small files, Restic’s metadata scanning can be slow. Use the
--files-fromflag to target specific directories or increase theGOMAXPROCSenvironment variable if CPU is not the bottleneck. - Verification: Run
restic checkmanually to ensure the integrity of the data in B2. This checks for missing or corrupted blobs.