Set up a high-availability database with this guide on creating a docker compose mongodb replica set. Our Docker Team is always here to help you.
How to set up docker compose mongodb replica set
A MongoDB replica set ensures high availability by syncing data across multiple mongod instances. Only one node is primary at any given time for write operations. Secondary nodes replicate changes from the primary’s oplog. If the primary goes down, a new one is automatically elected.
In this quick guide, we’ll walk you through creating a docker compose mongodb replica set with three MongoDB containers. Here’s how to set up this step by step.
An Overview
Step 1: Docker Compose File
Create a docker-compose.yml file:
version: '3'
services:
mongodb-1:
image: mongo:latest
container_name: mongodb-1
ports:
- "27017:27017"
networks:
- replica-net
command: "--replSet rs0"
mongodb-2:
image: mongo:latest
container_name: mongodb-2
networks:
- replica-net
command: "--replSet rs0"
mongodb-3:
image: mongo:latest
container_name: mongodb-3
networks:
- replica-net
command: "--replSet rs0"
networks:
replica-net:
Copy Code
This defines three MongoDB containers and connects them on the same Docker network.
Step 2: Initiate the Replica Set
Enter the shell of mongodb-1:
docker exec -it mongodb-1 mongo
Copy Code
Inside the Mongo shell, run:
rs.initiate(
{
_id: "rs0",
members: [
{ _id: 0, host: "mongodb-1:27017" },
{ _id: 1, host: "mongodb-2:27017" },
{ _id: 2, host: "mongodb-3:27017" }
]
}
)
Copy Code
This sets up the mongodb replica set with three members.
Step 3: Start the Replica Set
Start the containers in the background:
docker-compose up -d
Copy Code
Step 4: Connect to Replica Set
Use the connection string below for your application:
mongodb://mongodb-1:27017,mongodb-2:27017,mongodb-3:27017/?replicaSet=rs0
Copy Code
This string ensures your app talks to the replica set correctly (cosmos-db-mongodb-error-code).
[If needed, Our team is available 24/7 for additional assistance.]
Conclusion
That’s all you need to spin up a reliable docker compose mongodb replica set. This setup works well with WordPress or any app that requires a fault-tolerant MongoDB backend. Connect MongoDB to cPanel. You can extend it with authentication, volume mounts, exclude specific collections during MongoDB backups, or monitoring as needed.
0 Comments