Databases 6 min read

How to Build a MongoDB Replica Set with Docker: Step‑by‑Step Guide

This tutorial shows how to create a three‑node MongoDB replica set using Docker, configure automatic primary election, verify data synchronization across secondaries, and simulate a primary failure to observe failover, providing a practical guide for high‑availability database deployments.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
How to Build a MongoDB Replica Set with Docker: Step‑by‑Step Guide

Overview

MongoDB replica sets consist of one Primary node and multiple Secondary nodes. Clients write to the Primary, and Secondaries automatically sync data from it, ensuring identical data across members and providing high availability. The Primary is elected automatically, and if it fails, a new Primary is chosen from the Secondaries.

Prerequisites

Install Docker and pull the MongoDB image: docker pull mongo Using a Docker registry accelerator (e.g., Alibaba Cloud or DaoCloud) is recommended.

Configuration Process

Create a dedicated Docker network and launch three MongoDB containers (mongo1, mongo2, mongo3) that will become the replica set members.

Create Docker Network

docker network create mongo-cluster

Verify the network:

docker network ls

Start Containers

Run the first container:

docker run -d \
  -p 30001:27017 \
  --name mongo1 \
  --net mongo-cluster \
  mongo mongod --replSet mongo-repliset

Explanation:

docker run – start a container from the image

-p 30001:27017 – map container port 27017 to host port 30001

--name mongo1 – name the container

--net mongo-cluster – attach to the created network

mongo – image name

mongod --replSet mongo-repliset – start mongod with replica set name

Run the other two containers:

docker run -d -p 30002:27017 --name mongo2 --net mongo-cluster mongo mongod --replSet mongo-repliset
docker run -d -p 30003:27017 --name mongo3 --net mongo-cluster mongo mongod --replSet mongo-repliset

Check running containers:

docker ps

Initialize Replica Set

Enter the shell of any container (e.g., mongo1): docker exec -it mongo1 mongo Create the replica set configuration:

{
  "_id": "mongo-repliset",
  "members": [
    { "_id": 0, "host": "mongo1:27017" },
    { "_id": 1, "host": "mongo2:27017" },
    { "_id": 2, "host": "mongo3:27017" }
  ]
}

Initialize with:

rs.initiate(config)

The shell prompt changes, indicating a connection to the Primary node.

Testing

Data Synchronization

Insert a document into the Primary:

db.mycollection.insert({name : 'sample'})

Query the collection on the Primary:

db.mycollection.find()

Switch to a Secondary (mongo2) and enable reads:

docker exec -it mongo2 mongo
db = (new Mongo('localhost:27017')).getDB('test')
db.setSlaveOk()
db.mycollection.find()

The document is present on mongo2, confirming replication. The same check can be performed on mongo3.

Simulating Primary Failure

Stop the Primary container (mongo1):

docker stop mongo1

Only mongo2 and mongo3 remain. After logging into their shells, you can see that mongo3 has been elected as the new Primary.

The replica set continues to operate with the new Primary, demonstrating automatic failover.

Conclusion

The MongoDB replica set has been successfully configured using Docker, providing high availability and automatic data replication across nodes.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Dockerdatabasehigh availabilityReplicationMongoDBReplica Set
Java High-Performance Architecture
Written by

Java High-Performance Architecture

Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.