Ubuntu VPS – WordPress files and database automated backup | AWS S3

by | Oct 10, 2017 | Documentation, Hosting, Linux, WordPress

There are many ways to backup an Ubuntu installation. It’s important to plan and develop a backup plan consisting of what to back up, where to back it up to, and how to restore it.

An easy way to back up a Linux VPS system is using a shell script. For example, a script can be used to configure which directories to back up, and pass those directories as arguments to the tar utility, which creates an archive file. The archive file can then be moved or copied to another location. I am very pleased with the AWS S3 service, so I use it for all my storage needs so I modified the original shell script provided in the Ubuntu Documentation so I can upload my backup file to S3:

The Script:
#!/bin/bash
# Script by OrbitUX
# Variables
TODAY=`date '+%Y%m%d'`
TEMP_DIR=./temp
BACKUP_NAME="wpbackup"
DB_NAME="orbitux"
DB_USER="username"
DB_PASS="password"
DB_HOST="databasehost"
SITE_PATH=/var/www/html
S3_BUCKET=s3://mybackupdestination
#Run
echo "Starting Backup..."
mkdir $TEMP_DIR
mysqldump -u $DB_USER -p$DB_PASS -h $DB_HOST $DB_NAME > $TEMP_DIR/database.sql
tar --exclude="updraft" -zcf $TEMP_DIR/files.tar.gz $SITE_PATH
tar -zcf $BACKUP_NAME-$TODAY.tar.gz -C $TEMP_DIR .
#Upload to S3
s3cmd put $BACKUP_NAME-$TODAY.tar.gz $S3_BUCKET
echo "Backup Complete [$(du -sh $BACKUP_NAME-$TODAY.tar.gz | awk '{print $1}')]"
#clean up
rm $BACKUP_NAME-$TODAY.tar.gz
rm -Rf $TEMP_DIR

How to use it:

To upload or sync files and directories from Linux we use the s3cmd command, Initially, I had a problem uploading files to S3 because I was using an older version of s3cmd(version 1.6) provided by APT Python-Pip provides a newer version of s3cmd(version 2.0):

$sudo apt-get install python-pip build-essential python-dev lm-sensors
$sudo apt-get install python-pip build-essential python-dev lm-sensors
$sudo pip install psutil logutils bottle batinfo https://bitbucket.org/gleb_zhulik/py3sensors/get/tip.tar.gz zeroconf netifaces pymdstat influxdb elasticsearch potsdb statsd pystache docker-py pysnmp pika py-cpuinfo bernhard
$sudo pip install --upgrade pip
$sudo pip install s3cmd

Go ahead and create AWS IAM credentials and provide full access to AWS S3 buckets, then add them to s3cmd with the following command:

$sudo s3cmd --configure

Make a bucket:

$sudo s3cmd mb s3://mybackupdestination

create a file with the script above and save it as backup.sh then add execute permissions to the file:

$sudo vi backup.sh <--- Press i then paste the code, press :wq! to save and exit the file

Don forget to edit the parameters to match your WordPress files location and database connection parameters (stored in ../wp-config.php)

$sudo chmod +x backup.sh

Schedule it to run automatically every Sunday:

$sudo crontab -e
/
0 0 * * 0 /home/ubuntu/backup.sh

run the backup manually to see it work, then you can call it a day. 🙂

$sudo ./backup.sh