I am using Windows 10. I followed this process:
- Write a
docker-compose.yml
file:
version: '3.9'
services:
mongo1:
image: mongo:6
container_name: mongo1
command: --replSet my-replica-set
ports:
- 27017:27017
networks:
- mongo-network
mongo2:
image: mongo:6
container_name: mongo2
command: --replSet my-replica-set
ports:
- 27018:27017
networks:
- mongo-network
mongo3:
image: mongo:6
container_name: mongo3
command: --replSet my-replica-set
ports:
- 27019:27017
networks:
- mongo-network
networks:
mongo-network:
driver: bridge
- Run it using
docker-compose up -d
. - Initialize the replica set.
docker exec -it mongo1 mongosh --eval "rs.initiate({ _id: "myReplicaSet", members: [ {_id: 0, host: "mongo1"}, {_id: 1, host: "mongo2"}, {_id: 2, host: "mongo3"} ] })"
- Evaluate.
docker exec -it mongo1 mongosh --eval "rs.status()"
- Populate some data.
docker exec -it mongo1 mongosh
and
db.myCollection.insertOne({name: "John Doe", age: 30})
This creates on “test” database a collection named “myCollection” and adds some data. Finally I exit the app by typing exit
.
- I try to connect to the replication database using MongoDB Compass with this URI:
Does not work:
mongodb://127.0.0.1:27017,127.0.0.1:27018,127.0.0.1:27019/?replicaSet=my-replica-set
Works
mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.8.2
The issue: The main idea was to create a replication cluster, where I can stop the main container from running, so that the new primary source would be elected from the remaining two sources. If I do that and run:
docker exec -it mongo2 mongosh --eval "rs.status()"
I indeed get the answer, that mongo1 container has stopped working and mongo2 is now the primary, while mongo3 is the secondary. HOWEVER, MongoDB Compass stops working, because I used a direct connection to access the database and it does not understand, that a new database has been elected as the primary.
According to all the articles, I should be using this URI:
mongodb://127.0.0.1:27017,127.0.0.1:27018,127.0.0.1:27019/?replicaSet=my-replica-set
But it just does not work. It always throws this error:
getaddrinfo ENOTFOUND mongo1
Please help.