I had previously set up a bash script to backup a mysql database. It created daily dumps, gzipped them, and retained 7 daily, 4 weekly and 3 monthly backups via a system of symlinking. That all worked fine for a few years, but I revisited it more recently as we now wanted to keep an offsite copy of the backups, and that would require encrypting them. The problem is gzip doesn't do encryption, so we needed to explore a few options, so I went through gpg, zip with password, etc, and then came to restic.
I've used restic in many other backup scenarios, but I figured it wouldn't be good with database backups. An sql dump file, I reasoned, would have a few tables that had changed, and many that hadn't. So I was thinking that maybe the answer was to loop through the database, dump each table, and then send those to a restic repo. But then I asked my friendly (too friendly) AI and it told me that I had misunderstood how restic does backups, and it actually uses "Content Defined Chunking" to address the exact problem I was facing. Its a bit math-y, but TLDR: go ahead and do a single dump, and content defined chunking will figure out the bits that are the same, and you'll still get a space efficient incremental backup. (And encrypted of course as that was the original aim).
Too good to be true? I'd have to test that out. So I took two consecutive days files and added them to a restic test repo. Wow. The .sql dump file was the same size of course, but the first restic backup was smaller than the gzipped file. And then adding the second, only increased the total data size by 10%. So I re-wrote the script, and now I've been running that for a few days, here are the results.
Before: Database dump 4.5Gb. Gzipped file ~ 650Mb. Retaining 14 of them costs 9Gb.
After 5 days of running the new script: Database dump 4.5Gb. Restic backup actual disk size ~750Gb with 5 incremental backups, so maybe around 1Gb for 14 of them? I'll update this post later when the results are in.
So looks like we're on for a substantial space saving. In addition,
- the backup now takes half the time, down from 113 sec to 60.
- Server load is better during the backup as dumping mysql through gzip seemed quite CPU heavy, whereas dump to plain file in a temporary folder, then let restic compress it seems lighter.
- the script is a lot smaller and cleaner, as restic does all the backup rotation for me with restic forget –prune.
- Encrypted, incremental backups achieved.
#!/bin/bash
set -Eeuo pipefail
## Configuration
DB_USER="databaser"
DB_HOST="localhost"
DATABASES="mysql database2 database3"
MAX_DAILY_BACKUPS=7
MAX_WEEKLY_BACKUPS=4
MAX_MONTHLY_BACKUPS=3
# Restic configuration
export RESTIC_REPOSITORY="/data/database-backups/"
export RESTIC_PASSWORD="adfadfasdfasdfasdf"
# Directories
LOG_DIR="/data/database-backups/backup-logs"
TEMP_DUMP_DIR="/data/db-backup-temp"
## Initialisation
LOG_FILE="$LOG_DIR/$(date +%F)_dbbackup.log"
# Send stdout and stderr to log
exec >> "$LOG_FILE" 2>&1
# Remove logs older than 30 days
find "$LOG_DIR" -maxdepth 1 -type f -name '*_dbbackup.log' -mtime +30 -delete
# Error handling
send_alert() {
local MESSAGE="$1"
# add your mail, webhook etc here.
}
error_handler() {
local exit_code=$1
local line_number=$2
local failed_command=$3
# Prevent error handler from triggering itself
trap - ERR
MESSAGE="Database backup FAILED on $(hostname). Exit code: $exit_code. Line: $line_number"
echo
echo "=========================================="
echo "ERROR: $MESSAGE"
echo "Failed command: $failed_command"
echo "Time: $(date)"
echo "=========================================="
send_alert "$MESSAGE"
exit "$exit_code"
}
trap 'error_handler "$?" "$LINENO" "$BASH_COMMAND"' ERR
# Backup process
SECONDS=0
echo "=========================================="
echo "Starting mysql backup: $(date)"
echo "=========================================="
# Clean up SQL files from previous runs
echo
echo "Removing previous SQL dumps..."
find "$TEMP_DUMP_DIR" -maxdepth 1 -type f -name '*.sql' -print -delete
# Dump databases
for DB in $DATABASES; do
echo
echo "Dumping database: $DB at $SECONDS seconds"
DUMP_FILE="$TEMP_DUMP_DIR/${DB}_$(date +%F).sql"
mysqldump -h "$DB_HOST" -u "$DB_USER" \
--single-transaction --quick --routines --events --triggers \
"$DB" > "$DUMP_FILE"
echo "Successfully dumped $DB ($(du -h "$DUMP_FILE" | cut -f1))"
# Give database a break between dumps
sleep 10
done
# Restic backup and rotate
echo
echo "Adding SQL dumps to restic repository..."
restic backup "$TEMP_DUMP_DIR" \
--tag mysql \
--host "$(hostname -f)"
echo
echo "Applying retention policy..."
restic forget \
--tag mysql \
--keep-daily "$MAX_DAILY_BACKUPS" \
--keep-weekly "$MAX_WEEKLY_BACKUPS" \
--keep-monthly "$MAX_MONTHLY_BACKUPS" \
--prune
echo
echo "Getting repo stats ..."
restic stats --mode raw-data
echo
echo "=========================================="
echo "Database backup completed successfully."
echo "Duration: $SECONDS seconds"
echo "Finished: $(date)"
echo "=========================================="