How do you run MongoDB as a replica set with Docker Compose for testing?
IntermediateHands-onMongoDB
Answer
Short answer
Start three mongod containers with the same --replSet name, then run rs.initiate() once with all three members. Apps connect with a connection string listing all members and the replicaSet parameter.
docker-compose.yml
services:
mongo1:
image: mongo:7
command: ["mongod", "--replSet", "rs0", "--bind_ip_all"]
ports: ["27017:27017"]
mongo2:
image: mongo:7
command: ["mongod", "--replSet", "rs0", "--bind_ip_all"]
mongo3:
image: mongo:7
command: ["mongod", "--replSet", "rs0", "--bind_ip_all"]
docker compose up -d
docker compose exec mongo1 mongosh --eval '
rs.initiate({ _id: "rs0", members: [
{ _id: 0, host: "mongo1:27017" }, { _id: 1, host: "mongo2:27017" }, { _id: 2, host: "mongo3:27017" } ] })'
docker compose exec mongo1 mongosh --eval 'rs.status().members.map(m => m.name + " " + m.stateStr)'
Test failover
docker compose stop mongo1 # primary goes away
docker compose exec mongo2 mongosh --eval 'rs.status().members.map(m => m.stateStr)' # a new PRIMARY
(For production you'd add auth with a keyFile, persistent volumes and TLS.)
What to say in the interview
"Three mongod containers with the same replSet name, rs.initiate with their hostnames, and a replicaSet connection string. Stopping the primary demonstrates automatic election. Production adds keyFile auth, volumes and TLS."