Monday, February 25, 2019

How to create a MongoDB Replica Set on Unix

Lets say, we want to create a 3 node mongo replication set on 3 machines -mongo_host1 ,mongo_host2, mongo_host3 with following log and data directory

Host1: mongo_host1
Data directory  : /u02/msetup/repl_data/mem1
Log directory : /u02/msetup/repl_data/log/mongod1.log
port:3000

Host2 : mongo_host2
Data directory  : /u02/msetup/repl_data/mem2
Log directory : /u02/msetup/repl_data/log/mongod2.log
port:3000

Host3 : mongo_host3
Data directory  : /u02/msetup/repl_data/mem3
Log directory : /u02/msetup/repl_data/log/mongod3.log
port:3000

1 Firstly,  we have to setup respective directories -
mkdir -p  /u02/msetup/repl_data/log
mkdir p  /u02/msetup/repl_data/mem1(for node 1)

2 Next, we create configuration file for mongo for mongo_host1
more /u02/msetup/repl_data/mem1/mongo1.conf
mongo1.conf

processManagement:
   fork: true
systemLog:
  destination: file
  logAppend: true
  path: /u02/msetup/repl_data/log/mongod1.log
# Where and how to store data.
storage:
  dbPath: /u02/msetup/repl_data/mem1
# network interfaces
net:
  port: 30000
  bindIp: 0.0.0.0
##  bindIp: 127.0.0.1  # Listen to local interface only, comment to listen on all interfaces.
replication:
  replSetName: repl_data

3 Next we create similar files for other 2 nodes-mongo_host2 and mongo_host3
edit the respective conf file for log and data directory location

4 Next, we start each of these 3 mongo members as stand alone mongo

On mongo_host1 ->mongod --config /u02/msetup/repl_data/mem1/mongo1.conf
On mongo_host2 ->mongod --config /u02/msetup/repl_data/mem2/mongo2.conf
On mongo_host3 ->mongod --config /u02/msetup/repl_data/mem3/mongo3.conf


5 Now, we connect to mongo and define the configuration for replica set and initiate it
On mongo_host1,
mongo  --port 30000

cfg ={ _id : "repl_data", members: [ { _id:0 ,host:"mongo_host1:30000" }, { _id:1 ,host:"mongo_host2:30000" }, { _id:2 ,host:"mongo_host3:30000" } ] }

rs.initiate ( cfg )

rs.status() -> this will show information about all 3 members of replica set.

NOTE: To connect to secondary nodes, we have to issue rs.slaveOk(). Like in this case, to connect to mongo on mongo_host2 and mongo_host3-
mongo  --port 30000
rs.slaveOk()


If you want to set up mongo replication on windows, then plz go through following link for creating mongo replica set-
http://www.dbatraininghub.com/2019/02/how-to-create-replica-set-in-mongo-on.html


No comments: