MongoDB Replica Docker: Cannot connect on replica, only individual connection

The ports in your replicaset have to change too, to match the exposed ports. With a replicaset it is the config in the replica set that a client will connect to.

I prefer to use different ip’s and keep 27017 as the port.

My ports in compose look like:

ports extract docker-compose.yaml
services:
  mongo-0-a:
    ports:
    - 127.0.10.1:27017:27017
...
  mongo-0-b:
    ports:
    - 127.0.10.2:27017:27017
...
  mongo-0-c:
    ports:
    - 127.0.10.3:27017:27017
...
Full Compose for reference
version: '3.7'

services:
  mongo-0-a:
    image: mongo:4.4
    ports:
      - 127.0.10.1:27017:27017
    volumes:
      - mongo-0-a:/data/db
    restart: unless-stopped
    command: "--wiredTigerCacheSizeGB 0.25 --replSet rs0"

  mongo-0-b:
    image: mongo:4.4
    ports:
      - 127.0.10.2:27017:27017
    volumes:
      - mongo-0-b:/data/db
    restart: unless-stopped
    command: "--wiredTigerCacheSizeGB 0.25 --replSet rs0"

  mongo-0-c:
    image: mongo:4.4
    ports:
      - 127.0.10.3:27017:27017
    volumes:
      - mongo-0-c:/data/db
    restart: unless-stopped
    command: "--wiredTigerCacheSizeGB 0.25 --replSet rs0"
volumes:
  mongo-0-a:
  mongo-0-b:
  mongo-0-c:
/etc/hosts
...
127.0.10.1 mongo-0-a
127.0.10.2 mongo-0-b
127.0.10.3 mongo-0-c
...

This command on the secondary below returns the hosts of the replicaset a client must connect to. These hostnames must resolve and the ports have to match. This is why exposing on a different port to what is in the rs.conf() does not work.

ismaster() on secondary
mongo --host 127.0.10.2 --eval 'var m = db.isMaster(); print("Is Primary?", m.ismaster); print("hosts:", m.hosts); print("Primary:", m.primary)' --quiet
Is Primary? false
hosts: mongo-0-a:27017,mongo-0-b:27017,mongo-0-c:27017
Primary: mongo-0-c:27017

Connecting to replicaSet:

ReplicaSet Connect
mongo --host rs0/127.0.10.2 --quiet
2020-12-09T15:25:53.458-0500 I  NETWORK  [js] Starting new replica set monitor for rs0/127.0.10.2:27017
2020-12-09T15:25:53.458-0500 I  CONNPOOL [ReplicaSetMonitor-TaskExecutor] Connecting to 127.0.10.2:27017
2020-12-09T15:25:53.460-0500 I  CONNPOOL [ReplicaSetMonitor-TaskExecutor] Connecting to mongo-0-c:27017
2020-12-09T15:25:53.463-0500 I  NETWORK  [ReplicaSetMonitor-TaskExecutor] Confirmed replica set for rs0 is rs0/mongo-0-a:27017,mongo-0-b:27017,mongo-0-c:27017
2020-12-09T15:25:53.463-0500 I  CONNPOOL [ReplicaSetMonitor-TaskExecutor] Connecting to mongo-0-a:27017
2020-12-09T15:25:53.463-0500 I  CONNPOOL [ReplicaSetMonitor-TaskExecutor] Connecting to mongo-0-b:27017

2 Likes