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.
First, install rsync on your Debian server by running the following commands:
sudo apt update
sudo apt install rsync
Create a directory where backups will be stored:
mkdir -p /path/to/backup-directory
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/
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/
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/
Test the rsync command to ensure the backup runs correctly.
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/