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.