Automating Backups with Rsync and Cron

This guide explains how to automate backups on your Debian server using rsync and cron. In this example, we will be backing up the static website set up in the Deploying a Static Website with Nginx guide.

Step-by-Step Guide

  1. Step 1: Install Rsync

    First, install rsync on your Debian server by running the following commands:

    sudo apt update
    sudo apt install rsync
  2. Step 2: Create a Backup Directory

    Create a directory where backups will be stored:

    mkdir -p /path/to/backup-directory
  3. Step 3: Rsync Command Setup

    Use rsync to copy the static website files from /var/www/html/ to the backup directory:

    rsync -avz /var/www/html/ /path/to/backup-directory/
  4. Step 4: Set Up SSH for Remote Backups (Optional)

    If you want to back up to a remote server, set up an SSH key for passwordless login:

    ssh-keygen -t rsa -b 4096 -f ~/.ssh/backup_key
    ssh-copy-id -i ~/.ssh/backup_key.pub user@remote-server

    Then, use rsync over SSH to copy files to the remote backup server:

    rsync -avz -e "ssh -i /path/to/backup_key" /var/www/html/ user@backup-server:/path/to/backup-directory/
  5. Step 5: Automate with Cron

    To schedule regular backups, open the cron configuration:

    crontab -e

    Add the following line to run the backup every day at midnight:

    0 0 * * * rsync -avz /var/www/html/ /path/to/backup-directory/
  6. Step 6: Testing the Backup

    Test the rsync command to ensure the backup runs correctly.

  7. Step 7: Restoring from Backup

    To restore the files from the backup directory to /var/www/html/, use the following command:

    rsync -avz /path/to/backup-directory/ /var/www/html/