Backup WordPress Files and Database

I’ve been meaning to create a backup of my WordPress files and databases on my VPS (ChunkHost). After a minimal amount of digging (on WordPress’s Codex site), I wrote this script:

#!/bin/bash

WPBAK=/var/backups/wordpress
tar -cvJf $WPBAK/$(date +%F)_files.tar.xz /var/www || exit 1
mysqldump --all-databases --verbose | xz -c > $WPBAK/$(date +%F)_databases.sql.xz || exit 2

Just change the “$WPBAK” variable to where on the server you want to store the backups. Also, you’ll need to create the ~/.my.cnf file (I did it for the root user):

[mysqldump]
user=root
password=secret

You’ll need to change user to the appropriate MySQL user, and the password accordingly. Be sure to set .my.cnf to have the permissions 600 (“chmod 600 ~/.my.cnf”), that way the script doesn’t need to contain the MySQL user password in order to make the dump.

I put all of this in /etc/cron.daily/wordpress, and made it executable (“chmod +x /etc/cron.daily/wordpress”). This way my system will back up automatically on a daily basis.

The next step is to update my rsnapshot configuration so it will store the backup on my Network Attached Storage (NAS). First, I had to copy the SSH public key for my NAS admin user to my VPS, and add it to the user doing the work. Then, I added a single line (port number changed to protect the innocent):

backup  root@eldon.me:/var/backups/wordpress    eldon.me/       ssh_args=-p 4321

I’m waiting for another rsnapshot backup process to start naturally, rather than kicking off a manual run. I’m curious to see if this works as well as I thought.

The next step is to write a cron job that will remove old backups. This is simple enough (put in /etc/cron.daily/wordpress_backup-cleanup, and make executable, as above):

#!/bin/bash
find /var/backups/wordpress/ -mtime +7 -exec rm {} \;

This will delete backup files greater than seven days old. This will hopefully keep my li’l VPS’s disk from filling up. And that’s it!