You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

部署在Kubernetes的MongoDB ReplicaSet无法连接(ReplicaSetNoPrimary错误)

问题:Kubernetes部署单节点MongoDB ReplicaSet后,Node.js微服务连接报错ECONNREFUSED 127.0.0.1:27017

我为Node.js后端微服务搭建了本地Kubernetes集群,为使用事务功能,在Pod中部署单节点MongoDB ReplicaSet(仅用于学习,只需基础启动配置)。

部署配置

MongoDB镜像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部署与Service配置

引用镜像为instagram-clone/profile-mongo,YAML内容如下:

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

Node.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是否正常?这并非微服务连接数据库使用的ClusterIP地址。

已尝试的操作

  • 在Dockerfile中暴露27017端口
  • 在mongoose的connect函数中设置ssl: false
  • 修改replica-init.js为以下配置:
rs.initiate({
  _id: "rs0", 
  members: [
    { _id: 0, host: "profile-mongo-cluster-ip:27017" }
  ]
});

内容的提问来源于stack exchange,提问作者Davide Aprea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 11:01:08