Example of Deploy a Replica Set in MongoDB
- Prepare Servers: Set up these three servers are mongo-primary, mongo-secondary, and mongo-arbiter.
- Install MongoDB: Install MongoDB on each server.
1. Configure Replica Set:
Start a MongoDB replica set with one primary node, one secondary node and one arbiter node on the same local machine for testing and development purposes.
# Start the Primary Node
mongod --replSet rs0 --port 27017 --dbpath /data/rs0 --bind_ip 127.0.0.1
# Start the First Secondary Node
mongod --replSet rs0 --port 27018 --dbpath /data/rs1 --bind_ip 127.0.0.1
# Start the Arbiter Node
mongod --replSet rs0 --port 27019 --dbpath /data/rs2 --bind_ip 127.0.0.1
2. Start MongoDB Instances:
Start MongoDB instances on each server.
Initialize Replica Set:
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 }
]
})
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
How to Deploy a Replica Set in MongoDB?
A MongoDB replica set configures MongoDB instances that collectively maintain the same dataset providing redundancy and high availability. This setup is fundamental for all production deployments. A replica set consists of several data-bearing nodes with one acting as the primary node and the others as secondary nodes. In this article, We will learn How to Deploy a Replica Set in MongoDB in detail.