![]() |
VOOZH | about |
A MongoDB replica set is a group of MongoDB instances that maintain the same dataset to provide high availability, data redundancy, and automatic failover. It is the standard architecture for all production MongoDB deployments.
A replica set typically consists of:
Before deploying a replica set, ensure:
To deploy a MongoDB replica set, we will need to set up multiple MongoDB instances across different servers or virtual machines. After configuring each instance with a unique port and replica set name, initialize the replica set and add nodes. This ensures high availability, data redundancy, and automatic failover in case of node failure
Example
# Primary Node
mongod --replSet rs0 --port 27017 --dbpath /data/rs0 --bind_ip localhost
# Secondary Node
mongod --replSet rs0 --port 27018 --dbpath /data/rs1 --bind_ip localhost
# Arbiter Node
mongod --replSet rs0 --port 27019 --dbpath /data/rs2 --bind_ip localhost
# Start Primary Node
mongod --replSet "rs0" --port 27017 --dbpath /data/db1 --bind_ip localhost
# Start Secondary Node
mongod --replSet "rs0" --port 27018 --dbpath /data/db2 --bind_ip localhost
# Start Arbiter Node
mongod --replSet "rs0" --port 27019 --dbpath /data/db3 --bind_ip localhost
rs.initiate() command to initiate the replica set by selecting a primary node and synchronizing data to secondary nodes from the MongoDB shell. Initialize Replica Set Command:
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "127.0.0.1:27017" },
{ _id: 1, host: "127.0.0.1:27018" },
{ _id: 2, host: "127.0.0.1:27019", arbiterOnly: true }
]
})
This command specifies the replica set name (rs0) and the members, including the primary, secondary, and arbiter.
rs.add() method to add a new secondary node.Example:
rs.add("localhost:27020")
rs.status() command to verify the status of the replica set and ensure all nodes are functioning correctly.rs.status()
Output:
{
"ok": 1,
"$clusterTime": {
"clusterTime": Timestamp(1637264328, 1),
"signature": {
"hash": BinData(0, "LAtUrh6VpBqrz0W9EYXL/DBLKpM="),
"keyId": NumberLong("6957828764884994049")
}
},
"operationTime": Timestamp(1637264328, 1)
}
Explanation: The rs.initiate() command initializes a MongoDB replica set named rs0 with three members: one primary node, one secondary node, and one arbiter node, all running on localhost but different ports
mongod.conf and startup parametersMongoDB replica sets are designed to handle automatic failover. If the primary node fails, MongoDB automatically triggers an election process to promote one of the secondary nodes to primary, minimizing downtime.
rs.stepDown() command.Example:
rs.stepDown()