rsync is a fast, versatile file synchronisation tool that efficiently copies only changed files. Combined with cron, it provides automated, incremental backups. This guide sets up automated local and remote backups on Ubuntu 24.04 LTS.

Tested and valid on:

  • Ubuntu 24.04 LTS

Prerequisites

  • Ubuntu 24.04 LTS server
  • SSH access to a remote backup server (optional)
  • A user with sudo privileges

Step 1 – Install rsync

rsync is pre-installed on Ubuntu 24.04. Verify:

rsync --version

Step 2 – Basic rsync Usage

Sync a local directory:

rsync -avz /var/www/html/ /backup/html/

Sync to a remote server over SSH:

rsync -avz -e ssh /var/www/html/ user@backup_server:/backup/html/

Step 3 – Create a Backup Script

Create the backup script:

sudo nano /usr/local/bin/backup.sh

Add:

#!/bin/bash
DATE=$(date +%Y-%m-%d)
SRC=/var/www/html
DST=/backup/html
LOG=/var/log/backup.log

echo "[$DATE] Starting backup" >> $LOG
rsync -avz --delete $SRC/ $DST/ >> $LOG 2>&1
echo "[$DATE] Backup complete" >> $LOG

Make it executable:

sudo chmod +x /usr/local/bin/backup.sh

Step 4 – Set Up SSH Keys for Remote Backup

Generate a dedicated backup SSH key (no passphrase):

ssh-keygen -t ed25519 -f ~/.ssh/backup_key -N ''

Copy to the remote server:

ssh-copy-id -i ~/.ssh/backup_key.pub user@backup_server

Step 5 – Update Script for Remote Backup

Update the backup script to use the key:

rsync -avz --delete -e 'ssh -i /root/.ssh/backup_key' $SRC/ user@backup_server:$DST/

Step 6 – Schedule with Cron

Add a cron job to run daily at 2 AM:

echo '0 2 * * * root /usr/local/bin/backup.sh' | sudo tee /etc/cron.d/daily-backup

Step 7 – Rotate Old Backups

Add cleanup to the script to keep only the last 30 days:

find /backup/ -name '*.tar.gz' -mtime +30 -delete

Conclusion

Automated backups with rsync and cron are now running on Ubuntu 24.04 LTS. Test your restores regularly — a backup you have never restored is not a backup you can trust.