Home > Software design >  Spring MongoDB - How to connect to replica set?
Spring MongoDB - How to connect to replica set?

Time:03-09

I'm running locally a statefulset replica of MongoDB on Minikube and I'm trying to connect to this one using Spring Mongo DB.

In the configuration properties I have:

spring.data.mongodb.uri=mongodb://mongod-0.mongo:27017/test

The problem is that, when I try to deploy the application locally, I receive this error:

com.mongodb.MongoSocketException: mongod-0.mongo: Name or service not known

Looks like I can't enrich the deployed replica but I don't know why.

The statefulset, the service and the pods are running correctly.

Here is the configuration of them:

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: mongod
spec:
  serviceName: mongodb-service
  replicas: 1
  selector:
    matchLabels:
      role: mongo
  template:
    metadata:
      labels:
        role: mongo
        environment: test
        replicaset: MainRepSet
    spec:
      terminationGracePeriodSeconds: 10
      containers:
        - name: mongod-container
          image: mongo
          command:
            - "mongod"
            - "--bind_ip"
            - "0.0.0.0"
            - "--replSet"
            - "MainRepSet"
          resources:
            requests:
              cpu: 0.2
              memory: 200Mi
          ports:
            - containerPort: 27017
          volumeMounts:
            - name: mongodb-persistent-storage-claim
              mountPath: /data/db
  volumeClaimTemplates:
    - metadata:
        name: mongodb-persistent-storage-claim
        annotations:
          volume.beta.kubernetes.io/storage-class: "standard"
      spec:
        accessModes: [ "ReadWriteOnce" ]
        resources:
          requests:
            storage: 1Gi 
apiVersion: v1
kind: Service
metadata:
  name: mongodb-service
  labels:
    name: mongo
spec:
  ports:
    - port: 27017
      targetPort: 27017
  clusterIP: None
  selector:
    role: mongo

Someone has any idea how I could connect my application to the replica?

CodePudding user response:

it's due to your service name is : mongodb-service

You have to use always service name in connection strings everywhere mostly.

Traffic flow goes like :

Service -> deployment or statefulsets -> PODs

now you have exposed the service name and port(27017) and K8s will auto manage the service name into internal DNS, so you can use the name for the connection string.

Your application will be only able to connect on service name if running on the same K8s cluster.

Example :

spring.data.mongodb.uri=mongodb://mongo-service:27017/test

You can follow this article also for refrence. : https://medium.com/geekculture/how-to-deploy-spring-boot-and-mongodb-to-kubernetes-minikube-71c92c273d5e

  • Related