What is wrong with this docker-compose file? It's supposed to create a MongoDB replica set

51 Views Asked by At

I just want to configure a MongoDB replica set for a local development environment and I have the following docker-compose file. Everything seems to initialise well but it seems that the container mongo-init-replica is not able to connect with the provided connection string. I understand that Docker Compose creates all the containers in the same network so they should be able to see each other.

This is the docker-compose.yml file:

version: '3'
services:
  redis:
    image: redis:latest
    container_name: redis
    ports:
      - "6379:6379"

  mongodb1:
    image: mongo:latest
    container_name: mongodb1
    ports:
      - "27017:27017"
    volumes:
      - ./data/db1:/data/db
    environment:
      - MONGO_INITDB_DATABASE=tennis
      - MONGO_REPLICA_SET_NAME=rs0
      - MONGO_PORT=27017
      - MONGO_PRIORITY=1
    command: ["mongod", "--replSet", "rs0", "--bind_ip_all"]

  mongodb2:
    image: mongo:latest
    container_name: mongodb2
    ports:
      - "27018:27017"
    volumes:
      - ./data/db2:/data/db
    environment:
      - MONGO_INITDB_DATABASE=tennis
      - MONGO_REPLICA_SET_NAME=rs0
      - MONGO_PORT=27017
      - MONGO_PRIORITY=0
    command: ["mongod", "--replSet", "rs0", "--bind_ip_all"]

  mongodb3:
    image: mongo:latest
    container_name: mongodb3
    ports:
      - "27019:27017"
    volumes:
      - ./data/db3:/data/db
    environment:
      - MONGO_INITDB_DATABASE=tennis
      - MONGO_REPLICA_SET_NAME=rs0
      - MONGO_PORT=27017
      - MONGO_PRIORITY=0
    command: ["mongod", "--replSet", "rs0", "--bind_ip_all"]

  mongo-init-replica:
    image: mongo:latest
    depends_on:
      - mongodb1
      - mongodb2
      - mongodb3
    volumes:
      - ./scripts:/scripts
    command: ["mongosh", "mongodb://mongodb1:27017,mongodb2:27017,mongodb3:27017/admin", "/scripts/init-replica.js"]

And this are the logs when the container mongo-init-replica is started:

Current Mongosh Log ID: 65c6bbfee1b8e4ee1e55263f
Connecting to:          mongodb://mongodb1:27017,mongodb2:27017,mongodb3:27017/admin?appName=mongosh+1.6.0
MongoServerSelectionError: Server selection timed out after 30000 ms

If I stop any of the mongodb1, mongodb2 or mongodb3 containers I get something like MongoServerSelectionError: getaddrinfo ENOTFOUND mongodb3

So it looks like it resolves the containers address but cannot establish a connection.

Any hint please?

Thanks in advance :)

1

There are 1 best solutions below

0
Neniel On

It looks like the following entry was missing in my /etc/hosts file:

127.0.0.1 mongodb1 mongodb2 mongodb3

That resolved the issue and I was able to configure the replica set :)