Jun 18, 2008

HOWTO: Scheduled Remote MySQL Backups

Author: gaweee | Filed under: development, howto

If you have more access to more than 1 server, a good idea would be to schedule remote backups using a small script and crontab. This way, if 1 server goes down at least SOME data still resides on another. (a friend’s hosting service got prematurely terminted recently because someone else sharing a hosting plan was serving illegal content and the whole system was confiscated by the police in that country!)

of course backing up mysql is the only thing you can do, unless you’ve way too much disk space and way too much bandwidth… in that case please consult a professional on the actual 1001 ways to throw money at redundancy.

The script will first run remote commands on the target server over ssh to dump and gzip the database into a file. The file is then downloaded to the backup server. A final ssh command removes the dump file from the target server. Viola! And here is the shell script…

ssh root@wits.sg 'mysqldump -uroot twits> /tmp/twits.backup.sql && bzip2 -9 /tmp/twits.backup.sql'
scp root@wits.sg:/tmp/twits.backup.sql.bz2 /var/backups/twits/`date "+%Y%m%d-%H%M"`.sql.bz2
ssh root@wits.sg 'rm /tmp/twits.backup.sql.bz2'

Save this few lines to a file on the backup server and give it execute permissions! (I saved it at /root/twits_backup.sh)
Note: Passwordless logins between the 2 servers must have been setup prior to running this script. Otherwise scp and ssh commands will both be prompted for a password.

Next set up the cron job on the backup server to run the script

30 05 * * * /root/twits_backup.sh

This sets the script to run at 5:30am everyday.
Here is a good place to read up more on cron jobs.


Leave a Reply