我有一个用于 Node.js 后端应用程序的 Kubernetes 本地集群,分为微服务。在一个 pod 上,我尝试用一个节点启动 MongoDB ReplicaSet,以便使用事务。 该项目仅用于学习目的,因此我只需要基本设置即可开始。 为了部署数据库,我配置了一个 Dockerfile,如下所示:
FROM mongo
COPY replica-init.js /docker-entrypoint-initdb.d/replica-init.js
CMD ["mongod", "--replSet", "rs0", "--bind_ip_all"]
文件replica-init.js只是这行代码:
rs.initiate();
然后,我在 kubernetes yaml 文件中将图像引用为 instagram-clone/profile-mongo:
apiVersion: apps/v1
kind: Deployment
metadata:
name: profile-mongo-depl
spec:
replicas: 1
selector:
matchLabels:
app: profile-mongo
template:
metadata:
labels:
app: profile-mongo
spec:
containers:
- name: profile-mongo
image: instagram-clone/profile-mongo
---
apiVersion: v1
kind: Service
metadata:
name: profile-mongo-cluster-ip
spec:
selector:
app: profile-mongo
ports:
- name: profile-mongo
protocol: TCP
port: 27017
targetPort: 27017
最后,在我的 index.js 文件中,我只需执行以下操作:
try {
await connect(process.env.LOCAL_DB_URL!);
console.log("Successully connected to the database.");
} catch (e) {
console.log("Couldn't connect to the database.", e);
}
ReplicaSet 正常启动,但微服务抛出以下错误:
MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
at _handleConnectionErrors (/usr/app/node_modules/mongoose/lib/connection.js:909:11)
at NativeConnection.openUri (/usr/app/node_modules/mongoose/lib/connection.js:860:11)
at init (/usr/app/src/server.ts:7:9) {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
servers: Map(1) { '127.0.0.1:27017' => [ServerDescription] },
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: 'rs0',
maxElectionId: new ObjectId('7fffffff0000000000000002'),
maxSetVersion: 1,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined
}
另外,在错误中看到 127.0.0.1:27017 是否正确?这不是微服务用于连接数据库的 cluster-ip 地址。
这是我尝试做的:
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "profile-mongo-cluster-ip:27017" }
]
});
我将链接我的 GitHub 存储库,以获取更多上下文。我正在处理的分支是 profile/enabling-transactions: https://github.com/davideaprea/Instagram-backend-clone/tree/profile/enabling-transactions 所有 yaml 文件都位于 infra 文件夹中。
我只需在 mongoose 的
connect函数中设置
directConnection: true
就可以解决这个问题,如下所示:
await connect(process.env.LOCAL_DB_URL!, {
directConnection: true,
replicaSet: "rs0",
});