January 02, 2013

How to setup a replication set in MongoDB?

I just wanted to setup a replication set in MongoDB to check the behavior of MongoDB replica set.
For this demonstration I use MongoDB 2.2.0 and PowerShell 2.0.
First I want to create directories for MongoDB replication instances. I’m going to for a replication set with three nodes. So because of the I need to create there MongoDB data directories.

New-Item -ItemType Directory -Path \data\
New-Item -ItemType Directory -Path \data\repDb1
New-Item -ItemType Directory -Path \data\repDb2
New-Item -ItemType Directory -Path \data\repDb3
New-Item -ItemType Directory -Path \log

Now copy MongoDB Binaries to the drive that you ran above PowerShell commands. Change directory to MongoDB bin. And create three separate configuration files in MongoDB bin folder with notepad or any other plain text editor.
  • config1.cnf
  • config2.cnf
  • config3.cnf
Create config1.cnf file with below content.

logpath=d:\log\log1.txt
dbpath=d:\data\repDb1
port=9991
replSet=samplecluster
rest=true

Create config2.cnf file with below content.

logpath=d:\log\log2.txt
dbpath=d:\data\repDb2
port=9992
replSet=samplecluster
rest=true

Create config3.cnf file with below content.

logpath=d:\log\log3.txt
dbpath=d:\data\repDb3
port=9993
replSet=samplecluster
rest=true

Now we are going to run MongoDB. For that you must go to MongoDB bin folder. And Press Shift and while you pressing shift right click on free area. And select ‘Open command window here’




Now you will get a Command Prompt. Type below three commands on your command prompt.
start mongod –-config config1.cnf
start mongod –-config config2.cnf
start mongod –-config config3.cnf
Now you should login to one of those MongoDB instance to initiate the MongoDB replication set. For that type below command.

mongo localhost:9991
Now you have a MongoDB shell and you can initiate replication set. Type below command to initiate MongoDB replication set.

rs.initiate()
This command will take some time. Don’t worry most of the times its not stuck. Then you have to add other instances to this MongoDB replication set.

rs.add(“localhost:9992”);
rs.add(“localhost:9993”);
This will return { “ok” : 1 }. If it is not please replace your machine name to “localhost”. Now it is done. Your MongoDB replication is up and running!!!

No comments:

Post a Comment