Three Node MongoDB Replica


MongoDB is a popular NoSQL database. It’s a document database meaning it stores data in JSON-like format. What if our database is down for some reason? How will we serve the users in the meantime? We need a system that is scalable, highly available, has better performance, ensures data durability. Replica set comes to the rescue here.

Replica set

Replica set in MongoDB are instances of mongod processes that have the same data. Whenever data is written in any of the databases that are immediately replicated in the other databases in the replica sets. Usually, there is one primary node, and the rest of the nodes act as secondary nodes or as arbiters. Unlike the primary and secondary nodes, arbiters don’t store data. They participate in the election for primary only. There may be up to 50 nodes in a replica set.


We will be using CentOs and MongoDB-4.4 version for this tutorial.

Configure the package management system (yum)

Create a repo file so that you can install MongoDB directly using yum:

cd /etc/yum.repos.d/
[mongodb-org-4.4]name=MongoDB Repositorybaseurl=$releasever/mongodb-org/4.4/x86_64/gpgcheck=1enabled=1gpgkey=

Install the MongoDB packages

To install the latest stable version of MongoDB, issue the following command:

sudo yum install -y mongodb-org

Run MongoDB as a service

  • To start mongo as daemon(background process):
sudo systemctl start mongod
sudo systemctl status mongod
sudo systemctl stop mongod

Setting up replica set

For all the members in the replica set open /etc/mongod.conf file & edit the followings:

replSetName: “REPLICA_NAME”
bindIp: localhost,OTHER_IP_ADDRESS/HOST_NAME ( for allowing all ips)
sudo systemctl daemon-reload
sudo systemctl status mongod

Initiating the replica set

First, we need to initiate the replica set. From any of the servers, you need to initiate it. To initiate, go to mongo console and run the following commands():

rs.initiate( {
members: [
{ _id: 0, host: "" },
{ _id: 1, host: "" },
{ _id: 2, host: "" }
use admin


  1. In /etc/mongod.conf file never use for ip_bind option it will allow all ips to interact with the db.
  2. The article assumes all default options for initial configuration. You can change the port number, add authorization from the /etc/mongod.conf file. Always verify mongod is running fine after any change in this file.
  3. With version change, commands and configurations for mongo change a lot. To stop updating the version after installation, add the line in the /etc/yum.conf file:

Software Engineer