Set up lsyncd to synchronize files between two or more servers

This post is more than a year old and may be obsolete. It was published October 6, 2021.

lsyncd runs a daemon to watch your filesystem for changes, and when a change occurs, copy files to another location. This can be a different location on the same server or an entirely different location. I used it to sync a Wordpress installation from one server to another behind a load balancer, so uploading files or upgrading plugins on the primary server would immediately synchronize the changes to a secondary server.

Setup lsyncd

1sudo apt update && sudo apt install lsyncd -y
2sudo mkdir /etc/lsyncd /var/log/lsyncd
3sudo nano /etc/lsyncd/lsyncd.conf.lua

Adapt the following config:

1settings {
2 logfile = "/var/log/lsyncd/lsyncd.log",
3 statusFile = "/var/log/lsyncd/lsyncd.status"
4}
5
6sync {
7 default.rsyncssh,
8 source = "/home/forge/blog.domain.com",
9 host = "[email protected]",
10 targetdir = "/home/forge/blog.domain.com"
11}

Note that host can include a username. targetdir is the remote path on server2.

Configure remote access from server1 -> server2

lsyncd will run as root and so you need to configure key authentication so it can connect from server1 -> server2.

Generate a key file (if necessary) on server1

1sudo su
2ssh-keygen -t ed25519 -C "[email protected]"
3Copy that file to server2:

ssh-copy-id [server name or ip]

1You can also do this manually by editing `~root/.ssh/authorized_keys` on server2.
2
3Test the connection and save server2 to the list of known hosts:

sudo su ssh [server name or ip] The authenticity of host '1.2.3.4 (1.2.3.4)' can't be established. ECDSA key fingerprint is SHA256:yEwriym08cConPhwNetT0Qg+h1aUKu2L/SL3Sl9F2Bs. Are you sure you want to continue connecting (yes/no/[fingerprint])? yes Warning: Permanently added '1.2.3.4' (ECDSA) to the list of known hosts.

1
2## Start it up
3Reload the service to pick up your new config and try copying files.
4```bash
5sudo service lsyncd restart
6tail -f /var/log/lsyncd/lsyncd.log

This blog is an experiment: less about education and more about documenting the oddities I've experienced while building web apps.

My hope is that you're here because of a random search and you're experiencing something I've had to deal with.

Popular Posts

Recent Posts

View all