How to use Rsync for file synchronization between servers

Rsync is a very handy tool for local and remote file synchronization. It syncs your files by utilizing an algorithm that transfers only the modified parts of a file and minimizes the data transferred. In this article we will show you a few examples on how to use Rsync and enjoy it’s powerful features.

Prerequisites

Rsync is typically included in most Linux distributions by default.

SSH connection between the two parties in the transfer.

Examples

Rsync offers a plenty of option, but for a simple synchronization we’ll start just a few most commonly used.

The most common use case is syncing files between two servers. To do this you can simply use:

rsync -avz root@source.server.ip.address:/var/www/* /var/www/

With this command you will synchronize the ‘/var/www’ folder from the source (first parameter) to local  ‘/var/www’ folder.

Rsync will recuresevly copy all files and if you use the command later again, the second time it will transfer only the changes if there are any.

 

The options “-avz” are the most frequently used basic options.

  • ‘-a’ is for archive, meaning Rsync will preserve file permissions, ownership, symlinks  and so on
  • ‘-z’ is for using compression, and is a nice recommendation for transfers between remote servers, to save network traffic
  • ‘-v’ is simply verbose output so Rsync will disply all transferred files

SSH with keypair

If you are using SSH keypairs authentication on your servers, this is an example how to specify the private key to be used for the SSH connection:

rsync -e “ssh -i ~/private_key.pem” root@source.server.ip.address:/var/www/* /var/www/

Syncing local folders

Of course you can use Rsync to synchronize local folder on the same server as well. Simply point the path of the source and the destination directory:

rsync -av /var/tmp_www/* /var/www/

Rsync will only copy files that don’t exist or have been changed. As the transfer is now local, there is no need to waste CPU in compression so we skip the ‘-z’ option for this one.

 

Rsync is a powerful tool and offers many other options like listing files to be skipped in a transfer, restoring a tranfer after interruption, deleting files in source and more and more.

We’ll keep sharing knowledge on Rsync and use cases, so you can keep an eye on the Rsync tag in CloudBalkan blog.

Leave a Reply

Your email address will not be published. Required fields are marked *