mongodbHow to set up a MongoDB replica with Docker Compose?
Setting up a MongoDB replica with Docker Compose is a straightforward process.
- Create a
docker-compose.yml
file with the following content:
version: '3'
services:
mongo-primary:
image: mongo
ports:
- 27017:27017
volumes:
- ./data/primary:/data/db
command: mongod --replSet rs0
mongo-secondary:
image: mongo
ports:
- 27018:27017
volumes:
- ./data/secondary:/data/db
command: mongod --replSet rs0
-
Start the containers with
docker-compose up -d
-
Connect to the primary container with
docker exec -it mongo-primary mongo
-
Initialize the replica set with the following command:
rs.initiate(
{
_id: "rs0",
members: [
{ _id: 0, host: "mongo-primary:27017" },
{ _id: 1, host: "mongo-secondary:27017" }
]
}
)
- Verify the replica set is working with
rs.status()
Helpful links
Related
More of Mongodb
- How to use triggers in MongoDB?
- How to use unwind in MongoDB?
- How to list MongoDB users?
- How to rename a field in MongoDB?
- How to rename a MongoDB collection?
- What is MongoDB default port?
- How to convert MongoDB ObjectId to string?
- How to create a many to many relation in MongoDB?
- How to work with time series data in MongoDB?
- How to empty an array in MongoDB?
See more codes...