Rsync Backups for WordPress

This is for any CMS, but I needed to add an automatic backup when I migrated a site to WordPress. Most folks use a plugin, but I’m old-school and like to use cron. You need to know some Unix to implement this.

The backup system has (at least) two parts: the cron job on the server to dump the database, and a cron job on my desktop PC to download the files.

Server Side

On the server side, I have a cron job that runs every midnight to dump the database.

0 0 * * * /usr/local/bin/backup_databases

Just to make things easy, I backup to a directory alongside the websites.

#! /bin/bash
# this file is /usr/local/bin/backup_databases

PW=***password***

mkdir -p /www/backups

# list all the databases in ths for loop
for i in example_com example_org ; do
	mysqldump -u root -p$PW $i > /www/backups/$i.mysql
	if [[ -e /www/backups/$i.mysql.gz ]] ; then 
		rm /www/backups/$i.mysql.gz
	fi
	gzip /www/backups/$i.mysql
done

Every night, a new database dump is created, and gzipped up.

On the Backup System

I just backup to my desktop at the moment. Eventually, I’ll have a second backup on a Raspberry Pi based NAS.

My backup disk is at /mnt/backups. In there I have a directory, bin/, where my backup scripts are kept.

I have SSH keys set to allow me to connect to the server with a private key. This way, I won’t be prompted for a password.

Then, I construct an rsync command that will download both the backups and the website files. (You need to backup the uploads as well.) This gets saved into a backup script. It’s a short, five line script.

#! /bin/sh
alias RSYNC="rsync -t -rv --delete --exclude '.private' --bwlimit=3m "
mkdir -p /mnt/backups/example
cd /mnt/backups/example
RSYNC 138.197.123.123:/www/ /mnt/backups/example

Once that’s running, I copy it over to the NAS to run via cron on there.

I use the –bwlimit settings to prevent the backups from consuming too much of the internet link. The first backup will take a long time, but subsequent downloads will complete in much less time.

These backups are incomplete because they don’t create an archive. So, if I run the backup on a cron job, and my site gets hacked, I won’t have an old copy of the site to restore. Creating backup sets and archives is a bit more complex, but, for now, I’m making them by hand.

Leave a Reply