Getting error "getaddrinfo ENOTFOUND mongo1" when trying to reach replication cluster on Docker through MongoDB Compass on Windows 10

I am using Windows 10. I followed this process:

  1. 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
  1. Run it using docker-compose up -d.
  2. 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"} ] })"
  1. Evaluate.
docker exec -it mongo1 mongosh --eval "rs.status()"
  1. 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.

  1. 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.

Really this comes down to the docker networking namespace and being able to resolve the hostnames. It also relates to the replicaset discovery when a client connects, the hostnames and ports returned by db.hello() is what the client will try and connect to.

This would work if it wasn’t for docker. If you had multiple mongod on your local environment for example.

This is how I have have run a replset in docker and be able to connect from a local application.

1 Like