我学习Kubernetes并尝试部署NodeJs应用程序。我如何将我的MongoDb数据库连接到后端清单文件?这是我的nodejs,即后台日志。
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
}
}
您的mongodb副本必须部署在可以从k8s集群访问的服务器上
之后,在配置中将mongodb副本的地址设置为这些服务器的ip(而不是127.0.0.1或localhost)
您可能还需要在k8s部署中设置出口规则,以允许出站流量到端口27017。
如果MongoDB在k8s集群中运行,请参考在nodejs应用程序中安装db时创建的MongoDB服务。
如果MongoDB运行在k8s集群之外,那么你可以创建ExternalName/service和相同的端点,并在应用程序中引用它。