Replication is the high availability in MongoDB. Basically, this solution is use to replicate data to multiple servers (nodes) so if one server is down then system still can work by responding reads from clients.

Architecture

Rep-Architecture

In this example, I installed 3 servers as above. They are MongoDB standalone instance. Now we will set up to combine all of them into Replicat solution of MongoDB.

Click here to see how to install MongoDB.

Modify hosts file to enter IP of other machines

On machine 192.168.137.55

sudo bash

Step 1: Edit hosts file

nano /etc/hosts

192.168.137.55 mongodb0.com

192.168.137.36 mongodb1.com

192.168.137.37 mongodb2.com

Ctrl+X -> Y -> Ctrl+A+M

Step 2: Edit hostname file. Just alias IP Address such friendly name

nano /etc/hostname

mongodb0.com

Step 3: Edit mongod file

nano /etc/mongod.conf

Enter name of replication set

replSet=rs0

Repeate step 1 to step 3 for other machines but please notice that Step 2 is different

192.168.137.36 => should be mongodb1.com

192.168.137.37 => should be mongodb2.com

Check communication across servers

On master mongodb connect to mongodb1 and mongodb1 machines

Step 1: Connect to mongodb0 (192.168.137.55)

mongo –port 27017 –host 192.168.137.55

Step 2 : Connect to mongodb1 (192.168.137.36)

Mongo –port 27017 –host 192.168.137.36

 

Step 2 : Connect to mongodb2 (192.168.137.37)

Mongo –port 27017 –host 192.168.137.37

Make sure that all connections are done.

Set up Replication

Restart service mongod

By default, I choose mongodb0.com as primary server. Restart mongodb on mongodb0.com.

sudo service mongod restart

Connect to mongodb

mongo –port 27017 –host mongodb0.com

Start the replication

Rs.initiate()

This will initiate the replication set and add the current server connected currently to as the first member of the set.

rs.conf()

 

Add new members to the repl

rs.add(“mongodb1.com”)

rs.add(“mongodb2.com”)

If connect successfully, then we can check status of replicat set.

rs.status()

Replication solution is now available.

 

Advertisements

One thought on “How to set up Replication in MongoDB

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s