Sometimes, taking a few minutes to do a simple thing will save you a headache down the road.  Like changing the oil in your car, or brushing your teeth every night, or automatically backing up your databases.

The development server that I mess around on has recently accumulated a lot of data that I really don't want to lose, so I whipped up a small script that will help to ensure this never happens.

#!/bin/bash
rm -f /path/to/backups/tmp/*
mysqldump --opt --host=localhost --user=USERNAME --password=PASSWORD --all-databases > /path/to/backups/tmp/dbBackup.sql
tar -czvf /path/to/backups/database/mysql.`date '+%Y%m%d%H%M%S'`.tar.gz /backups/tmp
service httpd restart

Line by line, what's happening here is:

  • delete the .sql file generated by the previous backup
  • dump every MySQL table to a file called dbBackup.sql.  You don't have to go this far; check out MySQL's documentation on mysqldump for all the options
  • tar up the dbBackup.sql file, include a timestamp in the filename
  • restart Apache

I want this script to run every night at 1am, so I added it to the crontab:

0 1 * * * /path/to/backup.daily.cron

Obviously this is a very simple script that can grow in complexity fairly quickly. For example, you can clear out old logs (a must for some Rails apps), and do other housekeeping functions. A good idea would also be to have a syncing program grab that .tar and upload it to your home machine, or even an S3 bucket.

When your MySQL instance gets corrupted or otherwise obliterated, you'll thank yourself for taking 5 minutes to set this up.

Related posts:

  1. mysqldump usage
  2. Backing Up Subversion Repositories Using svnadmin hotcopy
  3. Ruby On Rails and SliceHost Part 1: Initial Setup
  4. Setup Python 2.6.4, mod_wsgi 2.6, and Django 1.1.1 on CentOS 5.3 (cPanel)
  5. PHP Dynamic JavaScript SCRIPT Insertion for Embedding