How to access mongodb replicaset from inside kubernetes cluster?

Hi, I have deployed my MongoDB replicaset in Kubernetes in the following way

1 - Headless Service -

kind: Service
metadata:
  name: mongo
  labels:
    app: mongo
spec:
  ports:
  - name: mongo
    port: 27017
    targetPort: 27017
  clusterIP: None
  selector:
    app: mongo 

2 - MongoDB Replica Set

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: mongo
spec:
  selector:
    matchLabels:
      app: mongo
  serviceName: "mongo"
  replicas: 3
  template:
    metadata:
      labels:
        app: mongo
    spec:
      terminationGracePeriodSeconds: 10
      containers:
      - name: mongo
        image: mongo
        command:
        - mongod
        - "--bind_ip_all"
        - "--replSet"
        - rs0
        ports:
        - containerPort: 27017
        volumeMounts:
        - name: mongo-volume
          mountPath: /data/db
  volumeClaimTemplates:
  - metadata:
      name: mongo-volume
    spec:
      accessModes: [ "ReadWriteOnce" ]
      resources:
        requests:
          storage: 1Gi

Now, I see that there are three mongodb pods, mongo-0, mongo-1, mongo-2. I want my application to connect to all of these, just in case one of them goes down and the other one becomes the primary node. As of now, I am using

ENV MONGO_HOST mongo-0.mongo.mongodb.svc.cluster.local

But if I want to connect to all the members in the replicaset, how do I do it ? I tried using

#ENV MONGO_HOST mongo-0.mongo.mongodb.svc.cluster.local,mongo-1.mongo.mongodb.svc.cluster.local,mongo-2.mongo.mongodb.svc.cluster.local/?replicaSet=rs0

But it returns the error

pymongo.errors.ServerSelectionTimeoutError: No replica set members available for replica set name "rs0:27017"

Any help ??

Hi @Tushar_Sonawane1, and welcome to the forum!

Not entirely sure about your Kubernetes set up, but have you initiated the replica set?
See rs.initate() and also Deploy a Replica Set for more information.

You may also find Troubleshoot Replica Set guide to be a useful resource.

The error looks like related to an incorrect parsing, i.e. a concatenation between the replica set name and default port number. Please make sure that you’re passing a valid connection URI to MongoClient(). Please see PyMongo: making a connection with MongoClient for more information.

Regards,
Wan.