Replica Set Initialization and Management
Advanced20 min
Deploy a MongoDB replica set for high availability with automatic failover, data redundancy, and read scaling across multiple nodes.
Prerequisites
- -MongoDB 6+ installed on 3 servers (or 3 local instances on different ports)
- -Network connectivity between all nodes
Steps
1
Start MongoDB instances with replication enabled
Launch three mongod instances with the same replica set name.
$ mongod --replSet rs0 --port 27017 --dbpath /data/rs0-0 --bind_ip localhost --fork --logpath /var/log/mongodb/rs0-0.log
Repeat for ports 27018 and 27019 with different dbpath and logpath values.
2
Initialize the replica set
Connect to one instance and initialize the replica set with all members.
$ mongosh --port 27017 --eval 'rs.initiate({_id: "rs0", members: [{_id: 0, host: "localhost:27017"}, {_id: 1, host: "localhost:27018"}, {_id: 2, host: "localhost:27019"}]})'
3
Check replica set status
View the current state of all replica set members and identify the primary.
$ mongosh --port 27017 --eval 'rs.status().members.forEach(m => print(m.name + ": " + m.stateStr + " (health: " + m.health + ")"))'
4
Verify replication is working
Write data to the primary and read it from a secondary to confirm replication.
$ mongosh --port 27017 --eval 'db.test.insertOne({msg: "replication test", ts: new Date()})' mydb && mongosh --port 27018 --eval 'db.getMongo().setReadPref("secondary"); db.test.find().sort({ts: -1}).limit(1)' mydb
5
View replication lag
Check how far behind each secondary is from the primary.
$ mongosh --port 27017 --eval 'rs.printSecondaryReplicationInfo()'
Full Script
FAQ
Discussion
Loading comments...