Three Node MongoDB Replica

Introduction

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.

Installation

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=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.4/x86_64/gpgcheck=1enabled=1gpgkey=https://www.mongodb.org/static/pgp/server-4.4.asc

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
mongo

Setting up replica set

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

replication:
replSetName: “REPLICA_NAME”
net:
bindIp: localhost,OTHER_IP_ADDRESS/HOST_NAME (0.0.0.0 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( {
_id : "REPLICA_NAME",
members: [
{ _id: 0, host: "mongodb0.example.net:27017" },
{ _id: 1, host: "192.168.40.5:27017" },
{ _id: 2, host: "mongodb2.example.net:27017" }
]
})
rs.conf()
use admin
db.shutdownServer()
rs.stepDown();

Notes

  1. In /etc/mongod.conf file never use 0.0.0.0 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:
exclude=mongodb-org,mongodb-org-server,mongodb-org-shell,mongodb-org-mongos,mongodb-org-tools

Software Engineer