How to Set Up Automated Database Backups (Step-by-Step Guide)

We earn commissions when you shop through the links below.

Knowing how to set up automated database backups is one of those things every developer intends to do — and too often skips until something breaks. A single corrupted table, a botched migration, or a rogue DELETE query can wipe out weeks of data in seconds. Backups are your insurance policy, and automating them removes the human error from the equation entirely.

In this guide I’ll walk you through a production-ready setup using shell scripts, cron jobs, and cloud object storage. I’ll cover PostgreSQL and MySQL, but the patterns apply broadly.

Why Automated Backups Matter

Manual backups fail because humans forget. Even disciplined teams skip them during crunch time. Automation guarantees consistency — same schedule, same retention policy, every single day — without anyone having to remember.

Beyond the obvious disaster recovery angle, automated backups also let you:

  • Roll back bad deployments quickly
  • Restore a staging environment from production data
  • Meet compliance requirements (GDPR, HIPAA, SOC 2)
  • Debug data issues by comparing historical snapshots

What You’ll Need

  • A Linux server running your database (Ubuntu 22.04+ works fine)
  • Access to a cloud storage bucket (S3, Spaces, R2, etc.)
  • The aws CLI or s3cmd installed
  • Basic cron knowledge

I run most of my infrastructure on DigitalOcean — their Managed Databases come with automated backups built in, but I still layer my own scripts on top for more granular control and off-platform storage.

Step 1: Write a Backup Script

Start with a simple shell script that dumps your database and compresses it. Here’s a production-ready example for PostgreSQL:

#!/bin/bash

# config
DB_NAME="myapp_production"
DB_USER="postgres"
BACKUP_DIR="/var/backups/postgres"
S3_BUCKET="s3://my-backup-bucket/postgres"
DATE=$(date +"%Y-%m-%d_%H-%M-%S")
FILENAME="${DB_NAME}_${DATE}.sql.gz"
RETENTION_DAYS=30

# create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"

# dump and compress
pg_dump -U "$DB_USER" "$DB_NAME" | gzip > "${BACKUP_DIR}/${FILENAME}"

if [ $? -ne 0 ]; then
  echo "[ERROR] Database dump failed" >&2
  exit 1
fi

echo "[OK] Backup created: ${FILENAME}"

# upload to S3-compatible storage
aws s3 cp "${BACKUP_DIR}/${FILENAME}" "${S3_BUCKET}/${FILENAME}" \
  --storage-class STANDARD_IA

if [ $? -ne 0 ]; then
  echo "[ERROR] S3 upload failed" >&2
  exit 1
fi

echo "[OK] Uploaded to ${S3_BUCKET}"

# delete local backups older than retention period
find "$BACKUP_DIR" -name "*.sql.gz" -mtime +"$RETENTION_DAYS" -delete

echo "[OK] Cleanup complete"

For MySQL, replace the dump command with:

mysqldump -u "$DB_USER" -p"$DB_PASS" "$DB_NAME" | gzip > "${BACKUP_DIR}/${FILENAME}"

Save this file as /usr/local/bin/db_backup.sh and make it executable:

chmod +x /usr/local/bin/db_backup.sh

Step 2: Secure Your Credentials

Never hardcode passwords in scripts. For PostgreSQL, use a .pgpass file:

# ~/.pgpass
# hostname:port:database:username:password
localhost:5432:myapp_production:postgres:supersecretpassword
chmod 600 ~/.pgpass

For MySQL, use a credentials file:

# ~/.my.cnf
[mysqldump]
user=myuser
password=supersecretpassword
chmod 600 ~/.my.cnf

For AWS credentials, configure them via aws configure or use an IAM instance role if you’re on EC2 or a managed cloud host — no credentials stored in plain text at all.

Step 3: Schedule with Cron

Now automate it. Open your crontab:

crontab -e

Add a line to run the backup daily at 2 AM:

# Run database backup every day at 2:00 AM
0 2 * * * /usr/local/bin/db_backup.sh >> /var/log/db_backup.log 2>&1

The redirect appends both stdout and stderr to a log file — essential for debugging failures. If you want to be notified on failure, pipe the output to a notification service or add a curl call to a Slack webhook at the end of the script.

Step 4: Verify Your Backups Actually Work

This is the step most people skip. A backup that can’t be restored is worthless. After your first automated run, test it:

# Download the backup
aws s3 cp s3://my-backup-bucket/postgres/myapp_production_2026-01-15_02-00-00.sql.gz /tmp/

# Restore to a test database
gunzip -c /tmp/myapp_production_2026-01-15_02-00-00.sql.gz | psql -U postgres myapp_test

Schedule a monthly restore test on a staging server. I know it sounds tedious, but discovering your backup format is broken during an actual incident is a genuinely awful experience.

Step 5: Set Up Backup Retention and Lifecycle Rules

Keeping every backup forever is expensive. Use S3 lifecycle rules to automatically expire old backups. In your AWS console or via CLI:

aws s3api put-bucket-lifecycle-configuration \
  --bucket my-backup-bucket \
  --lifecycle-configuration '{
    "Rules": [{
      "ID": "DeleteOldBackups",
      "Status": "Enabled",
      "Filter": {"Prefix": "postgres/"},
      "Expiration": {"Days": 90}
    }]
  }'

A common retention strategy: daily backups for 30 days, weekly backups for 6 months, monthly backups for a year. You can implement tiered retention in your shell script by naming files with prefixes and running different lifecycle rules per prefix.

Going Further: Managed Database Platforms

If you’re running a newer project and don’t want to manage this infrastructure yourself, platforms like Railway handle automated backups out of the box for PostgreSQL databases — no scripting required. It’s worth the trade-off for smaller projects or solo developers who’d rather ship features than manage ops.

For teams who want to build more complex automation workflows around backups — like triggering restore tests, sending alerts, or syncing backups across multiple environments — Make can orchestrate these workflows visually without writing glue code.

Checklist: Before You Call It Done

  • ✅ Script runs without errors manually
  • ✅ Credentials are stored securely, not hardcoded
  • ✅ Cron job is scheduled and logged
  • ✅ Backups are uploading to off-server storage
  • ✅ You’ve done at least one restore test
  • ✅ Lifecycle/expiry rules are configured
  • ✅ You’ll receive alerts if the backup job fails

Final Thoughts

Understanding how to set up automated database backups is non-negotiable for anyone running production software. The whole process — script, cron, cloud storage, retention — takes about an hour to implement properly. That hour will be the best time you’ve ever invested in your infrastructure.

The key mindset shift: a backup strategy isn’t complete until you’ve proven you can restore from it. Everything else is just creating files you hope you’ll never need.