mysqldump on a schedule: cron on the server or backups to your Mac
The most common way to automate MySQL backups is a mysqldump script in cron. It works until it breaks, and it usually breaks silently.
A typical script
#!/bin/bash
set -euo pipefail
d=$(date +%F)
mysqldump --single-transaction --routines --triggers --events shop \
| gzip > /var/backups/shop-$d.sql.gz
find /var/backups -name 'shop-*.sql.gz' -mtime +14 -delete
And a line in crontab -e to run it every night at 3:00 AM:
0 3 * * * /usr/local/bin/backup-shop.sh
Where these scripts let you down
- A failure mid-pipeline goes unnoticed. Without
set -o pipefailthe script takes the exit code ofgzip, notmysqldump. The dump failed, the script thinks all is well. - Rotation ignores the result.
find … -deleteremoves old copies even if the new ones have come out empty for two weeks. - Copies live on the same server. A dead disk, a hacked server or an unpaid hosting bill, and the backups go with the site.
- Nobody hears about failures. cron mails its output to a local mailbox no one reads. You find out when you need the copy.
- Disk space. Copies eat the server's disk, and one day they take the database down with them.
Keeping copies on your own machine
You can pull copies to your own computer: dump over SSH straight into a file on the Mac, as in "Back up MySQL over SSH to your Mac". Instead of cron, the Mac has launchd, which can do something cron can't: if the Mac was asleep at 3:00 AM, a StartCalendarInterval job runs when it wakes up.
Verification, rotation, retries and notifications are still yours to write.
A good backup checklist
- The copy isn't kept on the same server.
- Every file is verified: the archive reads, the dump has its last line.
- Old copies are deleted only after a good new one.
- A failed run is retried, and a failure sends you a message.
- There's one more copy in the cloud.
- You've restored a database from a copy at least once (how to test a backup).