Sync Two Cloud Servers Files

Sivakumar V

1 min read

Recently I have implemented two-way files synchronization between two Ubuntu Cloud servers using unison and inotifywait.
Thought I would share it here as a blog for future references.
Requirements:
1. Setup: Two Rackspace Cloud server running Ubuntu or your own VPS server.
2. Smile

Unison is a file-synchronization tool for Unix and Windows. It allows to replicate a collection of files and directories between two servers (or different disks on the same host), modified separately, and then brought up to date by propagating the changes in each replica to the other.
inotifywait is an Linux utility to notify file changes.
Now, lets use both of them
Install unison on both servers
[source language=””]
$ apt-get install unison openssh-server ssh
[/source]
Unison requires password less ssh-key authentication between servers. Lets set them.
Server1:
Generate public/private key on server1.
[source language=””]
$ ssh-keygen -t rsa
[/source]
Copy the ssh keys and paste it into server2 authorized_keys which would be typically located at ~/.ssh/authorized_keys. (if not create it)
To make sure SSH working with password try login to server2 from server 1, it should connect without asking password.
Server1:
[source language=””]
$ ssh root@server2_ip_address
[/source]
Install inotifywait on both servers
[source language=””]
$ sudo apt-get install inotify-tools
[/source]
Now unison and inotifywait are ready to use. Run the unison to listen for folder between two servers.
[source language=””]
$ unison /var/www/proj1/images ssh://192.168.0.5//var/www/proje1/images/
[/source]
Open server1 terminal and try to create some file inside /var/www/proj1/folder on server1. Unison will detect the file and prompt to user to enter.
To skip prompting use -batch option.
[source language=””]
$ unison -batch /var/www/proj1/images ssh://192.168.0.101//var/www/proje1/images/
[/source]
Once file synchronized with server2 unison will stop. To make unison to listen always for file changes create small shell script that you can run in background.
[source language=””]
$ nano sync_file.sh
#!/bin/bash
LOCATION=”/var/www/proj1/images/”
RSYNC_OPTIONS=…
while true
do
inotifywait -r $LOCATION
unison -batch $LOCATION ssh://///$LOCATION
done

[/source]
Run the shell script
[source language=””]
$ sh sync_file.sh
[/source]
Run the shell script in background(add & symbol at the end).
[source language=””]
$ nohup sh sync_file.sh &
[/source]
It should work fine if not please post your issue as a comment.

Related posts:

One Reply to “Sync Two Cloud Servers Files”

Leave a Reply

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