Top.Mail.Ru
30% off VPS 7 d 08:41:03 Grab it

Rsync over SSH: Sync and Back Up Files

5
Rsync over SSH: Sync and Back Up Files

Rsync copies only the changes: not the whole file, just the blocks that differ from the previous version. In practice, the first sync of 10 GB takes as long as it takes to transfer 10 GB, and the next one takes seconds if little has changed. Rsync also works over SSH with no extra setup: if you have SSH access to a server, rsync is ready to use.

Basic syntax

Copy files from the local machine to a remote server:

rsync -av /local/path/ user@server:/remote/path/

Copy from a remote server to the local machine:

rsync -av user@server:/remote/path/ /local/path/

The -av flags are used almost always: -a preserves permissions, timestamps and symbolic links, and walks directories recursively. -v shows what is being copied. This pair is a sensible minimum for most tasks.

The main trap: the trailing slash

Whether the source path ends with a slash or not changes how rsync behaves completely. It is the most common cause of an “unexpected” result.

Without a slash, rsync copies the directory itself:

rsync -av /data/files /backup/
# Result: /backup/files/

With a slash, rsync copies the contents of the directory:

rsync -av /data/files/ /backup/
# Result: /backup/file1, /backup/file2...

A simple rule: a slash at the end of the source means “take what is inside”. No slash means “take the folder itself”. The destination path behaves predictably either way: rsync creates it if it does not exist.

Checking before you run

Before the first run with unfamiliar flags, especially --delete, always do a trial run:

rsync -av --dry-run /data/ user@server:/backup/

The --dry-run flag (or -n for short) shows what rsync would do without actually doing it. You see the list of files that would be copied or deleted. Once you are sure it is right, run it again without --dry-run.

SSH keys for automation

When rsync runs interactively, it asks for a password over SSH, and that is fine. But if you need to run rsync from cron or a script, there is nobody to type the password.

The solution is an SSH key without a passphrase, made specially for backups:

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

The -N "" flag creates the key with no passphrase. Copy the public part of the key to the remote server:

ssh-copy-id -i ~/.ssh/backup_key user@remote-server

Now rsync connects without a password if you name the key explicitly:

rsync -av -e "ssh -i ~/.ssh/backup_key" /data/ user@server:/backup/

This is safer than keeping a password in environment variables or a config: a key without a passphrase is used for a single purpose, and you can revoke it at any time through ~/.ssh/authorized_keys on the server.

A non-standard SSH port

If SSH on the remote server does not use the standard port 22, give the port through the -e flag:

rsync -av -e "ssh -p 2222" /data/ user@server:/backup/

A common mistake is to use the -p flag directly in rsync. But -p in rsync means something else entirely: preserve permissions (it is part of -a). For an SSH port, always use -e "ssh -p PORT".

Sync with deletion: the –delete flag

By default rsync only adds and updates files in the destination. If a file was deleted at the source, it stays in the destination. To make the destination an exact mirror of the source, you need the --delete flag:

rsync -av --delete /data/ user@server:/backup/

Be careful: --delete removes files in the destination that are not in the source. Without a --dry-run first, this can cause unwanted losses. Take extra care if the destination holds data from several sources.

Excluding files and directories

To skip temporary files, cache or logs:

rsync -av --exclude="*.log" --exclude="cache/" --exclude=".git" \
  /var/www/ user@server:/backup/www/

Exclusions apply to paths relative to the source. If you need to exclude a lot, it is easier to move the list into a file:

echo "*.log" >> ~/.rsync-exclude
echo "cache/" >> ~/.rsync-exclude
echo ".git" >> ~/.rsync-exclude

rsync -av --exclude-from="$HOME/.rsync-exclude" /var/www/ user@server:/backup/www/

Limiting speed

If you need to avoid saturating the link when syncing large amounts of data:

rsync -av --bwlimit=5120 /data/ user@server:/backup/

The value is in KB/s: 5120 = 5 MB/s, 10240 = 10 MB/s. It is useful when syncing during working hours, when the link is needed for other tasks.

Incremental backups with version history

A plain sync keeps only the current copy: if a file changed or was deleted, the old version is lost. The --link-dest flag solves this neatly: it creates hard links to unchanged files instead of copying them.

DATE=$(date +%Y-%m-%d)
DEST="/backup/snapshots"
LATEST="$DEST/latest"

rsync -av --link-dest="$LATEST" /var/www/ "$DEST/$DATE/"
ln -sfn "$DEST/$DATE" "$LATEST"

Each run creates a dated directory that looks like a full copy of the site but takes up disk space only for the changed files. Unchanged files are just links to the previous version. To roll back to any day, simply open the directory for that day.

Automating with cron

An example cron job: sync every night at 3:00 with logging:

crontab -e
0 3 * * * rsync -av --delete -e "ssh -i /home/user/.ssh/backup_key" \
  /var/www/ backup@backup-server:/backups/www/ \
  >> /var/log/rsync-backup.log 2>&1

2>&1 redirects both stdout and stderr to the log, so if something goes wrong, the error ends up in the file instead of getting lost.

Frequently asked questions

Do I need to install rsync on both servers?

Yes, rsync must be installed on both the source and the destination. Install it with one command: sudo apt install rsync on Ubuntu/Debian or sudo dnf install rsync on CentOS/AlmaLinux.

Why does rsync copy files that have not changed?

By default rsync compares files by size and modification time. If the time changed (for example after touch, or a copy that did not keep attributes), rsync considers the file changed. The --checksum flag makes rsync compare by checksum, which is slower but more exact.

Can I use rsync to back up a database?

Rsync copies files, and the database files may be in an inconsistent state while the DBMS is running. For MySQL and PostgreSQL it is better to make a dump (mysqldump, pg_dump) and then rsync the dump file. Or use a filesystem snapshot before running rsync.

How do I check that the sync succeeded?

Rsync returns exit code 0 on success and non-zero on error. In scripts: if rsync -av ... ; then echo "OK"; else echo "FAILED"; fi. Also look at the last lines of the output: rsync always prints a summary with the number of files transferred and the amount of data.

How is rsync different from scp?

scp copies the whole file on every run. Rsync transfers only the changes, which is much faster on repeated copies. Rsync can also sync directories, exclude files, delete extras in the destination and make incremental backups. scp is handy for a one-off transfer of a single file, rsync for regular syncing.

Rsync over SSH is the standard way to move data between VPS servers. At UFO.Hosting every server is reachable over SSH from the moment it is created, so rsync works right away with no extra setup.

Related

All articles
Стеклянное хранилище в форме облака с папками и файлами, тарелка лучом открывает замок

Nextcloud on a VPS: your own cloud with Docker Compose

Nextcloud is a cloud you own: files synced to your phone and computer, a calendar, contacts, and share-by-link. On a VPS you run it with Docker Compose as five containers: Nextcloud itself, a PostgreSQL database, a Redis cache, a container…

Server rack with two monitors and two users: two administrators working on one Windows server

RDP for two users on Windows Server 2016-2025: setup guide

By default, Windows Server 2016, 2019, 2022 and 2025 let two administrators connect over RDP at the same time, and you don’t need to buy Remote Desktop licenses for it. Below: how this works, how resources are shared, and a…