Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Error: Unable to reach primary for set [set_name] when connect to mongo replica set

I'm trying to connect to MongoDB replica set consists of 3 mongo docker-container, but Error Message: Unable to reach primary for set rs0 occurs.

Git Repository: https://github.com/frontalnh/mongodb-replica-set

I made docker swarm consists of 3 MongoDB docker-container and map each port to localhost: 27017, 27018, 27019

Connecting to a single mongo docker-container is possible by below command

mongo localhost:27017

But When I try to connect to Replica set consists of 3 by below command,

Error Message: Unable to reach primary for set rs0 occurs

Command

mongo "mongodb://localhost:27017,localhost:27018,localhost:27019/testdb?replicaSet=rs0"

Configuration

cfg = {
  _id: 'rs0',
  members: [
    { _id: 0, host: 'mongo-rs0-1:27017' },
    { _id: 1, host: 'mongo-rs0-2:27017' },
    { _id: 2, host: 'mongo-rs0-3:27017' }
  ]
};
cfg.protocolVersion = 1;
rs.reconfig(cfg, { force: true });

Docker Compose

version: '3'

services:
  mongo-rs0-1:
    image: 'mongo-start'
    build: ./mongo-rs0-1
    ports:
      - '27017:27017' # left is computer's port right side is docker internal port
    volumes:
      - ./mongo-rs0-1/data:/data/db
    depends_on:
      - 'mongo-rs0-2'
      - 'mongo-rs0-3'

  mongo-rs0-2:
    image: 'mongo'
    command: --replSet rs0
    command: --config ./conf/mongo.conf
    ports:
      - '27018:27017'
    volumes:
      - ./mongo-rs0-2/data:/data/db
      - ./mongo-rs0-2/conf:/conf

  mongo-rs0-3:
    image: 'mongo'
    command: --replSet rs0
    command: --config ./conf/mongo.conf
    ports:
      - '27019:27017'
    volumes:
      - ./mongo-rs0-3/data:/data/db
      - ./mongo-rs0-2/conf:/conf

  setup-rs:
    image: 'setup-rs'
    build: ./setup
    depends_on:
      - 'mongo-rs0-1' # mongo-rs0-1 서비스가 실행중이어야 해당 서비스가 실행될 수 있다.

  adminmongo:
    image: 'mrvautin/adminmongo'
    ports:
      - '1234:1234'
like image 733
Namhoon Lee Avatar asked Oct 23 '18 01:10

Namhoon Lee


1 Answers

I solved it by register host name in localhost

Anyone who needs mongo replica set in localhost can setup replica set with docker-compose.

https://github.com/frontalnh/mongodb-replica-set

like image 150
Namhoon Lee Avatar answered Oct 21 '22 21:10

Namhoon Lee