@Anusha_Reddy
Sorry I set you wrong. I read you were trying to connect to 127.0.0.1 and did the mental leap that was all you were trying to do… despite the topic.

  1. Do not run this as a production configuration. I mentioned it already but I will do so again. Replica sets are to provide redundancy and data availability. Running all the replicas on the same host counteracts the point of a replica set, an anti-pattern. The loss of this host is the loss of you data, temporarily or permanently. It is also very likely to be less performant due to contention for resources.
  2. If the replicaset is required for features such as change streams, you can initialize and run a replica set of one.

With that in mind and you still want to run a replicaset on one host…

  1. Replica set members and client must be able to resolve and connect to the members of the replicaset. Specifically the hostnames used to configure the replica set.
  2. With the fact that other hosts will connect to the replicaset use an alias/cname to point to the docker host where you will run the replicaset.
  3. Use this hostname for all members of the replicaset initialise.
  4. You will need a separate port for each member, use this as the port when you initialize the set or add a member.

Note: You will need to layer TLS and Authentication in.
I would mount another volume on each container for a configuration mount for Keys and a mongod.conf

Minimum viable compose
version: '3.9'

services:
  mongo-0-a:
    image: mongo:4.4
    ports:
      - 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:
      - 27117:27017
    volumes:
      - mongo-0-b:/data/db
    restart: unless-stopped
    command: "--wiredTigerCacheSizeGB 0.25 --replSet rs0"

  mongo-0-c:
    image: mongo:4.4
    ports:
      - 27217: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:
rs.initiate
rs.initiate(
  { 
    "_id" : "rs0",
    "members" : [
      { 
        "_id" : 0,
        "host" : "this-laptop.domain:27017"
      },
      { 
        "_id" : 1,
        "host" : "this-laptop.domain:27117"
      },
      { 
        "_id" : 2,
        "host" : "this-laptop.domain:27217"
      }
    ]
  }
)
Connect from another host

mongo “mongodb://this-laptop.domain:27217/admin?replicaSet=rs0” --quiet
Welcome to the MongoDB shell.
For interactive help, type “help”.
For more comprehensive documentation, see
https://docs.mongodb.com/
Questions? Try the MongoDB Developer Community Forums
MongoDB Developer Community Forums - A place to discover, learn, and grow with MongoDB technologies
rs0:PRIMARY> db.isMaster().hosts
[
“this-laptop.domain:27017”,
“this-laptop.domain:27117”,
“this-laptop.domain:27217”

3 Likes