Backup Your WordPress Website

There are two things you need to have backed up when you want to restore your website.

  1. MYSQL tables
  2. WordPress installation files. Typically found at “/var/www/<site domain name>”

Backup Mysql Tables to a File

Backing up mysql database to a file is very simple using mysqldump. You need to have the proper access permissions to execute these commands.

mysqldump -u <wordpress username> -p <wordpress database name> > wp_bp.sql

For example:

mysqldump -u wordpressuser -p wordpress > wp_bp.sql

If you get an error message, this means your user does not have the necessary privileges over the database to perform this operation. In this case you can revert to mysql root user.

mysqldump: Error: 'Access denied; you need (at least one of) the PROCESS privilege(s) for this operation' when trying to dump tablespaces

Backing up with the root user is done with the same command.

For example:

mysqldump -u root -p wordpress > wp_bp.sql

Backup WordPress Files

Much in the same way we want to store all related data in a file. We will use the famous archiving tool tar since we want to preserve the users and groups associated with these files.

tar -czvf backup.tar.gz /var/www/<domain name>

Automate Backups With Crontab

Let’s now create a bash script that will backup the website once a day.

First we will create a bash script to automate the above tasks.

You may copy the following code and change the values of the variables.

#!/bin/bash

# Edit the following variables for your site
MYSQL_USER=root
MYSQL_PASSWORD=TOP_SECRET
MYSQL_DATABASE=wordpress
SITE_PATH=/var/www/cooldomainname.com

# no need to edit this
TIMESTAMP=$(date '+%H_%M_%S-%d_%m_%Y')
BACKUPPATH=/home/$USER/wp_backups/backup_${TIMESTAMP}
mkdir -p $BACKUPPATH && cd $BACKUPPATH

mysqldump -u $MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DATABASE > wp_bp.sql
tar -czf wp_site.tar.gz $SITE_PATH

#this will delete folders older than 30 days
find /home/$USER/wp_backups/* -type d -ctime +30 -exec rm -rf {} \;

And now for the Crontab part. Run the command to open the crontab file

crontab -e

We need to add a command that will cause the script to run every day at a certain hour.

0 0 * * * /home/$USER/scripts/wp_backup.sh

This line means that script at /home/$USER/scripts/wp_backup.sh will run every day at 00:00 for the rest of time.

Leave a Comment