-1

I am trying to connect to the default mongo image in Kubernetes, I am running Desktop docker for windows, below is the YAML configuration for the mongo service which I am using in the server code to connect.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: auth-mongo-depl
spec:
  replicas: 1
  selector:
    matchLabels:
      app: auth-mongo
  template:
    metadata:
      labels:
        app: auth-mongo
    spec:
      containers:
        - name: auth-mongo
          image: mongo
---
apiVersion: v1
kind: Service
metadata:
  name: auth-mongo-srv
spec:
  selector:
    app: auth-mongo
  ports:
    - name: db
      protocol: TCP
      port: 27017
      targetPort: 27107

Trying to connect to the Kubernetes instance through the below code

import express from 'express'
import { json } from 'body-parser'
import mongoose from 'mongoose'
const app = express()
app.use(json())

const start = async () => {
  console.log('Starting servers...!')
  try {
    await mongoose.connect('mongodb://auth-mongo-srv:27017/auth', {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useCreateIndex: true
    })
    console.log('Connected to MongoDB !')
  } catch (err) {
    console.log(err)
  }
  app.listen(3000, () => {
    console.log('Listening on port :3000 !')
  })
}

start()

Services and pods details

PS D:\auth> kubectl get service

NAME             TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)     AGE  
auth-mongo-srv   ClusterIP   10.103.93.74   <none>        27017/TCP   5h27m
auth-srv         ClusterIP   10.101.151.7   <none>        3000/TCP    5h27m
kubernetes       ClusterIP   10.96.0.1      <none>        443/TCP     17h  


PS D:\auth> kubectl get ep auth-mongo-srv 

NAME             ENDPOINTS         AGE
auth-mongo-srv   10.1.0.15:27107   5h28m

getting below errors

 MongooseServerSelectionError: connect ECONNREFUSED 10.103.93.74:27017
     at NativeConnection.Connection.openUri (/app/node_modules/mongoose/lib/connection.js:846:32)
     at /app/node_modules/mongoose/lib/index.js:351:10
     at /app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5
     at new Promise (<anonymous>)
     at promiseOrCallback (/app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)
     at Mongoose._promiseOrCallback (/app/node_modules/mongoose/lib/index.js:1149:10)
     at Mongoose.connect (/app/node_modules/mongoose/lib/index.js:350:20)
     at /app/src/index.ts:28:20
     at step (/app/src/index.ts:33:23)
     at Object.next (/app/src/index.ts:14:53)
     at /app/src/index.ts:8:71
     at new Promise (<anonymous>)
     at __awaiter (/app/src/index.ts:4:12)
     at start (/app/src/index.ts:25:15)
     at Object.<anonymous> (/app/src/index.ts:43:1)
     at Module._compile (node:internal/modules/cjs/loader:1109:14) {
   reason: TopologyDescription {
     type: 'Single',
     setName: null,
     maxSetVersion: null,
     maxElectionId: null,
     servers: Map(1) { 'auth-mongo-srv:27017' => [ServerDescription] },
     stale: false,
     compatible: true,
     compatibilityError: null,
     logicalSessionTimeoutMinutes: null,
     heartbeatFrequencyMS: 10000,
     localThresholdMS: 15,
     commonWireVersion: null
   }

Do I need to run the Mongo DB service locally to connect to the Kubernetes mongo image? Below image is the Docker and Kubernetes versions.

enter image description here

Rahul Gupta
  • 69
  • 2
  • 14
  • Check the logs of your MongoDB pod. Also, I'm pretty sure you should use StatefulSet instead. – Riwen Jun 09 '21 at 08:19
  • @Riwen, can you let me know where can I find the logs for the pods? I have updated the pods and services running status in the question have a look. – Rahul Gupta Jun 09 '21 at 08:23
  • Try `kubectl get pods` and then `kubectl logs `. – Riwen Jun 09 '21 at 09:05
  • use the mongo db statefulsets image along with the open container port in deployment. ports: - containerPort: 27017 – Harsh Manvar Jun 09 '21 at 09:06
  • 1
    The `targetPort:` in your Service is 27107, not 27017. Is that a copy-and-paste error in your question? It could cause this problem. – David Maze Jun 09 '21 at 10:16
  • 1
    @DavidMaze, Thanks for pointing out that is the one that was causing the issue a simple typo issue. – Rahul Gupta Jun 09 '21 at 13:40

1 Answers1

0

Please use the container port to in stateful set or deployment to open the port.

Deployment example :

apiVersion: v1
kind: Service
metadata:
  name: mongo
  labels:
    app: mongo
spec:
  type: LoadBalancer
  ports:
  - port: 27017
    name: http
  selector:
    app: mongo
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: mongo
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mongo
  template:
    metadata:
      labels:
        app: mongo
        version: v1
    spec:
      containers:
        - name: mongo
          image: mongo:latest
          ports:
          - containerPort: 27017

statefulsets example :

apiVersion: apps/v1beta1
kind: StatefulSet
metadata:
  name: mongo
  app: mongodb
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: mongodb
    spec:
      terminationGracePeriodSeconds: 10
      containers:
        - name: mongo
          image: mongo
          command:
            - mongod
            - "--replSet"
            - rs0
            - "--smallfiles"
            - "--noprealloc"
          ports:
            - containerPort: 27017
          volumeMounts:
            - name: mongo-persistent-volume
              mountPath: /data/db
  volumeClaimTemplates:
  - metadata:
      name: mongo-persistent-volume
    spec:
      accessModes: [ "ReadWriteOnce" ]
      resources:
        requests:
          storage: 5Gi

here is an example statefulset for mongo db.

Harsh Manvar
  • 27,020
  • 6
  • 48
  • 102