Database replication is a service for shipping changes to your database, off to a copy housed on another server, potentially even in another data center.It ensures redundancy, backup, and automatic failover.
Replication occurs through groups of servers known as replica sets, each of which stores the same dataset as the other members of the replica set.
Replication in MongoDB
In MongoDB, replication is implemented in two forms:
- Replica Sets: Group of replication nodes containing one primary node and multiple secondary nodes. Primary accepts write operations, and secondaries are the replicating members. MongoDB’s replica sets provide automated failover. If a primary fails, the remaining members will automatically try to elect a new primary.
- Master-Slave Architecture: When the number of the replica nodes need to be more than 12, then Master-Slave architecture comes in. It is similar to Replica Sets except that it does not provide automated failover.
Replication in MongoDB
Deploying a Replica Set
With trivial knowledge gathered about Replica Sets in MongoDB, try deploying one using the steps below:
Step 1: Follow Step 1,2 and 3 for setting up MongoDB on all the nodes of the Replica Set as given in my previous post.
Step 2: Create a conf file (for example "mongod.conf") at a location owned and accessible by the user with the following content. You can configure "port" and name your replica set by setting the field "replSet" to that name which would be same on all the nodes of the replica set.
nojournal = true
port = 27017
bind_ip = machine_ip (for eg. 126.96.36.199)
fork = true
replSet = rsName
Step 3: Start the MongoD daemon on each node of the Replica Set using:
/bin/mongod --config /pathToFile/mongod.conf
Step 4: Open a mongo terminal on the node which you want to be the primary node using:
bin/mongo --host ip_of_the_machine
Step 5: To add the other nodes, run the add commands in the opened mongo terminal on the primary node:
and so on.
After initializing the primary using "rs.initiate()" add the secondaries using :
mongo primary_ip:mongod_port /path_to_js_file
where the .js file contains
Hope that the above steps helped you create a Replica Set successfully. My next post would be on "Creating a MongoDB Sharded Cluster".