How to automate database backups with cron
Updated 7/20/2026
A backup you have to remember to run is not a backup. With cron, your database saves itself every night. Here is how.
1. The backup script
Create /usr/local/bin/backup-db.sh. Example for MySQL, deleting archives older than 14 days automatically:
#!/bin/bash
DEST=/var/backups/mysql
mkdir -p "$DEST"
STAMP=$(date +%F)
mysqldump -u root -pPASSWORD app_db | gzip > "$DEST/app_db-$STAMP.sql.gz"
find "$DEST" -name '*.sql.gz' -mtime +14 -delete
For PostgreSQL, replace the dump line with:
pg_dump -U postgres app_db | gzip > "$DEST/app_db-$STAMP.sql.gz"
2. Make it executable
chmod +x /usr/local/bin/backup-db.sh
3. Schedule it with cron
Run crontab -e and add a line for every night at 3:00:
0 3 * * * /usr/local/bin/backup-db.sh
4. Send the backup off the server
A backup on the same server does not save you if the server fails. Copy the archives to a Backup Box, mounted as an extra disk via SSHFS or SMB. Add to the end of the script:
rsync -a "$DEST/" /mnt/backup/mysql/
Verify the restore
An untested backup does not count. See the MySQL and PostgreSQL guides for the restore steps.
Put this guide into practice on your own VPS
EU cloud servers, billed hourly, ready in minutes, with one-click installs for dozens of apps.
See pricingRelated tutorials
How to secure MongoDB with authentication
By default, MongoDB runs without a password. Here is how to enable authentication and create an admin user.
Updated 7/20/2026DatabasesHow to migrate a database between servers
Move a MySQL or PostgreSQL database to a new server with minimal downtime, using dump and restore.
Updated 7/20/2026DatabasesHow to connect an app to a remote database
Allow access to a database from another server, securely: bind address, dedicated user and firewall.
Updated 7/20/2026