Today I will tell you how to do Replica Set In Mongodb.
In this example, there are 3 servers, mongodb-node1, mongodb-node2 and mongodb-node3.
1 2 3 4 |
HOSTNAME IP ADDRESS mongodb-node1 192.168.1.26 PRIMARY mongodb-node2 192.168.1.27 SECONDARY mongodb-node3 192.168.1.28 SECONDARY |
1. We must have set up MongoDB Community on all three nodes.
2. Edit the /etc/hosts file on all three nodes.
1 2 3 |
192.168.1.26 mongodb-node1 192.168.1.27 mongodb-node2 192.168.1.28 mongodb-node3 |
3. We edit the following parameters in the /etc/mongod.conf file and configure the MongoDB replication cluster.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
mongodb-node1 : # network interfaces net: port: 27017 bindIp: 127.0.0.1,mongodb-node1 #replication: replication: replSetName: "replicaset01" mongodb-node2 : # network interfaces net: port: 27017 bindIp: 127.0.0.1,mongodb-node2 #replication: replication: replSetName: "replicaset01" mongodb-node3 : # network interfaces net: port: 27017 bindIp: 127.0.0.1,mongodb-node3 #replication: replication: replSetName: "replicaset01" |
4. We restart the MongoDB service on all three nodes for the changes to take effect.
1 |
$ systemctl restart mongod |
5. In Primary, we start the MongoDB replication cluster.
1 2 3 4 5 6 7 8 9 |
$ mongo test> rs.initiate() { info2: 'no configuration specified. Using a default configuration for the set', me: '192.168.1.26:27017', ok: 1 } replicaset01 [direct: other] test> [ ENTER ] replicaset01 [direct: primary] test> |
6. We are adding other nodes.
1 2 |
replicaset01 [direct: primary] test> rs.add("mongodb-node2") replicaset01 [direct: primary] test> rs.add("mongodb-node3") |
TESTING
To test, we create a collection in the Primary and this collection is queried in the Secondary node.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
PRIMARY NODE replicaset01 [direct: primary] test> use testdb replicaset01 [direct: primary] testdb> db.musteriler.insert({name: "Melek", surname: "Durdu"}) SECONDARY NODE replicaset01 [direct: secondary] testdb> show collections deneme musteriler replicaset01 [direct: secondary] testdb> db.musteriler.find().pretty() [ { _id: ObjectId("619e17e458487b48466c9cf4"), name: 'Melek', surname: 'Durdu' } ] |
As can be seen above, when we query the secondary node, the collection created in the primary is displayed. We have successfully created the replication cluster.