I learning Kubernetes and trying to deploy NodeJs app. How can I connect my MongoDb database to backend manifest files? this is my nodejs i.e. backend logs.
root@ip-172-31-26-165:/home/ubuntu# kubectl logs backend-59666ccd6b-ltbbs
Server is running on port: 3000
MongoDB connection failed!!! MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
at Connection.openUri (/app/node_modules/mongoose/lib/connection.js:847:32)
at Mongoose.createConnection (/app/node_modules/mongoose/lib/index.js:291:17)
at connectDB (/app/config/database/mongodb.js:5:14)
at Object.<anonymous> (/app/config/database/mongodb.js:13:29)
at Module._compile (node:internal/modules/cjs/loader:1112:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1166:10)
at Module.load (node:internal/modules/cjs/loader:988:32)
at Module._load (node:internal/modules/cjs/loader:834:12)
at Module.require (node:internal/modules/cjs/loader:1012:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (/app/server.js:4:17)
at Module._compile (node:internal/modules/cjs/loader:1112:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1166:10)
at Module.load (node:internal/modules/cjs/loader:988:32)
at Module._load (node:internal/modules/cjs/loader:834:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12) {
reason: TopologyDescription {
type: 'Single',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map(1) { 'localhost:27017' => [ServerDescription] },
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null
}
}
2
Answers
Your mongodb replica(s) must be deployed on server(s), which are reachable from the k8s cluster.
After that, you set the address(es) of the mongodb replica(s) in your config to those servers IPs (not 127.0.0.1 or localhost)
You might also need an egress rule in the k8s deployment to allow outgoing traffic to port 27017.
If MongoDB is running within k8s cluster please refer the mongodb service which would have been created during db install inside your nodesjs application.
If MongoDB is running outside the k8s cluster then you can create ExternalName/ service and endpoint of the same and refer it in application.