
Back up MySQL and Postgres running in Docker to Cloudflare R2 every night: consistent dumps, integrity checks, 30-day retention, alerts and a tested restore.
Once your apps run in Docker — like the Laravel and Next.js stacks behind Traefik — your data lives in a Docker volume on one disk. That's fine right up until the disk dies, the provider loses the VM, or someone runs docker volume prune on the wrong box.
I've written about Laravel backups to Google Drive before. That works great for one Laravel app. This post is the version for everything else: any MySQL or Postgres container, whatever app sits on top of it, dumped every night and shipped off the server to Cloudflare R2.
Why R2? It's S3-compatible, it has a free tier that comfortably covers a few databases' worth of nightly dumps, and it doesn't charge egress fees — which matters on the one day you actually need to download a backup in a hurry.
By the end you'll have:
Most broken backups don't throw errors. They look like this:
mysqldump dies halfway, but it's piped into gzip, and gzip exits fine. The script reports success and uploads half a database.Every step below closes one of these.
In the Cloudflare dashboard:
db-backups.db-backups bucket.https://<account-id>.r2.cloudflarestorage.com).Scope the token to the one bucket. If this server is ever compromised, the attacker gets your backups bucket — not every bucket in your account.
rclone talks to R2 natively. Install it with the official script — distro packages are often old enough to predate R2 support:
curl https://rclone.org/install.sh | sudo bash
rclone versionCreate the config as root, since the backup will run from root's cron:
sudo mkdir -p /root/.config/rclone
sudo nano /root/.config/rclone/rclone.conf[r2]
type = s3
provider = Cloudflare
access_key_id = YOUR_ACCESS_KEY_ID
secret_access_key = YOUR_SECRET_ACCESS_KEY
endpoint = https://YOUR_ACCOUNT_ID.r2.cloudflarestorage.com
acl = private
# The token can't create buckets (good), so stop rclone from trying.
no_check_bucket = truesudo chmod 600 /root/.config/rclone/rclone.confTest it:
echo "hello" | sudo rclone rcat r2:db-backups/test.txt
sudo rclone ls r2:db-backups
sudo rclone delete r2:db-backups/test.txtIf you see test.txt listed, the credentials, endpoint and bucket are all correct.
One script handles both MySQL and Postgres. It dumps from inside the database container, so it uses the database credentials already set in the container's environment — no passwords in the script, in ps output, or in your shell history.
#!/usr/bin/env bash
# Nightly database backup: dump from the container, verify, upload to R2, prune.
set -euo pipefail
# ---- per-app settings ----
APP_NAME="laravel-app" # used in file and remote names
APP_DIR="/home/deploy/laravel-app" # where docker-compose.yml lives
SERVICE="mysql" # compose service name
ENGINE="mysql" # mysql or postgres
BACKUP_DIR="/var/backups/db/${APP_NAME}"
REMOTE="r2:db-backups/${APP_NAME}"
KEEP_LOCAL_DAYS=3
KEEP_REMOTE_DAYS=30
HEALTHCHECK_URL="" # optional, see Step 5
# ---------------------------
fail() {
echo "[$(date -Is)] BACKUP FAILED: $1" >&2
[ -n "$HEALTHCHECK_URL" ] && curl -fsS -m 10 --retry 3 "${HEALTHCHECK_URL}/fail" >/dev/null || true
exit 1
}
trap 'fail "line $LINENO"' ERR
mkdir -p "$BACKUP_DIR"
cd "$APP_DIR"
stamp="$(date +%F-%H%M)"
if [ "$ENGINE" = "mysql" ]; then
final="${BACKUP_DIR}/${APP_NAME}-${stamp}.sql.gz"
else
final="${BACKUP_DIR}/${APP_NAME}-${stamp}.dump"
fi
# Write to a temp name and rename at the end, so a half-written file never
# looks like a finished backup.
tmp="${final}.partial"
echo "[$(date -Is)] dumping ${SERVICE} (${ENGINE})"
if [ "$ENGINE" = "mysql" ]; then
# --single-transaction: consistent snapshot of InnoDB tables without locking them.
# MYSQL_PWD inside the container keeps the password off the command line.
docker compose exec -T "$SERVICE" sh -c \
'MYSQL_PWD="$MYSQL_ROOT_PASSWORD" exec mysqldump -u root \
--single-transaction --quick --routines --triggers "$MYSQL_DATABASE"' \
| gzip > "$tmp"
# pipefail catches a failed mysqldump, but also confirm the dump finished:
# mysqldump writes this footer only when it completes.
gzip -t "$tmp"
zcat "$tmp" | tail -n 1 | grep -q "Dump completed" || fail "dump is incomplete"
else
# Custom format (-Fc) is compressed and lets you restore single tables later.
docker compose exec -T "$SERVICE" sh -c \
'exec pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Fc' > "$tmp"
# Make pg_restore read the archive's table of contents: a corrupt file fails here.
docker compose exec -T "$SERVICE" pg_restore --list < "$tmp" > /dev/null || fail "dump is unreadable"
fi
mv "$tmp" "$final"
echo "[$(date -Is)] dump ok: $(du -h "$final" | cut -f1)"
rclone copy "$final" "$REMOTE/"
echo "[$(date -Is)] uploaded to ${REMOTE}"
# Prune: a few days locally for quick restores, a month in R2.
find "$BACKUP_DIR" -type f -mtime +"$KEEP_LOCAL_DAYS" -delete
rclone delete "$REMOTE" --min-age "${KEEP_REMOTE_DAYS}d"
[ -n "$HEALTHCHECK_URL" ] && curl -fsS -m 10 --retry 3 "$HEALTHCHECK_URL" >/dev/null || true
echo "[$(date -Is)] done"The two lines that do the most work are easy to miss:
set -o pipefail. Without it, mysqldump ... | gzip reports the exit code of gzip, which succeeds even when mysqldump crashed. That's the "truncated dump that succeeded" from earlier.mysqldump writes -- Dump completed on ... as its very last line. No footer, no upload.$MYSQL_ROOT_PASSWORD, $MYSQL_DATABASE, $POSTGRES_USER and $POSTGRES_DB are in single quotes on purpose: they're expanded inside the container, from the environment you gave it in docker-compose.yml, not on the host.
Make it executable and run it once by hand:
sudo chmod +x /usr/local/bin/db-backup.sh
sudo /usr/local/bin/db-backup.sh[2026-11-09T02:30:01+00:00] dumping mysql (mysql)
[2026-11-09T02:30:04+00:00] dump ok: 4.2M
[2026-11-09T02:30:06+00:00] uploaded to r2:db-backups/laravel-app
[2026-11-09T02:30:06+00:00] donesudo rclone ls r2:db-backups/laravel-appMore than one app on the box? Copy the script per app (
db-backup-shop.sh,db-backup-blog.sh) and change the settings block. Each app gets its own folder in the bucket.
Same pattern as the weekly cleanup in my maintenance post — a file in /etc/cron.d:
sudo tee /etc/cron.d/db-backup >/dev/null <<'EOF'
30 2 * * * root /usr/local/bin/db-backup.sh >> /var/log/db-backup.log 2>&1
EOFThat runs at 02:30 server time, when traffic is usually lowest. Check the log the next morning:
tail -n 20 /var/log/db-backup.logA failing backup is bad. A backup that stopped running is worse, because nothing errors — there's no run to fail.
The fix is a "dead man's switch": the script pings a URL after every successful run, and if the ping doesn't arrive on schedule, you get an email. Healthchecks.io does exactly this and has a free tier.
HEALTHCHECK_URL="https://hc-ping.com/your-check-uuid"Now you're covered both ways: a failed run pings /fail immediately, and a run that never happens — cron removed, server down, disk full — sets off the alert once the grace time passes.
A backup you've never restored is a rumor. Restore into a throwaway container, never into production, and check the data is really there.
MySQL:
# Grab the newest backup from R2
sudo rclone copy r2:db-backups/laravel-app /tmp/restore-test --max-age 2d
latest=$(ls -t /tmp/restore-test/*.sql.gz | head -n 1)
# A disposable MySQL with no volume: deleted the moment it stops
docker run -d --rm --name restore-test -e MYSQL_ROOT_PASSWORD=test mysql:8.4
until docker exec restore-test mysqladmin ping -uroot -ptest --silent 2>/dev/null; do sleep 2; done
docker exec restore-test mysql -uroot -ptest -e "CREATE DATABASE app"
gunzip -c "$latest" | docker exec -i restore-test mysql -uroot -ptest app
# Spot-check a table you know should have data
docker exec restore-test mysql -uroot -ptest app -e "SELECT COUNT(*) FROM users"
docker stop restore-test
rm -rf /tmp/restore-testPostgres:
sudo rclone copy r2:db-backups/blog /tmp/restore-test --max-age 2d
latest=$(ls -t /tmp/restore-test/*.dump | head -n 1)
# Use your production's major version (or newer): older pg_restore can't read newer dumps.
docker run -d --rm --name restore-test -e POSTGRES_PASSWORD=test postgres:17
until docker exec restore-test pg_isready -U postgres >/dev/null 2>&1; do sleep 2; done
docker exec -i restore-test pg_restore -U postgres -d postgres --no-owner < "$latest"
docker exec restore-test psql -U postgres -c "SELECT COUNT(*) FROM users"
docker stop restore-test
rm -rf /tmp/restore-testIf the row count looks right, your backups are real. Put a reminder in your calendar to repeat this every few months — the maintenance checklist already has a quarterly slot for it.
Restoring production is the same commands, pointed at the real container. Stop whatever writes to the database first, so nothing lands mid-restore:
cd /home/deploy/laravel-app
docker compose stop app queue scheduler
gunzip -c /var/backups/db/laravel-app/laravel-app-2026-11-09-0230.sql.gz \
| docker compose exec -T mysql sh -c 'MYSQL_PWD="$MYSQL_ROOT_PASSWORD" exec mysql -u root "$MYSQL_DATABASE"'
docker compose start app queue schedulerThe newest dump is usually still on local disk (KEEP_LOCAL_DAYS), so you skip the download. If the server itself is gone, pull it from R2 onto the new one with rclone copy.
-T on docker compose exec. Without it, Docker allocates a TTY, which rewrites line endings in the output. The dump looks fine and restores badly.pipefail or it didn't happen. A failed mysqldump piped into gzip reports success without it.Dump completed footer (MySQL) and pg_restore --list (Postgres) catch truncated files before they get uploaded.no_check_bucket = true, or rclone tries to create the bucket and fails with a 403.--single-transaction keeps MySQL online, but the dump still reads every row. If it takes long enough to matter, schedule it outside your busy hours.The script itself is small. What makes it a backup system rather than a cron job is everything around the dump: pipefail and a completion check so a broken dump never gets uploaded, an off-server copy in R2 with automatic pruning, a ping that tells you when backups stop, and a restore you've actually run.
Set it up once per database, test the restore, and the next time a disk dies or a volume gets pruned, it's a ten-minute inconvenience instead of a very bad week.