Setup MongoDB Replica Set

Setup MongoDB Replica Set – In this MongoDB Tutorial, we shall learn to set up a replica set on a single machine for practice and across multiple machines connected in a network for a more realistic deployment.

A MongoDB replica set is a group of mongod processes that maintain the same data set. One member is elected as the PRIMARY and receives writes. Other data-bearing members usually run as SECONDARY members and replicate the primary member’s oplog. If the primary becomes unavailable, eligible members can elect a new primary.

This tutorial keeps the original single-machine example and adds practical notes for modern MongoDB usage, including mongosh, hostnames, three-member planning, application connection strings, and checks to confirm replication.

MongoDB Replica Set Setup Options Covered in This Tutorial

MongoDB Replica Set Terms: PRIMARY, SECONDARY, Oplog and Election

Replica set termMeaning in MongoDBWhy it matters during setup
PRIMARYThe member that currently accepts write operations.Run write tests on the primary when verifying replication.
SECONDARYA data-bearing member that replicates data from the primary.Check secondaries to confirm that data is being copied.
OplogA capped collection that records operations for replication.Secondaries read the oplog to apply changes in order.
ElectionThe process used by eligible members to choose a primary.An odd number of voting members helps avoid election ties.
Replica set nameThe identifier passed with --replSet, such as rs0.All members and application connection strings must use the same set name.

Setup MongoDB Replica Set on a Single Machine with Multiple mongod Instances

In this scenario, there is only a single machine, but we run multiple mongod instances. This is useful for learning commands and checking replica set behavior. It is not a replacement for a production deployment because one machine failure can stop every member.

To set up a MongoDB replica set on a single machine, each mongod instance needs a different port and a different data path. In this example, the replica set name is rs0.

1. Start the First mongod Instance for Replica Set rs0

Standalone mongod instance by default uses 27017 port and /var/lib/mongodb/ (in ubuntu) data path. We shall use the same for this mongod instance.
Run the following command to start a mongod instance.

$ mongod --port 27017 --dbpath /var/lib/mongodb --replSet rs0

--replSet rs0 means that this mongod process is being started as a member of the replica set named rs0. All other members that join this set must use the same replica set name.

On a current installation, you may prefer the same command without the shell prompt symbol:

</>
Copy
mongod --port 27017 --dbpath /var/lib/mongodb --replSet rs0 --bind_ip localhost

For a local practice setup, --bind_ip localhost keeps the instance available only from the same machine. For a networked replica set, use resolvable hostnames and a secure private network configuration instead of exposing MongoDB directly to the public internet.

2. Start the Second mongod Instance with a Different Port and dbpath

We should use unique set of port and data path for each instance, otherwise we may get port binding error and data path issues. For this instance we shall use 27018 port and /var/lib/mongodb1/ data path. You may create the directory, /var/lib/mongodb1/ using following command.

$ mkdir /var/lib/mongodb1/

Run the following command to start mongod instance.

$ mongod --port 27017 --dbpath /var/lib/mongodb --replSet rs0

The command block above is kept from the original example. For the second local instance, use a different port and a different database path, as shown below.

</>
Copy
sudo mkdir -p /var/lib/mongodb1
sudo chown -R mongodb:mongodb /var/lib/mongodb1

mongod --port 27018 --dbpath /var/lib/mongodb1 --replSet rs0 --bind_ip localhost

Observe that this instance is also started with the same replica set name, rs0. The port and data path are different, but the replica set name is the same.

3. Start Replication by Initiating the MongoDB Replica Set

You may create as many number of instances as required and feasible, by following the second step.
To start replication, open mongo shell and run the following command.

> rs.initiate()
root@tutorialkart:/home/arjun# mongo
MongoDB shell version v3.4.10
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.10
> rs.initiate()
{
	"info2" : "no configuration specified. Using a default configuration for the set",
	"me" : "tutorialkart:27017",
	"ok" : 1
}

Current MongoDB versions use mongosh instead of the older mongo shell. Connect to the first member and initiate the replica set only once.

</>
Copy
mongosh --port 27017
</>
Copy
rs.initiate()

Now the mongo shell prompt would be changed to rs0:PRIMARY>

You may also check the status using rs.status() method.

4. Add a MongoDB Instance to the Replica Set

To add the MongoDB instances that we already started in step 2, run the following command in the mongo shell that we already opened in the previous step 2.

> rs.add(<hostname:port>);

To check the hostname, Open a new Terminal and run the following command

$ hostname
root@tutorialkart:~# hostname
tutorialkart

We shall add the second MongoDB instance running at tutorialkart:27018.

rs0:PRIMARY> rs.add("tutorialkart:27018");
{ "ok" : 1 }


Response { "ok" : 1 } meaning addition of mongod instance to the replica set is successful.

For a local-only test, you can add the second member with localhost. For a multi-machine replica set, use DNS hostnames that every member and application server can resolve consistently.

</>
Copy
rs.add("localhost:27018")

If you plan to add all members at the time of initiation, you can also pass a configuration document to rs.initiate(). The following syntax shows the pattern for a three-member set.

</>
Copy
rs.initiate({
  _id: "rs0",
  members: [
    { _id: 0, host: "mongodb0.example.net:27017" },
    { _id: 1, host: "mongodb1.example.net:27017" },
    { _id: 2, host: "mongodb2.example.net:27017" }
  ]
})

5. Check MongoDB Replica Set Status

You may check the status of the Replica Set by running the following command

> rs.status();
</>
Copy
rs0:PRIMARY> rs.status()
{
	"set" : "rs0",
	"date" : ISODate("2017-11-07T09:22:13.627Z"),
	"myState" : 1,
	"term" : NumberLong(1),
	"heartbeatIntervalMillis" : NumberLong(2000),
	"optimes" : {
		"lastCommittedOpTime" : {
			"ts" : Timestamp(1510046524, 1),
			"t" : NumberLong(1)
		},
		"appliedOpTime" : {
			"ts" : Timestamp(1510046524, 1),
			"t" : NumberLong(1)
		},
		"durableOpTime" : {
			"ts" : Timestamp(1510046524, 1),
			"t" : NumberLong(1)
		}
	},
	"members" : [
		{
			"_id" : 0,
			"name" : "tutorialkart:27017",
			"health" : 1,
			"state" : 1,
			"stateStr" : "PRIMARY",
			"uptime" : 448,
			"optime" : {
				"ts" : Timestamp(1510046524, 1),
				"t" : NumberLong(1)
			},
			"optimeDate" : ISODate("2017-11-07T09:22:04Z"),
			"electionTime" : Timestamp(1510046162, 2),
			"electionDate" : ISODate("2017-11-07T09:16:02Z"),
			"configVersion" : 2,
			"self" : true
		},
		{
			"_id" : 1,
			"name" : "tutorialkart:27018",
			"health" : 1,
			"state" : 2,
			"stateStr" : "SECONDARY",
			"uptime" : 29,
			"optime" : {
				"ts" : Timestamp(1510046524, 1),
				"t" : NumberLong(1)
			},
			"optimeDurable" : {
				"ts" : Timestamp(1510046524, 1),
				"t" : NumberLong(1)
			},
			"optimeDate" : ISODate("2017-11-07T09:22:04Z"),
			"optimeDurableDate" : ISODate("2017-11-07T09:22:04Z"),
			"lastHeartbeat" : ISODate("2017-11-07T09:22:11.678Z"),
			"lastHeartbeatRecv" : ISODate("2017-11-07T09:22:11.698Z"),
			"pingMs" : NumberLong(0),
			"syncingTo" : "tutorialkart:27017",
			"configVersion" : 2
		}
	],
	"ok" : 1
}

Now there are two members in the Replica Set, with tutorialkart:27017 being PRIMARY and tutorialkart:27018 being SECONDARY.

In a current shell, the same check is:

</>
Copy
rs.status()
rs.conf()

In the output, check that ok is 1, one member has stateStr as PRIMARY, and the added member has stateStr as SECONDARY. Also confirm that the member names use hostnames or addresses that other members can reach.

6. Check MongoDB Replication by Writing on PRIMARY and Reading from SECONDARY

Now we shall check if the replication is happening correctly.

In the PRIMARY instance, insert a document to MongoDB Database.

rs0:PRIMARY> use fruits
switched to db fruits
rs0:PRIMARY> db.seasonal.insertOne({ name: "Mango", season: "Summer"})
{
	"acknowledged" : true,
	"insertedId" : ObjectId("5a018ea7c89da78ba2076f25")
}
rs0:PRIMARY> 

It is time to check in the SECONDARY instance, if this has replicated.
To connect to MongoDB instance running at 27018, run the following command.

$ mongo --port 27018
rs0:SECONDARY> use fruits
switched to db fruits
rs0:SECONDARY> db.seasonal.find();
{ "_id" : ObjectId("5a018ea7c89da78ba2076f25"), "name" : "Mango", "season" : "Summer" }
rs0:SECONDARY> 

The document inserted on the primary is visible from the secondary, so replication is working.

With current mongosh, connect to the secondary and allow secondary reads before running a read query directly on that secondary member.

</>
Copy
mongosh --port 27018
</>
Copy
db.getMongo().setReadPref("secondary")
use fruits
db.seasonal.find()

Setup MongoDB Replica Set with Multiple Machines

In this scenario, there are multiple machines connected over the network and there is a MongoDB instance on each node. This is the normal direction for a real replica set because the members should not all depend on one physical or virtual machine.

The steps to Setup Replica Set with multiple machines are similar to Setup Replica Set on a single machine. The difference is that the second and third mongod instances run on other hosts in the network, and each member is added with a hostname that all members can resolve.

Initially, the one instance from which you start replication acts as PRIMARY and other instances act as SECONDARY. After that, MongoDB can elect another eligible member as primary if the current primary becomes unavailable.

Recommended Three-Member MongoDB Replica Set Layout

A three-member replica set is a common starting point because it gives the set an odd number of voting members. The hostnames below are examples; replace them with hostnames from your own private network or DNS.

MemberExample hostnamePortTypical role
Member 0mongodb0.example.net27017PRIMARY after initial election
Member 1mongodb1.example.net27017SECONDARY
Member 2mongodb2.example.net27017SECONDARY

On each server, start mongod with the same replica set name and a bind IP configuration that is reachable only from trusted hosts.

</>
Copy
mongod --replSet rs0 --bind_ip localhost,mongodb0.example.net --port 27017 --dbpath /var/lib/mongodb

Use the correct hostname for each server. Then connect to one member with mongosh and initiate the set with all members.

</>
Copy
mongosh "mongodb://mongodb0.example.net:27017"
</>
Copy
rs.initiate({
  _id: "rs0",
  members: [
    { _id: 0, host: "mongodb0.example.net:27017" },
    { _id: 1, host: "mongodb1.example.net:27017" },
    { _id: 2, host: "mongodb2.example.net:27017" }
  ]
})

After the set is initiated, run rs.status() and confirm that all members are healthy. If a member stays unreachable, check firewall rules, hostname resolution, bindIp, the replica set name, and whether the mongod process is running on that host.

MongoDB Replica Set Connection String for Applications

After a replica set is ready, applications should connect with a replica-set-aware connection string. Include multiple members so the driver can discover the topology and continue operating after a primary election.

</>
Copy
mongodb://mongodb0.example.net:27017,mongodb1.example.net:27017,mongodb2.example.net:27017/?replicaSet=rs0

For secured deployments, the connection string may also include authentication, TLS, read preference, retry writes, and application-specific options. Do not publish credentials in tutorials, logs, or screenshots.

Production Checks Before Using a MongoDB Replica Set

A local replica set is useful for learning, but a production MongoDB replica set needs additional planning. Review these points before allowing applications to depend on the set.

  • Use at least three voting members where possible: This helps the set elect a primary without depending on a single secondary.
  • Use hostnames instead of changing IP addresses: Hostnames are easier to manage when servers move or network details change.
  • Enable access control: Create users and require authentication before exposing the database to applications.
  • Secure member-to-member traffic: Use key files or x.509 configuration as appropriate for internal authentication.
  • Restrict network access: Open MongoDB ports only to trusted application hosts and replica set members.
  • Plan backups separately: Replication is not a backup. It copies writes, including accidental deletes, to other members.
  • Monitor replication lag: A secondary that falls behind can affect failover readiness and read behavior.
  • Test failover: Confirm that applications reconnect correctly after a primary election.

Common MongoDB Replica Set Setup Errors and Fixes

Error or symptomLikely causeWhat to check
Port already in useTwo mongod processes are using the same port.Use a unique port for each local instance, such as 27017 and 27018.
Data directory lock errorTwo instances are using the same dbpath.Create a separate data directory for each instance.
SECONDARY member not reachableHostname, firewall, or bindIp problem.Confirm DNS resolution and open ports only between trusted hosts.
rs.add() succeeds but member is unhealthyThe primary cannot communicate with the added member.Check logs on both servers and verify the member name in rs.conf().
Application connects to one node onlyConnection string does not include replica set details.Use a connection string with multiple hosts and replicaSet=rs0.
Reads fail on secondary in shellDirect secondary reads are not enabled for that shell session.Set an appropriate read preference before reading directly from a secondary.

FAQ About Setting Up a MongoDB Replica Set

How many MongoDB nodes are needed for a replica set?

A replica set can be initiated with one member for development or conversion work, but a practical highly available setup normally uses at least three voting members. With only two members, the set has limited ability to elect a primary if one member is unavailable.

Can I set up a MongoDB replica set on one machine?

Yes. You can run multiple mongod instances on one machine by giving each instance a separate port and data path. This is useful for learning and testing, but it does not protect against machine failure.

What is the difference between mongo and mongosh in replica set commands?

mongo is the older MongoDB shell used in many legacy examples. mongosh is the current MongoDB shell. Replica set methods such as rs.initiate(), rs.add(), rs.status(), and rs.conf() are run from the shell after connecting to a MongoDB instance.

Should I use IP addresses or hostnames in MongoDB replica set members?

Use stable, resolvable hostnames whenever possible. Hostnames are easier to manage than changing IP addresses and help avoid replica set configuration problems when servers or network details change.

Does MongoDB replication replace database backups?

No. Replication improves availability by keeping copies of the data on multiple members, but it also replicates accidental updates and deletes. Keep a separate backup and restore strategy for production data.

Editorial QA Checklist for MongoDB Replica Set Tutorial Review

  • Verify that every local mongod instance uses a unique port and unique dbpath.
  • Confirm that all members use the same replica set name, such as rs0.
  • Check that newer guidance mentions mongosh while preserving older mongo shell examples where needed.
  • Ensure that multi-machine examples use resolvable hostnames, not placeholder IP addresses that may encourage fragile configuration.
  • Confirm that the tutorial distinguishes learning setups from production deployments.
  • Check that the application connection string includes multiple hosts and the replica set name.
  • Review security notes for authentication, network restrictions, internal member authentication, and backups.
  • Verify that replication testing writes to the primary and reads from a secondary with the correct read preference.

Summary of MongoDB Replica Set Setup

In this MongoDB Tutorial – Setup MongoDB Replica Set, we have learnt to set up a replica set on a single machine with multiple mongod instances and across multiple machines connected in a network. For practice, a single-machine setup is enough to understand rs.initiate(), rs.add(), rs.status(), and basic replication checks. For applications, use a properly secured multi-member replica set, stable hostnames, a replica-set-aware connection string, monitoring, and backups.