MongoDB demo on Replica Set
--
Are you curious about how Replica Set works on Mongo DB? How much complex, or easy, is to set it? How the data is replied on “Secondary” slaves? or When a new master is born after the “Primary” gets down?
In this demo, if you keep reading, we will see the highlight steps and commands to deal on Mongo with a Replica Set.
Before we start, we will create three temp directories for this exercise: for simplicity will be using: /tmp/mongors/data
$ pwd
/tmp/mongorsets/data$ mkdir -p data/rs1 data/rs2 data/rs3
Step #01: Start the nodes
First of all, we will create a replica set, with three nodes:
$ mongod --replSet rs1 --logpath "1.log" --dbpath ./rs1 --port 27017 --fork$ mongod --replSet rs1 --logpath "2.log" --dbpath ./rs2 --port 27018 --fork$ mongod --replSet rs1 --logpath "3.log" --dbpath ./rs3 --port 27019 --fork
At this moment, we have three MongoDB, but they are independents (they do not know anything from each other)
Step #02: Setting the Replica Set
To setup the replica set, we will use the following script “init_replica_pablo.js”:
config = { _id: "rs1", members:[
{ _id : 0, host : "localhost:27017", priority:0, slaveDelay:5 },
{ _id : 1, host : "localhost:27018"},
{ _id : 2, host : "localhost:27019"} ]
};rs.initiate(config);
rs.status();
We will use the second node listening on 27018 as primary (the mongod on 27017 has priority in zero, so is the last elegible for prumary)
mongo --port 27018 < init_replica_pablo.js
Ok, we can see in the secondary logs, that after the replica set on primary, they realized that they are on a replica set:
Step #03: Insert Data in Primary
Now, inside the mongo console, we will run the folling command, and we will insert some data on Primary MongoDD Node
$ mongo --port 27018
Step #04: What is happening on Secondary
First time, we see an error, but it can be easy fixed with “rs.slaveOk()” on secondary:
So, we can see the data written on the replica slave, a Secondary One, but, what happen if something wrong affect the master node? It is easy to see … if we broke things!
Step #05: Shut down Primary!
So, the config is:
Step #05.i ~ Verify status with oplog.rs
Before the shut down, some commands to verify the healthy nodes:
rs1:PRIMARY> db.oplog.rs.find({ ns : “test.people”}).pretty()
We can see our insert ops recorded on oplog.rs
So, the same oplog.rs are on PRIMARY, and copied to secondaries ….
Step #05.ii ~ Shut Down Primary
Primary is dead … long live to the PRIMARY!
And that is all! In less than 10 minutos, a fast overview about how to work on MongoDB with Replicas Set
I hope you enjoyed it, and we will see o a next one
Pablo!
Resources
You can learn mongo in depth in the excellent course “MongoDB M101J” from MongoDB University. These topics about Replica Set are covered on chapter six