Configure replica set with docker

Hi, i am struggling to get my replica set running by using docker.
I am just not able to get a connection but my replica set seems to be setup correctly.

Did i miss something? Please see my compose.

version: '3.8'

services:
  mongo1:
    container_name: mongo1
    hostname: mongo1
    image: mongo:6.0.3
    expose:
      - 27017
    ports:
      - 30001:27017
    restart: always
    networks:
      - my-db
    command: mongod --replSet myrs
  mongo2:
    container_name: mongo2
    hostname: mongo2
    image: mongo:6.0.3
    expose:
      - 27017
    ports:
      - 30002:27017
    restart: always
    networks:
      - my-db
    command: mongod --replSet myrs
  mongo3:
    container_name: mongo3
    hostname: mongo3
    image: mongo:6.0.3
    expose:
      - 27017
    ports:
      - 30003:27017
    restart: always
    networks:
      - my-db
    command: mongod --replSet myrs

  mongoinit:
    container_name: mongoinit
    image: mongo:6.0.3
    restart: "no"
    networks:
      - my-db
    depends_on:
      - mongo1
      - mongo2
      - mongo3
    command: >
      mongosh --host mongo1:27017 --eval  ' db = (new Mongo("localhost:27017")).getDB("myDb"); config = { "_id" : "myrs", "members" : [
        {
          "_id" : 0,
          "host" : "mongo1:27017"
        },
        {
          "_id" : 1,
          "host" : "mongo2:27017"
        },
        {
          "_id" : 2,
          "host" : "mongo3:27017"
        }
      ] }; rs.initiate(config); '      


networks:
  my-db:
    driver: bridge

mongoinit does not part of the cluster, so you should have it in another file which also would immediately show you the problem:

mongoinit  | MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017
mongoinit exited with code 1

When you run mongo/mongosh, everything you do will basically belong to the host you run it, and functions are responsible to direct command to the db server.

Here in this new Mongo("localhost:27017") command, localhost is the mongoinit machine. just as you give it as a parameter to the mongo shell, you need to write, for example, new Mongo("mongo1:27017")

or remove that part completely. you just need to log in to one of the members, which you are already doing by mongosh --host mongo1:27017. besides, you do not even use db if you look closely.


PS: I suggest to have cluster.yaml for 3 members, and cluster-init.yaml for initializing and other works if needed.

1 Like

Thanks Sir, this made my day.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.