Thursday 1 January 2015

Setup MongoDB ReplicaSet in Simple Steps


Why Replication?

  • To keep your data safe
  • High (24*7) availability of data
  • Disaster Recovery
  • No downtime for maintenance (like backups, index rebuilds, compaction)
  • Read scaling (extra copies to read from)
  • Replica set is transparent to the application




How replication works in MongoDB
MongoDB achieves replication by the use of replica set. A replica set is a group of mongod instances that host the same data set. In a replica one node is primary node that receives all write operations. All other instances, secondaries, apply operations from the primary so that they have the same data set. Replica set can have only one primary node.


  • Replica set is a group of two or more nodes (generally minimum 3 nodes are required).
  • In a replica set one node is primary node and remaining nodes are secondary.
  • All data replicates from primary to secondary node.
  • At the time of automatic failover or maintenance, election establishes for primary and a new primary node is elected.
  • After the recovery of failed node, it again join the replica set and works as a secondary node.

Replica set features

  • A cluster of N nodess
  • Anyone node can be primary
  • All write operations goes to primary
  • Automatic failover
  • Automatic Recovery
  • Consensus election of primary


Here is a very quick example of how to setup a 3 node MongoDB replica set within a development environment.

Note these instructions walkthrough how to setup a replica set on a single box.
This is handy for a development machine but when moving to production you should have separate machines per node.

Setup MongoDB Replica set
Create 3 local MongoDB instances

1.Make data directory
First thing to do is to create 3 empty directories that will be used for each mongodb node to store its data

mkdir -p /data/r0
mkdir -p /data/r1
mkdir -p /data/r2

2.Start 3 Local Instances
Simply start each mongodb server giving it a replica set name, individual port and data directory

mongod --dbpath /data/r0 --port 27017 --replSet "mahesh-rs"
mongod --dbpath /data/r1 --port 27027 --replSet "mahesh-rs"
mongod --dbpath /data/r2 --port 27037 --replSet "mahesh-rs"

3.Configuring the Replica Set
Now that the mongodb nodes are running, the next step is to configure the set. Open the mongo command shell

mongo localhost:27017

Execute the following command to define the configuration members within your replica set

> config = {_id: 'mahesh-rs', members: [
               {_id: 0, host: 'localhost:27017'},
               {_id: 1, host: 'localhost:27018'},
               {_id: 2, host: 'localhost:27019'}]
           };
Once you have the configuration defined, you need to initial your configuration by executing:

> rs.initiate(config);

To check everything is running as expected execute:

> rs.status();

To find the primary

db.isMaster()



No comments:

Post a Comment