Database backups are the most neglected task on a self-managed VPS — until the moment a disk fails, a botched migration corrupts data, or a DROP TABLE runs on production. On a Hong Kong VPS, the responsibility for database backup falls entirely on you: there is no managed backup service running in the background unless you configure one.
This guide covers automated backup scripts for both MySQL and PostgreSQL, offsite storage to S3-compatible buckets (including Cloudflare R2 and MinIO), backup encryption, and — critically — restore testing procedures that verify your backups actually work.
Backup Strategy: The 3-2-1 Rule
Follow the industry-standard 3-2-1 backup rule:
- 3 copies of your data
- 2 different storage media
- 1 offsite copy
For a VPS deployment, this means: the live database (1) + daily dump on the same VPS (2) + encrypted copy in cloud object storage (3, offsite). The third copy in a different geographic location protects against data centre-level failures.
MySQL Automated Backups
Basic Backup Script
cat > /opt/backups/mysql-backup.sh << 'SCRIPT' #!/bin/bash set -euo pipefail BACKUP_DIR="/opt/backups/mysql" DATE=$(date +%Y%m%d_%H%M%S) RETENTION_DAYS=7 MYSQL_USER="root" MYSQL_PASS="YOUR_ROOT_PASSWORD" LOG="/var/log/mysql-backup.log" mkdir -p "$BACKUP_DIR" echo "[$(date)] Starting MySQL backup..." >> "$LOG"
# Get list of all databases (excluding system DBs)
DATABASES=$(mysql -u"$MYSQL_USER" -p"$MYSQL_PASS" -e "SHOW DATABASES;" 2>/dev/null \
| grep -Ev "^(Database|information_schema|performance_schema|mysql|sys)$")
for DB in $DATABASES; do
FILENAME="$BACKUP_DIR/${DB}_${DATE}.sql.gz"
mysqldump \
-u"$MYSQL_USER" -p"$MYSQL_PASS" \
--single-transaction \
--quick \
--lock-tables=false \
--routines \
--triggers \
--events \
"$DB" 2>>"$LOG" | gzip > "$FILENAME"
SIZE=$(du -sh "$FILENAME" | cut -f1)
echo "[$(date)] Backed up: $DB → $FILENAME ($SIZE)" >> "$LOG"
done
# Remove backups older than retention period
find "$BACKUP_DIR" -name "*.sql.gz" -mtime +"$RETENTION_DAYS" -delete
echo "[$(date)] MySQL backup complete. Old backups pruned (>${RETENTION_DAYS}d)." >> "$LOG"
SCRIPT
chmod +x /opt/backups/mysql-backup.sh
Secure Credentials with .my.cnf
Avoid passing passwords on the command line (visible in process list):
cat > /root/.my.cnf << 'EOF'
[client]
user=root
password=YOUR_ROOT_PASSWORD
EOF
chmod 600 /root/.my.cnf
Remove -u"$MYSQL_USER" -p"$MYSQL_PASS" from the script — MySQL reads credentials from .my.cnf automatically.
Full Backup with Binary Logs (Point-in-Time Recovery)
For production databases where you need point-in-time recovery (restore to any moment, not just daily snapshots), enable binary logging:
# In /etc/mysql/mysql.conf.d/mysqld.cnf:
server-id = 1
log_bin = /var/log/mysql/mysql-bin.log
binlog_format = ROW
expire_logs_days = 7
max_binlog_size = 100M
With binary logging enabled, a full daily dump plus the binary logs between dumps gives you complete point-in-time recovery capability.
PostgreSQL Automated Backups
Backup Script
cat > /opt/backups/postgres-backup.sh << 'SCRIPT' #!/bin/bash set -euo pipefail BACKUP_DIR="/opt/backups/postgres" DATE=$(date +%Y%m%d_%H%M%S) RETENTION_DAYS=7 LOG="/var/log/postgres-backup.log" PG_USER="postgres" mkdir -p "$BACKUP_DIR" echo "[$(date)] Starting PostgreSQL backup..." >> "$LOG"
# Backup each database individually
DATABASES=$(sudo -u "$PG_USER" psql -t -c "SELECT datname FROM pg_database WHERE datistemplate = false AND datname != 'postgres';" 2>/dev/null | tr -d ' ')
for DB in $DATABASES; do
FILENAME="$BACKUP_DIR/${DB}_${DATE}.dump"
sudo -u "$PG_USER" pg_dump \
--format=custom \
--compress=9 \
--verbose \
"$DB" > "$FILENAME" 2>>"$LOG"
SIZE=$(du -sh "$FILENAME" | cut -f1)
echo "[$(date)] Backed up: $DB → $FILENAME ($SIZE)" >> "$LOG"
done
# Also backup global objects (roles, tablespaces)
sudo -u "$PG_USER" pg_dumpall --globals-only | \
gzip > "$BACKUP_DIR/globals_${DATE}.sql.gz"
find "$BACKUP_DIR" -name "*.dump" -mtime +"$RETENTION_DAYS" -delete
find "$BACKUP_DIR" -name "*.sql.gz" -mtime +"$RETENTION_DAYS" -delete
echo "[$(date)] PostgreSQL backup complete." >> "$LOG"
SCRIPT
chmod +x /opt/backups/postgres-backup.sh
PostgreSQL Continuous Archiving (WAL)
For production PostgreSQL with point-in-time recovery requirements, enable WAL archiving:
# In postgresql.conf:
wal_level = replica
archive_mode = on
archive_command = 'cp %p /opt/backups/wal/%f'
archive_timeout = 300
WAL archives combined with a base backup enable restoration to any point in time — not just to the last daily dump boundary.
Offsite Backup to Cloudflare R2 (Zero Egress Cost)
Cloudflare R2 is S3-compatible with no egress fees — ideal for offsite backup from a Hong Kong VPS since uploads to R2 are free and downloads for restore are also free.
Install rclone
<code">curl https://rclone.org/install.sh | bash
Configure R2
rclone config
# Follow the prompts:
# n (new remote)
# Name: r2
# Storage: s3
# Provider: Cloudflare
# Access key: YOUR_R2_ACCESS_KEY
# Secret: YOUR_R2_SECRET_KEY
# Endpoint: https://YOUR_ACCOUNT_ID.r2.cloudflarestorage.com
# Leave other settings as default
Create Bucket and Test
<code"># Create backup bucket rclone mkdir r2:vps-backups # Test upload echo "test" | rclone rcat r2:vps-backups/test.txt rclone ls r2:vps-backups
Integrated Backup + Upload Script
cat > /opt/backups/full-backup.sh << 'SCRIPT' #!/bin/bash set -euo pipefail DATE=$(date +%Y%m%d_%H%M%S) LOCAL_DIR="/opt/backups" LOG="/var/log/full-backup.log" echo "[$(date)] === Full backup started ===" >> "$LOG"
# Run database backups
/opt/backups/mysql-backup.sh
/opt/backups/postgres-backup.sh
# Encrypt backup files before uploading
PASSPHRASE="YOUR_STRONG_ENCRYPTION_PASSPHRASE"
for FILE in $(find "$LOCAL_DIR" -name "*_${DATE}*" -type f); do
gpg --batch --yes --passphrase "$PASSPHRASE" \
--symmetric --cipher-algo AES256 \
-o "${FILE}.gpg" "$FILE"
# Upload encrypted file to R2
rclone copy "${FILE}.gpg" r2:vps-backups/
# Remove unencrypted copy after upload
rm "${FILE}"
echo "[$(date)] Uploaded: ${FILE}.gpg" >> "$LOG"
done
echo "[$(date)] === Full backup complete ===" >> "$LOG"
SCRIPT
chmod +x /opt/backups/full-backup.sh
Schedule Backups with Cron
crontab -e
# Add these lines:
# Daily full backup at 2:30am HKT
30 2 * * * /opt/backups/full-backup.sh >> /var/log/full-backup.log 2>&1
# Weekly backup verification (Sunday 4am)
0 4 * * 0 /opt/backups/test-restore.sh >> /var/log/restore-test.log 2>&1
Backup Monitoring and Alerting
Email Alert on Failure
<code">cat > /opt/backups/backup-with-alert.sh << 'SCRIPT'
#!/bin/bash
/opt/backups/full-backup.sh
EXIT_CODE=$?
if [ $EXIT_CODE -ne 0 ]; then
echo "BACKUP FAILED on $(hostname) at $(date). Exit code: $EXIT_CODE" | \
mail -s "ALERT: VPS Backup Failed" admin@yourdomain.com
fi
SCRIPT
Healthcheck.io / BetterUptime Heartbeat
Use a heartbeat service to alert you when backups stop running (not just when they fail):
<code"># Add to the end of your backup script (after successful completion): curl -fsS --retry 3 https://hc-ping.com/YOUR_HEALTHCHECK_UUID > /dev/null
If your backup script doesn’t ping the URL, Healthcheck.io sends you an email. This catches cron job failures, server downtime, and disk-full conditions that prevent backups silently.
Restore Procedures
Restore MySQL Database
# Decrypt backup
gpg --batch --passphrase "YOUR_PASSPHRASE" -d mydb_20260601_020000.sql.gz.gpg | \
gunzip > mydb_restore.sql
# Restore to existing database
mysql -u root mydb_target < mydb_restore.sql
# Or restore to a new database
mysql -u root -e "CREATE DATABASE mydb_restored CHARACTER SET utf8mb4;"
mysql -u root mydb_restored < mydb_restore.sql
Restore PostgreSQL Database
# Decrypt
gpg --batch --passphrase "YOUR_PASSPHRASE" -d mydb_20260601_020000.dump.gpg > mydb_restore.dump
# Restore (custom format — preserves indexes, constraints, etc.)
sudo -u postgres pg_restore \
--dbname=mydb_restored \
--verbose \
--clean \
--if-exists \
mydb_restore.dump
Step: Automated Restore Testing
A backup you have never tested is not a backup — it is a file of unknown value. Automate weekly restore verification:
<code">cat > /opt/backups/test-restore.sh << 'SCRIPT' #!/bin/bash LOG="/var/log/restore-test.log" DATE=$(date +%Y%m%d_%H%M%S) echo "[$(date)] Starting restore test..." >> "$LOG"
# Download most recent backup from R2
LATEST=$(rclone lsf r2:vps-backups/ --include "*.sql.gz.gpg" | sort | tail -1)
rclone copy "r2:vps-backups/$LATEST" /tmp/restore-test/
# Decrypt
gpg --batch --passphrase "YOUR_PASSPHRASE" \
-d "/tmp/restore-test/$LATEST" | gunzip > /tmp/restore-test/test_restore.sql
# Restore to a test database
mysql -u root -e "DROP DATABASE IF EXISTS restore_test; CREATE DATABASE restore_test;"
mysql -u root restore_test < /tmp/restore-test/test_restore.sql # Verify row count (adjust table name and expected count) ROW_COUNT=$(mysql -u root restore_test -se "SELECT COUNT(*) FROM users;" 2>/dev/null || echo "0")
if [ "$ROW_COUNT" -gt "0" ]; then
echo "[$(date)] Restore test PASSED. users table: $ROW_COUNT rows." >> "$LOG"
else
echo "[$(date)] Restore test FAILED. Zero rows found." >> "$LOG"
echo "Weekly restore test FAILED on $(hostname)" | \
mail -s "ALERT: Backup Restore Test Failed" admin@yourdomain.com
fi
# Cleanup
mysql -u root -e "DROP DATABASE IF EXISTS restore_test;"
rm -rf /tmp/restore-test/
SCRIPT
chmod +x /opt/backups/test-restore.sh
Backup Size and Retention Planning
| Database Size | Compressed Backup Size | 7-day retention (local) | Offsite (encrypted) |
|---|---|---|---|
| 1 GB | ~100–300 MB | ~2 GB | ~2 GB in R2 |
| 10 GB | ~1–3 GB | ~20 GB | ~20 GB in R2 |
| 100 GB | ~10–30 GB | ~200 GB | Consider incremental strategy |
For databases over 50 GB, consider switching from full daily dumps to incremental backups using binary log / WAL archiving between weekly full backups to manage storage costs.
Conclusion
Automated, tested, encrypted, offsite database backups are non-negotiable for any production database on a Hong Kong VPS. The scripts in this guide cover the full cycle: daily automated dumps, GPG encryption before upload, Cloudflare R2 offsite storage (zero egress cost), and weekly automated restore testing that verifies your backups are actually usable.
The restore test is the step most operators skip — and the only way to discover that your backup script has been silently failing, or that a schema change broke the restore procedure. Schedule it weekly and treat a failed restore test as urgently as a production outage.
Protect your data: Browse Server.HK Hong Kong VPS plans — all plans include NVMe SSD storage; offsite backup to R2 or S3 is your responsibility and is fully supported.