TeknoTUT

How to Automate Linux Backups with rsync and Cron

A complete guide to automated Linux server backups with rsync and cron: push data over SSH, keep space-saving daily snapshots, and restore.

Written by 17 min readBahasa Indonesia
Illustration of two servers copying data to each other on a schedule
On This Page

If you manage a Linux server, you're probably familiar with this particular worry: what if the data on that server disappears one day? The cause could be anything, from a failed disk, a mistyped rm -rf, or a botched update, to a VPS that suddenly gets deleted by its provider.

The trouble is that manual backups almost always end the same way. You're diligent in the first week, you start forgetting in the second, and when you really need it, the latest backup turns out to be three months old. A good backup is one that runs by itself without anyone having to remember it.

The good news is that you don't need complicated software for that. With two tools available on nearly every Linux distro, rsync to copy the data and cron to schedule it, you can build a reliable backup system.

In this article, we'll cover how to automate Linux backups with rsync and cron, from the basic rsync commands, sending backups to another server over SSH, and creating space-saving daily snapshots, to scheduling them with cron and restoring your data. Let's get started!

What is rsync?

rsync (remote sync) is a program for copying and synchronizing files, either between folders on one machine or between machines over a network. It was created by Andrew Tridgell and Paul Mackerras in 1996, and it's still a favorite among server administrators today.

What makes rsync special is how it works. Unlike cp or scp, which always copy every file from scratch, rsync only sends files that have changed. Even for a large file with a small change, rsync sends only the parts that differ.

Imagine you have a 20 GB website folder. The first backup does copy all of it. On the next backup, however, if only 50 MB has changed, only those 50 MB are sent. As a result, a daily backup finishes in seconds or minutes, not hours.

cron, meanwhile, is the built-in Linux task scheduler. Its job is simple: run a given command at a time you specify, for example every day at 02:30.

Why Back Up with rsync and Cron?

There are plenty of backup applications out there, but the rsync and cron combination remains popular for several reasons:

  • Available everywhere: rsync and cron are in every distro's repository, and they're often installed out of the box.
  • Saves bandwidth and time: only changes are sent, which suits a VPS with a limited network quota.
  • Secure: data travels over an encrypted SSH connection.
  • Backups are plain files: there's no special format. You can open the backup folder and grab a single file at any time without extra software.
  • Flexible: it's easy to combine with scripts, for example to create daily snapshots as we'll do later.

To keep things balanced, here are the limitations:

  • No encryption at rest: files on the backup server are stored as they are. If you need encrypted backups, consider tools such as restic or BorgBackup.
  • Not suitable for live database files: copying the data folder of a running MySQL or PostgreSQL server directly can produce a corrupt backup (see the tips section below).
  • No built-in notifications: if a backup fails, you have to check the log yourself.

Remember the 3-2-1 rule: keep at least 3 copies of your data, on 2 different media, with 1 copy in another location. A backup that lives on the same server as the original data won't help when the server itself is gone.

Preparation

Before starting, make sure you have:

  • A source server: the server whose data you want to back up, for example the VPS that runs your website.
  • A backup server: a second server to store the backups. It can be another VPS, a computer at home, or a Raspberry Pi with an external hard drive.
  • SSH access to both servers with a user that has sudo. If your server is brand new, follow the guide on how to secure a Linux VPS first.

The commands in this article are intended for Ubuntu 24.04 LTS and 26.04 LTS. At the time of writing, Ubuntu 24.04 ships rsync 3.2.7 and Ubuntu 26.04 ships version 3.4.1. Other distros are generally the same, apart from the package installation command.

The examples in this article use the following values. Replace them with your own.

Item Example value
User on the source server budi
Folder to back up /var/www/
Backup server IP 203.0.113.20
User on the backup server backupuser
Backup storage folder /home/backupuser/web01

How to Automate Backups with rsync and Cron

Step #1: Install rsync and Cron

rsync must be installed on both servers, because rsync on the source server talks to rsync on the backup server. Run the following commands on the source server:

sudo apt update
sudo apt install rsync cron -y

Then on the backup server, installing rsync alone is enough:

sudo apt install rsync -y

Check the installed rsync version with the following command:

rsync --version

The first line of the output looks roughly like this:

rsync  version 3.2.7  protocol version 31

The versions on the two servers don't have to match, because rsync automatically negotiates the protocol down to the older version.

Step #2: Understand the Basic rsync Command

Before sending data to another server, it's a good idea to try rsync locally first. The general form of the command is:

rsync [options] SOURCE DESTINATION

Create a test folder with a few files using the following commands:

mkdir -p ~/coba/asal/css
echo "Halo" > ~/coba/asal/index.html
echo "body {}" > ~/coba/asal/css/style.css

Now run rsync with the --dry-run option. With this option, rsync only shows what it would do without actually copying anything:

rsync -avh --dry-run ~/coba/asal/ ~/coba/salinan/

The output looks roughly like this:

sending incremental file list
created directory /home/budi/coba/salinan
./
index.html
css/
css/style.css
 
sent 143 bytes  received 71 bytes  428.00 bytes/sec
total size is 13  speedup is 0.06 (DRY RUN)

If the file list matches what you expect, run it again without --dry-run to actually copy the files:

rsync -avh ~/coba/asal/ ~/coba/salinan/

Try running the same command a second time. This time no files appear in the list, because nothing has changed. That is the essence of rsync.

Here are the rsync options most commonly used for backups:

Option Purpose
-a Archive mode: copies folders with their contents and preserves permissions, ownership, modification times, and symlinks
-v Shows the names of the files being processed
-h Shows sizes in human-readable units (K, M, G)
-z Compresses data in transit, useful on slow connections
-n or --dry-run Simulation, nothing is changed
--delete Deletes files at the destination that no longer exist at the source
--exclude Skips certain files or folders
-e Sets the SSH command to use, for example to pick an SSH key
--link-dest Creates hard links to the previous backup for unchanged files

Watch the trailing slash on the source! ~/coba/asal/ (with /) means "copy the contents of the asal folder", while ~/coba/asal (without /) means "copy the asal folder itself", so a salinan/asal/ folder appears at the destination. This small detail is the most common source of confusion for new rsync users.

One more thing to be careful with is the --delete option. It makes the destination an exact mirror of the source, which includes deleting files at the destination. If you swap the source and destination, you can lose data. Make it a habit to try with --dry-run first whenever you use --delete.

Step #3: Prepare the User and Folder on the Backup Server

Backups should be received by a dedicated user without sudo access, so that if the source server is compromised, the attacker doesn't automatically take over the backup server.

Log in to the backup server, then create a new user with the following command:

sudo adduser backupuser

Why not simply name it backup? Because Debian and Ubuntu already have a system user called backup, so that name is no longer available.

Next, create a folder to store the backups, along with the .ssh folder that will hold the public key later:

sudo -u backupuser mkdir -p /home/backupuser/web01 /home/backupuser/.ssh
sudo chmod 700 /home/backupuser/.ssh

The name web01 is just a label for the source server. That way, one backup server can hold backups from several servers, each in its own folder.

Step #4: Create a Dedicated SSH Key for Backups

Cron runs commands with nobody at the keyboard, so there's no one to type a password or passphrase. That's why we need an SSH key without a passphrase that is used only for backups.

On the source server, create a new SSH key with the following command:

ssh-keygen -t ed25519 -f ~/.ssh/id_backup -N "" -C "backup-web01"

The -f option sets the key file name, and -N "" leaves the passphrase empty. Display the public key with the following command:

cat ~/.ssh/id_backup.pub

Copy that single line of output (it starts with ssh-ed25519). Then on the backup server, paste it into the authorized_keys file that belongs to backupuser:

sudo -u backupuser nano /home/backupuser/.ssh/authorized_keys

Save the file by pressing CTRL+X, then Y, and Enter. After that, set the file permissions:

sudo chmod 600 /home/backupuser/.ssh/authorized_keys

Go back to the source server and test the connection:

ssh -i ~/.ssh/id_backup [email protected] "hostname"

On the first connection, you'll be asked whether you want to trust the server. Type yes, then press Enter. If the output shows the backup server's hostname without asking for a password, the SSH key is working.

Important: this test must be done manually once. If you skip it, cron will fail because nobody is there to answer that yes prompt.

Since this key isn't protected by a passphrase, treat the ~/.ssh/id_backup file like a password: don't copy it anywhere else, and don't use it for anything other than backups.

Step #5: Send the First Backup to the Backup Server

Now it's time to send the data. As usual, we start with a simulation. Run the following command on the source server:

rsync -avh --dry-run -e "ssh -i ~/.ssh/id_backup" /var/www/ [email protected]:/home/backupuser/web01/percobaan/

The destination format is user@host:/path. Check the list of files shown. If it looks right, run it without --dry-run:

rsync -avh -e "ssh -i ~/.ssh/id_backup" /var/www/ [email protected]:/home/backupuser/web01/percobaan/

At the end of the output, rsync prints a summary that looks roughly like this:

sent 1.25G bytes  received 48.31K bytes  10.42M bytes/sec
total size is 1.25G  speedup is 1.00

Run the same command once more and notice that it finishes much faster, because no files need to be sent again.

If there are folders that don't need to be backed up, such as a cache folder or node_modules that can be regenerated, add the --exclude option:

rsync -avh --exclude 'node_modules/' --exclude '.cache/' -e "ssh -i ~/.ssh/id_backup" /var/www/ [email protected]:/home/backupuser/web01/percobaan/

Once you're confident everything works, delete that test folder from the backup server:

ssh -i ~/.ssh/id_backup [email protected] "rm -rf /home/backupuser/web01/percobaan"

Step #6: Create a Backup Script with Daily Snapshots

A backup that is just a single mirror copy has a major weakness. If a file gets corrupted or deleted today without you noticing, tonight that damage is copied over and replaces the copy that was still good.

The solution is to keep several snapshots, one folder for each day. This is where the --link-dest option comes in. With it, files that haven't changed since the previous snapshot aren't copied again. Instead they get a hard link, which is a second name for the same data on disk.

As a result, every snapshot folder looks like a complete copy, but the disk space used is only as large as the files that changed. Neat, right?

On the source server, create the script file with the following command:

nano ~/backup-web.sh

Fill it with the following script:

#!/usr/bin/env bash
set -euo pipefail
 
# ---- Settings ----
SOURCE="/var/www/"
DEST_HOST="[email protected]"
DEST_DIR="/home/backupuser/web01"
SSH_KEY="$HOME/.ssh/id_backup"
KEEP=7   # number of snapshots to keep
 
# ---- Process ----
TODAY="$(date +%F)"
SSH_CMD="ssh -i $SSH_KEY -o BatchMode=yes"
 
echo "[$(date '+%F %T')] Starting backup of $SOURCE to $DEST_HOST:$DEST_DIR/$TODAY"
 
# Copy the data. Unchanged files are hard-linked from the latest snapshot.
rsync -a --delete \
  --exclude 'node_modules/' \
  -e "$SSH_CMD" \
  --link-dest="../latest" \
  "$SOURCE" "$DEST_HOST:$DEST_DIR/$TODAY/"
 
# Point "latest" to the snapshot that just finished.
$SSH_CMD "$DEST_HOST" "ln -sfn $TODAY $DEST_DIR/latest"
 
# Delete old snapshots, keeping the newest $KEEP.
$SSH_CMD "$DEST_HOST" "ls -1d $DEST_DIR/20*/ | head -n -$KEEP | xargs -r rm -rf"
 
echo "[$(date '+%F %T')] Backup finished"

Save the file, then make it executable:

chmod +x ~/backup-web.sh

A short explanation of the important parts:

  • set -euo pipefail: the script stops immediately if any command fails. That way, the latest marker never moves to a snapshot that failed halfway.
  • TODAY: today's date in the 2026-11-23 format, used as the snapshot folder name.
  • -o BatchMode=yes: SSH will never wait for password input. If something is wrong with the key, the command fails right away instead of hanging.
  • --link-dest="../latest": this path is relative to the destination folder, so it points to web01/latest, a symlink to the last successful snapshot.
  • ln -sfn: updates the latest symlink after rsync finishes without errors.
  • head -n -$KEEP: takes every snapshot folder except the newest 7, then deletes them. Because the folder names are dates, their alphabetical order matches their chronological order.

Note: on the very first run, rsync prints the warning --link-dest arg does not exist: ../latest. This is expected because there is no previous snapshot yet, and the backup still runs as a full copy.

Run the script manually to test it:

~/backup-web.sh

Then check the result on the backup server with the following command:

ssh -i ~/.ssh/id_backup [email protected] "ls -l /home/backupuser/web01"

The output looks roughly like this:

total 4
drwxr-xr-x 5 backupuser backupuser 4096 Nov 23 09:12 2026-11-23
lrwxrwxrwx 1 backupuser backupuser   10 Nov 23 10:41 latest -> 2026-11-23

If the folder with today's date and the latest symlink are there, the script is working correctly.

About file ownership: because the backup is received by backupuser, which isn't root, every file on the backup server will be owned by backupuser. File permissions and modification times are still preserved. For website files this usually isn't a problem, since ownership can be reset with chown after a restore.

Step #7: Schedule the Backup with Cron

The script is ready, so now we hand it over to cron to run every day. Open your user's crontab with the following command:

crontab -e

If this is your first time, you'll be asked to choose an editor. Pick nano to keep it easy. Then add the following line at the very bottom:

30 2 * * * flock -n /home/budi/.backup-web.lock /home/budi/backup-web.sh >> /home/budi/backup-web.log 2>&1

Save and exit the editor. Let's break that line down:

  • 30 2 * * *: the schedule, which is every day at 02:30.
  • flock -n …lock: prevents two backup processes from running at the same time. If yesterday's backup hasn't finished (for example because of a slow network), the new one is cancelled right away instead of colliding with it.
  • >> …backup-web.log 2>&1: all output and error messages are appended to the log file.

The five schedule fields in cron mean the following:

┌───────── minute (0–59)
│ ┌─────── hour (0–23)
│ │ ┌───── day of month (1–31)
│ │ │ ┌─── month (1–12)
│ │ │ │ ┌─ day of week (0–7, 0 and 7 = Sunday)
│ │ │ │ │
30 2 * * *

A few other commonly used schedules:

Schedule Meaning
30 2 * * * Every day at 02:30
0 */6 * * * Every 6 hours
0 3 * * 0 Every Sunday at 03:00
15 1 1 * * On the 1st of every month at 01:15

Note: with the script above, snapshots are named by date, so a backup that runs several times a day updates the same folder. If you want hourly snapshots, change the TODAY line to TODAY="$(date +%F_%H%M)".

Cron uses the system time zone. Check your server's time zone with the following command, so the backup doesn't run during busy hours:

timedatectl

To confirm the schedule is saved, print the crontab:

crontab -l

The next day, check whether cron really ran the script with the following command:

sudo journalctl -u cron --since today | grep backup-web

The output looks roughly like this:

Nov 24 02:30:01 web01 CRON[48211]: (budi) CMD (flock -n /home/budi/.backup-web.lock /home/budi/backup-web.sh >> /home/budi/backup-web.log 2>&1)

Then look at the backup result in the log file:

tail -n 20 ~/backup-web.log

If the last line says Backup finished, your automated backup is up and running. Done!

Alternative: besides cron, you can also use a systemd timer to schedule the script. You can read the basics of writing systemd units in the article on how to create a systemd service on Linux.

Step #8: Test Restoring Your Data

A backup that has never been restored can't really be called a backup yet. So take the time to test recovery, at least once after everything is set up.

A restore is basically rsync with the direction reversed. To fetch a single file from the latest snapshot, run the following command on the source server:

rsync -avh -e "ssh -i ~/.ssh/id_backup" [email protected]:/home/backupuser/web01/latest/index.html ~/restore/

To fetch the entire contents of a snapshot from a specific date into a temporary folder:

rsync -avh -e "ssh -i ~/.ssh/id_backup" [email protected]:/home/backupuser/web01/2026-11-23/ ~/restore/

Check the contents of ~/restore/, and make sure the files open and contain what you expect. Only after that should you copy them back to their original location.

Tip: when restoring, copy to a temporary folder first as in the examples above, rather than overwriting /var/www/ directly. That way you can compare the contents first and avoid overwriting files that are actually newer.

Tips for More Reliable Backups

Tip #1: Dump the Database Before the Backup

Don't copy the data folder of a running database directly (for example /var/lib/mysql), because its files can change in the middle of the copy. The right way is to create a dump into a file first, and let rsync back up that file.

For MySQL or MariaDB, for example, add a line like the following to the script before the rsync command:

mysqldump --single-transaction --all-databases | gzip > /var/www/backup-db/semua-database.sql.gz

For PostgreSQL, the equivalent tools are pg_dump or pg_dumpall. Make sure the dump folder isn't reachable from the web.

Tip #2: Check the Disk Space Used

To see how much space each snapshot really takes, run the following command on the backup server:

du -sh /home/backupuser/web01/20*

The output looks roughly like this:

1.3G	/home/backupuser/web01/2026-11-23
42M	/home/backupuser/web01/2026-11-24
18M	/home/backupuser/web01/2026-11-25

The first snapshot is full size, while the following ones are only as large as the files that changed. That's because du counts hard-linked files only once.

Tip #3: Back Up Files Owned by root

A regular user's crontab can only read files that user is allowed to read. If you need to back up a folder such as /etc, where some files are readable only by root, install the script in root's crontab with sudo crontab -e.

Keep in mind that in this case the SSH key and the known_hosts file being used belong to root. So repeat Step #4 as root, and adjust the paths in the script and in the crontab line.

Tip #4: Review the Log Regularly

Since rsync and cron don't send notifications, make a habit of checking ~/backup-web.log from time to time. Here are some common error messages and their causes:

Error message Common cause
Permission denied (publickey) The public key isn't installed on the backup server, or the SSH_KEY path is wrong
Host key verification failed The first manual connection (Step #4) hasn't been made by the user that runs cron
rsync: command not found rsync isn't installed on the backup server
No space left on device The backup server's disk is full, so lower KEEP or add capacity
Permission denied (13) on certain files The user running the script isn't allowed to read those files (see Tip #3)

Conclusion

From this article, we can conclude that automating backups on Linux doesn't require expensive or complicated software. With rsync sending only the changes, a dedicated SSH key for a secure connection, the --link-dest option for space-saving daily snapshots, and cron as the scheduler, you have a backup system that runs by itself every night.

Things to Remember

  • Always try --dry-run before running a new rsync command, especially when using --delete.
  • Mind the trailing slash on the source path.
  • Keep backups on a server or location different from the original data.
  • Test your restores regularly, and don't wait for a disaster to find out.

This solution suits backups of website files, configuration, and application data on one or several servers. If your needs grow, for example you need encryption at rest or backups to object storage, you can look at tools such as restic or BorgBackup. The core concepts remain the same as what you've learned here.


I hope this article helps.

Continue Reading

More articles you might enjoy.