VPS

Automate VPS Backups with rsync and cron

Automate VPS Backups with rsync and cron

Table of Contents

  1. What is rsync and Why Use It
  2. Install rsync on Ubuntu/Debian
  3. Local Backup with rsync
  4. Remote Backup via SSH
  5. SSH Key Setup for Cron
  6. Writing a Complete Backup Script
  7. Scheduling with Cron
  8. Backup Rotation and Retention
  9. Verifying and Testing Backups
  10. FAQ

Backing up your VPS is essential, but manual backups are unreliable — you might forget or skip them when busy. This guide shows you how to use rsync with cron to create fully automated daily backups that run without any intervention.

1. What is rsync and Why Use It

rsync (Remote Sync) is a command-line tool built into Linux for synchronizing files locally and over SSH. Its key advantages for backup include:

rsync vs tar + scp: tar + scp copies everything every time. With 10GB of data, that takes a very long time. rsync only transfers what changed since the last run — daily backups finish in seconds to minutes.

2. Install rsync on Ubuntu/Debian

rsync is usually pre-installed. Check and install if needed:

# Check if rsync is installed
rsync --version

# Install on Ubuntu/Debian
sudo apt update && sudo apt install rsync -y

# Install on CentOS/AlmaLinux/Rocky Linux
sudo yum install rsync -y

3. Local Backup with rsync

Start with a local backup to understand rsync syntax before adding SSH complexity:

Basic Syntax

rsync [options] source/ destination/

Common Options

OptionMeaning
-aArchive mode — preserves permissions, owner, symlinks, timestamps
-vVerbose — shows file list being transferred
-zCompress data during transfer
--deleteDelete files at destination not in source
--excludeExclude files or directories matching pattern
--dry-runTest run without actual file transfer
-PShow progress bar

Local Backup Examples

# Backup /var/www to /backup/www
rsync -avz /var/www/ /backup/www/

# Backup excluding temp files and cache
rsync -avz --exclude='*.tmp' --exclude='cache/' /var/www/ /backup/www/

# Dry run to preview changes
rsync -avz --dry-run /var/www/ /backup/www/
Trailing Slash Matters: /var/www/ (with slash) = copy contents of the directory.
/var/www (without slash) = copy the directory itself. Results differ significantly.

4. Remote Backup via SSH

Backing up to a separate server is the most resilient approach — if your primary server fails, data survives elsewhere.

Remote Backup Syntax

# rsync over SSH to remote server
rsync -avz -e ssh /var/www/ user@remote-server:/backup/www/

# Specify non-standard SSH port
rsync -avz -e "ssh -p 2222" /var/www/ user@remote-server:/backup/www/

# Use specific SSH key file
rsync -avz -e "ssh -i /root/.ssh/backup_key" /var/www/ user@remote-server:/backup/www/

5. SSH Key Setup for Cron

Cron cannot interactively enter passwords — SSH key authentication is required.

# 1. Generate SSH key pair (no passphrase for cron use)
ssh-keygen -t ed25519 -f /root/.ssh/backup_key -N ""

# 2. Copy public key to remote server
ssh-copy-id -i /root/.ssh/backup_key.pub user@remote-server

# 3. Test passwordless connection
ssh -i /root/.ssh/backup_key user@remote-server "echo 'SSH key OK'"

6. Writing a Complete Backup Script

#!/bin/bash
# /root/scripts/backup.sh

BACKUP_SOURCE="/var/www /etc /home"
BACKUP_DEST="backup-user@backup-server:/backups/$(hostname)"
SSH_KEY="/root/.ssh/backup_key"
LOG_FILE="/var/log/backup.log"

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

log "=== Backup started ==="
ERRORS=0

for SRC in $BACKUP_SOURCE; do
    log "Backing up $SRC..."
    rsync -az \
        --delete \
        --exclude='*.tmp' \
        --exclude='cache/' \
        -e "ssh -i $SSH_KEY -o StrictHostKeyChecking=no" \
        "$SRC/" \
        "$BACKUP_DEST${SRC}/"

    if [ $? -eq 0 ]; then
        log "OK: $SRC"
    else
        log "ERROR: Failed $SRC"
        ERRORS=$((ERRORS + 1))
    fi
done

log "=== Backup finished (errors: $ERRORS) ==="
exit $ERRORS
chmod +x /root/scripts/backup.sh

7. Scheduling with Cron

# Open crontab
crontab -e

# Run backup daily at 2:00 AM
0 2 * * * /root/scripts/backup.sh >> /var/log/backup.log 2>&1

Cron Syntax Breakdown

FieldValueMeaning
Minute0At minute 0
Hour2At 2 AM
Day*Every day
Month*Every month
Weekday*Every weekday

8. Backup Rotation and Retention

#!/bin/bash
DATE=$(date +%Y-%m-%d)
BACKUP_BASE="/backup"
BACKUP_DIR="$BACKUP_BASE/$DATE"

mkdir -p "$BACKUP_DIR"
rsync -az /var/www/ "$BACKUP_DIR/www/"
rsync -az /etc/ "$BACKUP_DIR/etc/"

# Delete backups older than 30 days
find "$BACKUP_BASE" -maxdepth 1 -type d -mtime +30 -exec rm -rf {} \;

9. Verifying and Testing Backups

# Check today's log
tail -50 /var/log/backup.log

# Find errors
grep "ERROR" /var/log/backup.log | tail -20

# Test restore
rsync -avz backup-user@backup-server:/backups/hostname/var/www/index.html /tmp/test-restore/
diff /var/www/index.html /tmp/test-restore/index.html
3-2-1 Backup Rule: Keep 3 copies on 2 different media with 1 copy offsite. Combine local disk + remote VPS + cloud storage for maximum protection.

Frequently Asked Questions

What is rsync and why use it for VPS backups?
rsync is a Linux tool that syncs files incrementally — sending only changed parts. This saves bandwidth and time compared to copying everything each time, making it perfect for daily VPS backups.
What VPS specs do I need to run rsync backup?
rsync uses minimal CPU and RAM. Even the smallest VPS with 1 vCPU and 512MB RAM handles it fine. Just ensure sufficient storage space at the destination.
Where should I store my VPS backups?
Follow the 3-2-1 rule: 3 copies, 2 different media, 1 offsite. rsync to a separate remote server or cloud storage like S3 or Backblaze B2.
Will cron run backups even when no one is logged in?
Yes. The cron daemon runs continuously in the background regardless of active SSH sessions. Verify it's running with systemctl status cron.
How do I know if my backup succeeded?
Redirect rsync output to a log file and set up email alerts. Use mailutils or msmtp to send success/failure notifications from your cron job automatically.
Do I need SSH keys for rsync to a remote server in cron?
Yes. Cron cannot enter passwords interactively. Create an SSH key pair without a passphrase, copy the public key to the remote server, and reference the private key in your rsync command.
How is rsync different from tar + scp?
tar + scp copies everything every time (full backup). rsync only transfers changed blocks since the last run — daily backups finish in seconds instead of hours for large datasets.

Conclusion: Start Backing Up Your VPS Today

Automating VPS backups with rsync + cron is simple, reliable, and cost-effective. Summary:

  1. Install rsync and configure SSH keys
  2. Write a backup script with logging and error handling
  3. Schedule a cron job to run nightly
  4. Review logs weekly and test restores regularly

Looking for reliable VPS hosting? AsiaGB VPS offers Thailand and Singapore locations with SSD storage, 99% uptime, and expert support.