Failed to connect mongo-express to mongoDb in k8s

11/13/2021

I configured mongodb with user name and password, and deployed mongoDb and mongoDb express. The problem is that I'm getting the following error in mongo-express logs:

Could not connect to database using connectionString: mongodb://username:password@mongodb://lc-mongodb-service:27017:27017/"

I can see that the connection string contains 27017 port twice, and also "mongodb://" in the middle that should not be there.

This is my mongo-express deployment:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: lc-mongo-express
  labels:
    app: lc-mongo-express
spec:
  replicas: 1
  selector:
    matchLabels:
      app: lc-mongo-express
  template:
    metadata:
      labels:
        app: lc-mongo-express
    spec:
      containers:
      - name: lc-mongo-express
        image: mongo-express
        ports:
        - containerPort: 8081
        env:
        - name: ME_CONFIG_MONGODB_SERVER
          valueFrom: 
            configMapKeyRef:
              name: lc-configmap
              key: DATABASE_URL
        - name: ME_CONFIG_MONGODB_ADMINUSERNAME
          valueFrom:
            secretKeyRef:
              name: lc-secret
              key: MONGO_ROOT_USERNAME
        - name: ME_CONFIG_MONGODB_ADMINPASSWORD
          valueFrom:
            secretKeyRef:
              name: lc-secret
              key: MONGO_ROOT_PASSWORD
---
apiVersion: v1
kind: Service
metadata:
  name: lc-mongo-express-service
spec:
  selector:
    app: lc-mongo-express
  type: LoadBalancer  
  ports:
    - protocol: TCP
      port: 8081
      targetPort: 8081

And my mongoDb deployment:

---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: lc-mongodb-pvc
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
  volumeMode: Filesystem
  storageClassName: gp2
---
apiVersion: apps/v1
kind: StatefulSet
metadata: 
  name: lc-mongodb
  labels: 
    app: lc-mongodb
spec: 
  replicas: 1
  serviceName: lc-mongodb-service
  selector: 
    matchLabels: 
      app: lc-mongodb
  template: 
    metadata: 
      labels: 
        app: lc-mongodb
    spec: 
      volumes:
        - name: lc-mongodb-storage
          persistentVolumeClaim:
            claimName: lc-mongodb-pvc
      containers: 
        - name: lc-mongodb
          image: "mongo"
          ports: 
          - containerPort: 27017
          env:
          - name: MONGO_INITDB_ROOT_USERNAME
            valueFrom:
              secretKeyRef:
                name: lc-secret
                key: MONGO_ROOT_USERNAME
          - name: MONGO_INITDB_ROOT_PASSWORD
            valueFrom:
              secretKeyRef:
                name: lc-secret
                key: MONGO_ROOT_PASSWORD
          command:
          - mongod
          - --auth
          volumeMounts:
            - mountPath: '/data/db'
              name: lc-mongodb-storage
---
apiVersion: v1
kind: Service
metadata:
  name: lc-mongodb-service
  labels:
    name: lc-mongodb
spec:
  selector:
    app: lc-mongodb
  ports:
    - protocol: TCP
      port: 27017
      targetPort: 27017

What am I doing wrong?

-- Israel
connection-string
kubernetes
mongo-express
mongodb

1 Answer

11/13/2021

Your connection string format is wrong

You should be trying out something like

mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]

Now suppose if you are using the Node js

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@<Mongo service Name>/<Database name>?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
    // creating collection
    const collection = client.db("test").collection("devices");
    // perform actions on the collection object
    client.close();
});

also you missing the Db path args: ["--dbpath","/data/db"] in command while using the PVC and configuring the path

apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    app: mongo
  name: mongo
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mongo
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: mongo
    spec:
      containers:
      - image: mongo
        name: mongo
        args: ["--dbpath","/data/db"]
        livenessProbe:
          exec:
            command:
              - mongo
              - --disableImplicitSessions
              - --eval
              - "db.adminCommand('ping')"
          initialDelaySeconds: 30
          periodSeconds: 10
          timeoutSeconds: 5
          successThreshold: 1
          failureThreshold: 6
        readinessProbe:
          exec:
            command:
              - mongo
              - --disableImplicitSessions
              - --eval
              - "db.adminCommand('ping')"
          initialDelaySeconds: 30
          periodSeconds: 10
          timeoutSeconds: 5
          successThreshold: 1
          failureThreshold: 6
        env:
        - name: MONGO_INITDB_ROOT_USERNAME
          valueFrom:
            secretKeyRef:
              name: mongo-creds
              key: username
        - name: MONGO_INITDB_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mongo-creds
              key: password
        volumeMounts:
        - name: "mongo-data-dir"
          mountPath: "/data/db"
      volumes:
      - name: "mongo-data-dir"
        persistentVolumeClaim:
          claimName: "pvc"
-- Harsh Manvar
Source: StackOverflow