MongoDB Replication

MongoDB Replication on same server with two secondary instances.

Requirement :

  1. Primary Server (127.0.0.1) – 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)--------------
/var/lib/mongo3/
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/mongod.pid --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/mongod2.pid --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/mongod3.pid --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>");
rs.initiate()
rs.conf()

Step 7 : Add replica

rs.add ("hostname:port")
#REPLICA 1
rs.add("localhost:27018")
#REPLICA 2
rs.add("localhost:27019")

Step 7 : Check status

rs.status()

Step 8 : Remove Replica

If in future you want to remove replica

rs.remove("localhost:27018")

Leave a Reply