What is a MongoDB Replica Set? A Beginner-Friendly Guide with Docker Compose Demo

📌 Introduction
Ensuring your database is always available — even during server failures or maintenance — is a must in modern applications.
MongoDB's Replica Sets allow for high availability, data redundancy, and automatic failover. In this blog, we’ll explain:
What a MongoDB Replica Set is
Why it's important
Core components
How replication works
How to set up a MongoDB Replica Set using Docker Compose
Bonus tips for production environments
How to test and verify the MongoDB Replica Set
How to insert data into the replica set and verify its replication across nodes
🧬 What is a MongoDB Replica Set?
A Replica Set in MongoDB is a group of MongoDB servers that all maintain copies of the same data, providing high availability and fault tolerance. The core components are:
Primary Node – Accepts writes and reads.
Secondary Nodes – Replicate the primary’s data and can serve reads if configured.
Arbiter Node – A node that participates in elections but doesn’t store data (used for odd-numbered replica sets).
In simple terms, MongoDB Replica Sets ensure that your data is always accessible, even if one of the nodes goes down.
🧩 Core Components of a Replica Set
Primary Node: The main node that handles all writes and reads (unless read preferences are set to read from secondaries).
Secondary Nodes: These nodes replicate data from the primary and can serve read requests.
Arbiter Node: Used in even-numbered replica sets to help with elections. It does not store data but votes on primary elections.
🔁 How Replication Works
Client writes to the Primary.
Primary node logs the operation in its operation log (oplog).
Secondary nodes replicate the changes from the oplog.
Replication is asynchronous (there can be a small lag), which ensures eventual consistency.
⚠️ What Happens If the Primary Fails?
If the Primary node fails:
MongoDB starts an election to determine which secondary should become the new Primary.
The newly elected Primary node takes over and continues accepting writes.
This failover process is automatic and typically happens in seconds.
⚙️ Setting Up a MongoDB Replica Set with Docker Compose
Now, let’s set up a MongoDB Replica Set using Docker Compose. Docker Compose will help us easily spin up a multi-container environment with 3 MongoDB nodes.
🧑💻 Folder Structure
Create a new project directory and create the following files:
mongodb-replica-set/
├── docker-compose.yml
docker-compose.yml
will define the MongoDB replica set.
📄 Step 1: Define the Docker Compose File
version: '3.8'
services:
mongo1:
image: mongo:5
container_name: mongo1
command: mongod --replSet myReplicaSet --bind_ip localhost,mongo1
ports:
- "27017:27017"
networks:
- mongoCluster
restart: unless-stopped
mongo2:
image: mongo:5
container_name: mongo2
command: mongod --replSet myReplicaSet --bind_ip localhost,mongo2
ports:
- "27018:27017"
networks:
- mongoCluster
restart: unless-stopped
mongo3:
image: mongo:5
container_name: mongo3
command: mongod --replSet myReplicaSet --bind_ip localhost,mongo3
ports:
- "27019:27017"
networks:
- mongoCluster
restart: unless-stopped
networks:
mongoCluster:
driver: bridge
This file defines 3 MongoDB instances running on ports 27017, 27018, and 27019.
We’ve set root credentials for authentication.
🚀 Running the Replica Set
Navigate to the project directory and run the following command:
docker compose up -d
This command will pull the MongoDB Docker images and create the three MongoDB instances. Docker Compose will also execute the init-replica.js
script to initiate the replica set.
Screenshot 1 : Running a mongodb replica set
📄 Step 2: Initialize the Replica Set
docker exec -it mongo1 mongosh --eval "rs.initiate({
_id: 'myReplicaSet',
members: [
{_id: 0, host: 'mongo1:27017'},
{_id: 1, host: 'mongo2:27017'},
{_id: 2, host: 'mongo3:27017'}
]
})"
This command will initialize the replica set with 3 members.
We specify the container names (
mongo1
,mongo2
, andmongo3
) as the host addresses for each replica.
Screenshot 2 :Initialize the Replica Set
🧑💻 Verify the Replica Set Status
Once the containers are up, you can connect to any MongoDB instance to verify the status of the replica set.
Connect to the mongo1
container:
docker exec -it mongo1 mongosh
Run the following MongoDB shell command to check the replica set status:
rs.status()
Screenshot 2 :Verify the Replica Set Status
🔐 Testing MongoDB Replica Set Failover
Now that we have a working replica set, it’s time to test failover. Follow these steps:
1. Check the Current Primary Node
Run this command in the MongoDB shell:
rs.isMaster()
2. Simulate Primary Node Failure
Stop the mongo1
container to simulate a primary failure:
docker stop mongo1
MongoDB will automatically trigger a failover and elect a new Primary node from the remaining secondaries.
3. Verify the New Primary Node
After a few seconds, run the rs.isMaster()
command again to see which node is now the Primary:
rs.isMaster()
The primary
field should now show the new Primary node. This is a seamless failover with no downtime.
📝 Inserting Data into the Replica Set and Verifying Replication
1. Insert Data into the Primary Node
Insert some sample data into the replica set by connecting to the Primary node (e.g., mongo1
). You can use the MongoDB shell or a MongoDB client like MongoDB Compass.
Run this command to insert a document into a test
collection:
use test
db.users.insertOne({ name: "Alice", age: 30 })
This will insert the document { name: "Alice", age: 30 }
into the users
collection.
Screenshot 3 :Insert Data into the Primary Node
2. Verify Data Replication on the Secondary Nodes
Now, connect to the secondary nodes (mongo2
or mongo3
) to verify that the data has been replicated.
Connect to mongo2
:
docker exec -it mongo2 mongosh
Query the users
collection to verify the data:
use test
db.users.find()
You should see the document { name: "Alice", age: 30 }
replicated on mongo2
.
Screenshot 4 :Verify Data Replication on the Secondary Nodes
3. Verify Data on the New Primary Node After Failover
If you simulated a failover earlier, connect to the new Primary node and verify that the data has been replicated there as well.
docker exec -it mongo3 mongo
Run the same query to confirm the data is present:
use test
db.users.find()
You should see the same document { name: "Alice", age: 30 }
.
🔐 Production Considerations
Odd number of nodes: Always use an odd number of nodes (e.g., 3, 5) to ensure that there’s always a majority during elections.
Geographic distribution: For high availability, deploy MongoDB instances across multiple availability zones or regions.
Arbiter: If needed, deploy an Arbiter in a separate data center to avoid an even-numbered replica set.
Authentication: Enable authentication in production environments.
TLS: Ensure secure communication between nodes with TLS encryption.
🧠 Final Thoughts
MongoDB Replica Sets are a critical component for building highly available, resilient applications. Using Docker Compose makes it easier than ever to set up and experiment with MongoDB Replica Sets locally.
Now you understand:
How replication works
What happens if a primary fails
How to set up a local replica set using Docker Compose
How to test failover and verify the health of your replica set
How to insert data and ensure it replicates across all nodes
🙌 Found This Useful?
💡 Drop a comment below with any questions
💬 Share this with your team or on social media
🛠️ Follow me for more tutorials on Docker, MongoDB, and high availability setups!
Subscribe to my newsletter
Read articles from Loga Rajeshwaran Karthikeyan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by