How to create and start a MongoDB Replica Set?
This guide is primarily for Windows PC. However you might find some useful information on replica sets here.
Step 1: Initial Setup - Create necessary folders
Create the 3 folders for PRIMARY(1) and SECONDARY(2) MongoD instances
C:\data\db0
C:\data\db1
C:\data\db2
Step 2: Configure MongoD
I will be using MONGO_DIR
to alias the MongoDB installation folder. For example MONGO_DIR
equals to C:\Program Files\MongoDB\Server\4.4
on my PC
Open the file MONGO_DIR\bin\mongod.cfg
in your favorite editor. And check if there are any replication options confiured. By default you will find replication commented.
#replication:
You can specify replSetName as rs0
replication:
replSetName: rs0
I recommend you to run the following commands with administrator privilages. You might need to open 4 terminals or command prompt windows(all as administrator). (Optional)I recommend using Microsoft Terminal in which you can open new terminal as a new tab - easy to manage.
Step 3: Start PRIMARY node
Run the following command to start a PRIMARY mongod instance
mongod --port 27017 --replSet rs0 --dbpath="C:\data\db0"
Step 4: Start your first SECONDARY node
Open new command prompt window. Run the following command to start a SECONDARY mongod instance
mongod --port 27027 --replSet rs0 --dbpath="C:\data\db1"
Step 5: Start another SECONDARY node
Open new command prompt window. Run the following command to start another SECONDARY mongod instance
mongod --port 27037 --replSet rs0 --dbpath="C:\data\db2"
Step 6: Initiate Replica Set
Open new command prompt window and connect to primary node
mongo --port 27017
Initiate Replica Set
rs.initiate()
Step 7: Add new members to Replica Set
In the same window where you initiated the replica set, Run the following commands:
rs.add( { host: "127.0.0.1:27027", priority: 0, votes: 0 } )
rs.add( { host: "127.0.0.1:27037", priority: 0, votes: 0 } )
Now we have one primary node and two secondary nodes in the replica set. We can confirm it by running the following command:
rs.status()
Bonus: Connecting through MongoDB Compass
You can use the following connection string to connect using Compass
mongodb://127.0.0.1:27017/?replicaSet=rs0&w=majority&readPreference=primary&ssl=false
Last Updated on
Comments