Automatically back up your website to Dropbox

I host most of my personal projects on DigitalOcean, but sadly, their backup option only creates a backup each 7 days. This is enough for backing up the server setup, but it isn’t for websites that are worked on daily such as WordPress or Ghost blogs. You don’t ever want to loose 6 days of drafts or published content.

Since I still have lots of space on my Dropbox account I wanted to find out how hard it would be to back it up there. Well, apparently not that hard 🙂.

The first thing you need to do is get the cool Dropbox Uploader script created by Andrea Fabrizi:

sudo apt install gitgit clone https://github.com/andreafabrizi/Dropbox-Uploader.git

Next, update the permissions on the script:

cd ~/Dropbox-Uploader
sudo chmod +x dropbox_uploader.sh

And then run it for the first time:

./dropbox_uploader.sh

Follow the instructions to create an API key in your Dropbox account. For the permission type I chose “Access to a single folder created specifically for your app.“, which will create a App/my-app-name folder in your Dropbox account. This setting allows the script to access that folder alone.

Once you’ve pasted the API key, run the shell script once again, and try it out:

./dropbox_uploader.sh
touch test.txt
./dropbox_uploader.sh upload test.txt /

If all went well, you should now see the test.txt file appear in your App/my-app-name folder.

Next you’ll have to write a script that creates a full backup of your website. I created a shell script here: /home/my-user/crons/website-backup.sh.

TIMESTAMP=`date "+%Y%m%d-%H%M%S"`
DB_USER="db-user-name"
DB_PASSWORD="db-password"
DB_DATABASE="db-db-name"

# Create an SQL dump of my database
mysqldump -u${DB_USER} -p${DB_PASSWORD} ${DB_DATABASE} > ${TIMESTAMP}.sql

# Create a zip file of the website, and include the SQL dump
zip -r ~/crons/${TIMESTAMP}.zip /var/www/html ${TIMESTAMP}.sql

# Upload the zip file to Dropbox
~/Dropbox-Uploader/dropbox_uploader.sh upload ~/crons/${TIMESTAMP}.zip /

# Cleanup
rm ~/crons/${TIMESTAMP}.zip
rm ~/crons/${TIMESTAMP}.sql

Try out the script to see if the zip file is uploaded to your Dropbox account:

sh ~/crons/website-backup.sh

Now all that’s left is to create a cronjob, run:

crontab -e

And add the task:

0 2 * * * sh ~/crons/website-backup.sh

If you’re not too familiar with cronjobs: this will execute the script every day at 2 a.m.

That’s it! Of course, in most cases you don’t want to make a complete backup of your DocumentRoot. E.g. for Ghost you’ll only need to zip the /var/www/ghost/content directory, for WordPress that’ll be /var/www/html/wp-content.