Backup Your VPS with Cron and Rsync (with logging)

I realized recently that I needed to have some kind of backup for my VPS (virtual private server, i.e., a hosting service), and I had a Raspberry Pi 4 sitting at home doing nothing, so why not use my Pi and rsync?

Overview of Steps

  1. Install sshd on the VPS
  2. Setup SSH Keys
  3. Test the ssh login
  4. Install rsync on the VPS
  5. Create and Test the Script
  6. Add to crontab

Step 1: Install SSH on your server / VPS

There's a bunch of tutorials out there to do this, so I won't repeat here. See here

Step 2: Setup SSH Keys

Again, here's another tutorial to avoid using passwords. This is important so that your cron job can run automatically without input Setting Up SSH Keys

Step 3: Test SSH Login

If you run

$ ssh <user>@<yourserver>

You should be automatically logged into your system without the need for a password

Step 4: Installing rsync (if not already present)

Setting up rsync

Step 5: Create and Test the Script

Using rsync

rsync -aAX --delete --log-file=/home/pi/rsync.log <user>@<server>:/remote/path/to/backup/ /local/path/on/pi/

NOTE: before you blindly use this script, note that the “—delete” option is there. What this will do is remove files from the backup if they're deleted from the source (rsync keeps all files by default). If you're not careful it'll delete files you may want to keep. I suggest adding the “-n” option to do a dry-run and check the output

NOTE 2: the “—log-file=/home/pi/rsync.log” will log all output to the file specified when cron runs it (below)

Step 5a: Create Script

$ touch ~/.local/bin/backup.sh
$ chmod +x ~/.local/bin/backup.sh
$ vim ~/.local/bin/backup.sh

And drop this in there:

#!/bin/bash
rsync -aAX --delete --log-file=/home/pi/rsync.log <user>@<server>:/remote/path/to/backup/ /local/path/on/pi/

Step 6: add to user's crontab

$ crontab -e

and add this line (if you want it to run a 0200, daily) 0 02 * * * /home/pi/.local/bin/backup.sh

The End

That's it. If you followed along, you should be backing up your VPS files to your Raspberry Pi (or other machine) at 0200 daily, with logs going to rsync.log in the home directory.