Backup your mysql blog with cron

codinghorror.com loses it's blog to a hosting failure

Everyone’s tweeting about codinghorror’s data loss today. I’m not sure exactly why their hosting provider lost their blog, but I’m prepared if mine ever does. In my case, it’s easy - I email myself a dump of the WordPress mysql database nightly.

$ crontab -l
0 7 * * *  /usr/bin/mysqldump -u root -psecret --all-databases |bzip2 > /tmp/dbbackup.sql.bz && (printf "\%b" "Subject: db backup for `date`\nTo: jonathan\n"; /usr/bin/uuencode /tmp/dbbackup.sql.bz all-databases.sql.bz) |/usr/sbin/ssmtp jonathan@example.com

That command runs once a night, dumping the structure and contents of my mysql database, compresses it, and formats the file as an email attachment and sends it to me using ssmtp. You can substitute sendmail, or your favorite MTA (Mail Transfer Agent).

Every morning, I hit “y” on that message in gmail, and that’s a fine tradeoff for sleeping soundly.

UPDATE: the same technique can be used to backup your entire www directory, saving images and site tweaks. This cron task runs once a week, emailing my my entire WordPress install for all sites hosted on this slice.

15 7 */7 * *  cd /var/www && tar zcf /tmp/www.tar.gz * && (printf "\%b" "Subject: www backup for `date`\nTo: jonathan\n"; /usr/bin/uuencode /tmp/www.tar.gz www.tar.gz) |/usr/sbin/ssmtp jonathan@example.com

As you can imagine, the files can be uploaded to another host via scp or sent to Amazon S3 instead of emailed.