Can't change replicaset port in Docker

My docker-compose:

version: '3.6'

services:
  mongodb:
    image: mongo
    command: --replSet rs0
    restart: unless-stopped
    ports:
      - 27017:27017
    environment:
      - MONGO_INITDB_DATABASE=shadow
    volumes:
      - mongodb:/data/db
      - mongoconfig:/data/configdb
      - ./initdb.js:/docker-entrypoint-initdb.d/initdb.js:ro

volumes:
  mongodb:
  mongoconfig:

And initdb.js:

rs.initiate(
  {
    _id: 'rs0',
    members: [{ _id: 0, host: '127.0.0.1:27017' }]
  },
  { force: true }
);

When I map any other port in (Ex: - 27018:27017) in compose, I can no longer connect to the DB.
In compass it says “ECONNREFUSED 127.0.0.1:27017” which is the docker port so it somehow resolves to that even though I entered 27018.

If I change any ip/port in the initdb.js, I get “No host described in new configuration with {version: 1, term: 0} for replica set rs0 maps to this node”

@Dedicated_Server Clients by default tries to discover all the members of the replicaset , so it doesnot consider the port mentioned . If you want client to connect to port mentioned in the connection string . Try forcing with directConnection flag

So in your connection string should look like

mongodb://localhost:27018/?directConnection=true

Reference :

Thanks! I thought ?replicaSet= was required to connect and get change events, but it seems to work with direct connect too.

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