MongoDB Replication

MongoDB Replication on same server with two secondary instances.

Requirement :

  1. Primary Server ( – Port : 27017
  2. Secondary server – A (Replica)  Port : 27018
  3. Secondary Server – B (Replica)  Port : 27019

STEP 1 : Install MongDB

Step 2: Create mongo,mongo2,mongo3 (three) directories at three different location

------------For Data Directory 1 (Primary)--------------
mkdir /var/lib/mongo/
chmod mongod:mongod  /var/lib/mongo/

------------For Data Directory 2 (Replica 1)--------------
mkdir /var/lib/mongo2/
chmod mongod:mongod /var/lib/mongo2/

------------For Data Directory 3 (Replica 2)--------------
chmod mongod:mongod /var/lib/mongo3/

Step 2 : Initialize Primary Server

mongod --port 27017 --dbpath /var/lib/mongo/ --keyFile /mongodb-keyfile --replSet rs2 
--pidfilepath /var/run/mongodb/ --fork --logpath /var/log/mongodb/mongod.log

mongod – is binary to initialize

port – port on which mongo will be initialize

dbpath – directory where your data reside

keyFile – Required if you want to initialize your database with authentication

replSet –  Replica set name which consist of multiple replica, Its unique name and should be same on all instances

pidfilepath – process id of mongod daemon will save on given location (optional)

fork to run process in background

logpath – mongo logs will be generated at given file and location

Step 4 : Initialize Replica Server 1 (27018)

mongod --port 27018 --dbpath /var/lib/mongo2/ --keyFile mongodb-keyfile --replSet rs2 
--pidfilepath /var/run/mongodb/ --fork --logpath /var/log/mongodb/mongod2.log

Step 5 : Initialize Replica Server 2 (27019)

 mongod --port 27019 --dbpath /var/lib/mongo3/ --keyFile mongodb-keyfile --replSet rs2 
--pidfilepath /var/run/mongodb/ --fork --logpath /var/log/mongodb/mongod3.log

Step 6 : Login on Primary Server and initialize replica set 

mongo --port 27017
use admin
db.auth("username", "<password>");

Step 7 : Add replica

rs.add ("hostname:port")

Step 7 : Check status


Step 8 : Remove Replica

If in future you want to remove replica


Leave a Reply