How to sync data between 2 servers automatically

Have you ever wanted to know how to easily synchronize the data between multiple servers automatically?
In this article I’ll explain how to setup 2 Linux servers to automatically synchronize data between a specific directory on each server. To do this we will use rsync, ssh key authentication, and a cron job.

Let’s call the 2 servers ‘SOURCESERVER’ and ‘DESTSERVER’ for
SOURCESERVER = Source server (the server we’re connecting from to upload the data)
DESTSERVER = Destination server (the server we’re connecting to receive the data)


Part 1 - Setting up SSH key authentication

First, we need to make sure the DESTSERVER has the ability to use key authentication enabled. Find your sshd configuration file (usually ‘/etc/ssh/sshd_config’) and enable the following options if they are not already set.

RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys

If you edit the file be sure to restart sshd afterwards.

# /etc/init.d/sshd restart

Next, on the SOURCESERVER we will create the public / private key pair to be used for authentication with the following command.

# ssh-keygen -t rsa

*Note: Do not enter a passphrase for this, just hit enter when prompted.

This should create 2 files, a public key file and a private key file.
The public key file (usually [homedir]/.ssh/id_rsa.pub) we will upload to the DESTSERVER.
The private key file (usually [homedir]/.ssh/id_rsa) we will keep on the SOURCESERVER.
*Be sure to keep this private key safe. With it anyone will be able to connect to the DESTSERVER that contains the public key.

Now we will plant the public key we created on to the DESTSERVER.
Choose the user account which you will use to connect to on DESTSERVER, we’ll call this user ‘destuser’ for now.
In that account’s home directory, create a ‘.ssh’ subdirectory, and in that directory create a new text file called ‘authorized_keys’. If it already exists, great, use the existing file.
Open the ‘authorized_keys’ file and paste in the contents of the public key you created in the previous step (id_rsa.pub). It should look something like the following

ssh-rsa <lots and lots of characters…> sourceuser@SOURCESERVER

Save the file and change the permissions to 600 for the file and 700 for the ‘.ssh’ directory.

Now to test that the keys are working.
From the SOURCESERVER try logging in as normal using ssh to the DESTSERVER.

# ssh destuser@DESTSERVER

If all is working you should not be prompted for a password but instead connected directly to a shell on the DESTSERVER.


Part 2 - Creating the rsync script

Now for the rsync script.
I use a simple script such as the following

——————————————-

#!/bin/bash

SOURCEPATH=’/source/directory’
DESTPATH=’/destination’
DESTHOST=’123.123.123.123′
DESTUSER=’destuser’
LOGFILE=’rsync.log’

echo $’\n\n’ >> $LOGFILE
rsync -av –rsh=ssh $SOURCEPATH $DESTUSER@$DESTHOST:$DESTPATH 2>&1 >> $LOGFILE
echo “Completed at: `/bin/date`” >> $LOGFILE

——————————————-

Copy this file into the home directory of the sourceuser on the SOURCESERVER
and modify the first 4 variables in the file.
SOURCEPATH (Source path to be synced)
DESTPATH (Destination path to be synced)
DESTHOST (Destination IP address or host name)
DESTUSER (User on the destination server)
Save it as something like ‘rsync.sh’
Set the permissions on the file to 700.
# chmod 700 rsync.sh

Now you should be able to run the script, have it connect to the DESTSERVER, and transfer the files all without your interaction.
The script will send all output to the ‘rsync.log’ file specified in the script.


Part 3 - Setting up the cron job

Assuming everything has worked so far all that’s left is to setup a cron job to run the script automatically at a predefined interval.

As the same sourceuser use the ‘crontab’ command to create a new cron job.

# crontab -e

This will open an editor where you can schedule the job.
Enter the following to have the script run once every hour

——————————————-
# Run my rsync script once every hour
0 * * * * /path/to/rsync.sh
——————————————-

Your 2 servers should now be syncing the chosen directory once every hour.
Hope this helped, let me know if you have any questions.

-------------------------

Related Posts in Computer / Servers

11 Responses to “How to sync data between 2 servers automatically”

  1. The Toober Says:

    This looks handy, I’ll try it.

  2. Pankaj Says:

    cool… i was looking for something like this

  3. Sergej Says:

    Thank you for your great article. Plain simple, just what i needed.

  4. Raam Says:

    thx for this was very helpful and crafty

  5. Raam Says:

    also added a LIST variable so it would handle multiple dirs and list in the log dirs and time of completion

    for LIST in “`cat list.txt`”;
    do
    SOURCEPATH=”/$LIST”
    DESTPATH=”/$LIST”
    DESTHOST=”111.111.111.111″
    LOGFILE=”rsync.log”

    echo $’\n\n’ >> $LOGFILE
    rsync -av –rsh=”ssh -i .ssh/id_rsa” $SOURCEPATH $DESTHOST:$DESTPATH 2>&1 >> $LOGFILE
    echo “$LIST Completed at: `/bin/date`” >> $LOGFILE;
    done

  6. Pablo’s Blog»Archivo del blog » Sincronizar Datos entre 2 servidores Linux Says:

    […] El siguiente artículo explica como configurar 2 servidores Linux para que automáticamente sincronicen datos de un directorio a otro. Para realizar esto se usó rsync, atentificación con clave ssh y cron. […]

  7. Very good SME Server Howto guides Says:

    […] Sync data between 2 or more linux servers […]

  8. Rijas Says:

    Actually it is one way synchronization, i.e, If we are keeping multiple servers in an load balanced environment this technique wont work properly.

    If any one knows two way synchronization in load balanced environment please inform me.

  9. tahir Says:

    i have two linux server at my home trying to use given script but is not working please help me.

  10. Alexander Driantsov Says:

    2Rijas:
    You should look at NAS or FUSE+SSHFS to mount webroot of one server to another that is not exactly synchronization but will solve your issue. Of course this solution suits if problem lies not in harddrive capacity.

    2tahir:
    The script is example, if you experiencing problems implementing this synchronization I would better recommend you to read documentation on how does rsync works to understand what is going wrong.

  11. Eric Greer Says:

    Great Guide!!
    Thank you!!

Leave a Reply


Copyright 2007 HowtoMonster.com
Freelance Server Administration | The Musicians Network | www.techshoot.net | Social Network User Search