首页 > 解决方案 > GCP Kubernetes MongoDb statefulset 连接字符串 MongooseError getaddrinfo ENOTFOUND

问题描述

我正在按照以下教程将 MongoDB 配置为 GCP 上的 Kubernetes 集群中的状态集。

https://codelabs.developers.google.com/codelabs/cloud-mongodb-statefulset/index.html?index=..%2F..index#0

我可以使用“kubectl exec -ti mongo-0 mongo”访问数据库,如教程中所示。但是,我的 Node JS-Mongoose 应用程序无法连接到它并引发以下错误

MongoDB connection error: { MongooseError [MongooseServerSelectionError]: connect ECONNREFUSED 10.16.0.22:27017
    at new MongooseServerSelectionError (/usr/src/app/node_modules/mongoose/lib/error/serverSelection.js:24:11)
    at NativeConnection.Connection.openUri (/usr/src/app/node_modules/mongoose/lib/connection.js:823:32)
    at Mongoose.connect (/usr/src/app/node_modules/mongoose/lib/index.js:333:15)
    at Object.<anonymous> (/usr/src/app/app.js:6:10)
    at Module._compile (internal/modules/cjs/loader.js:816:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
    at Module.load (internal/modules/cjs/loader.js:685:32)
    at Function.Module._load (internal/modules/cjs/loader.js:620:12)
    at Function.Module.runMain (internal/modules/cjs/loader.js:877:12)
    at internal/main/run_main_module.js:21:11
  message: 'connect ECONNREFUSED 10.16.0.22:27017',
  name: 'MongooseServerSelectionError',
  reason:
   TopologyDescription {
     type: 'ReplicaSetNoPrimary',
     setName: null,
     maxSetVersion: null,
     maxElectionId: null,
     servers:
      Map {
        'mongo-0.mongo:27017' => [ServerDescription],
        'mongo-1.mongo:27017' => [ServerDescription],
        'mongo-2.mongo:27017' => [ServerDescription] },
     stale: false,
     compatible: true,
     compatibilityError: null,
     logicalSessionTimeoutMinutes: null,
     heartbeatFrequencyMS: 10000,
     localThresholdMS: 15,
     commonWireVersion: null },
  [Symbol(mongoErrorContextSymbol)]: {} }
(node:29) UnhandledPromiseRejectionWarning: MongooseServerSelectionError: connect ECONNREFUSED 10.16.0.22:27017
    at new MongooseServerSelectionError (/usr/src/app/node_modules/mongoose/lib/error/serverSelection.js:24:11)
    at NativeConnection.Connection.openUri (/usr/src/app/node_modules/mongoose/lib/connection.js:823:32)
    at Mongoose.connect (/usr/src/app/node_modules/mongoose/lib/index.js:333:15)
    at Object.<anonymous> (/usr/src/app/app.js:6:10)
    at Module._compile (internal/modules/cjs/loader.js:816:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
    at Module.load (internal/modules/cjs/loader.js:685:32)
    at Function.Module._load (internal/modules/cjs/loader.js:620:12)
    at Function.Module.runMain (internal/modules/cjs/loader.js:877:12)
    at internal/main/run_main_module.js:21:11
(node:29) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:29) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

app.js 连接代码如下

mongoose.connect(
  process.env.MONGO_CONNECTION_STRING,
  {
    useUnifiedTopology: true,
    useNewUrlParser: true,
  }
);
mongoose.Promise = global.Promise;
let db = mongoose.connection;
db.on("error", console.error.bind(console, "MongoDB connection error:"));

部署文件中的环境变量如下。

env:
  - name: MONGO_CONNECTION_STRING
    value: "mongodb://mongo-0.mongo,mongo-1.mongo,mongo-2.mongo:27017/test"

Mongo pod 状态

mongo-0                                         2/2     Running     0          8m35s
mongo-1                                         2/2     Running     0          7m49s
mongo-2                                         2/2     Running     0          6m54s

kubectl 获取状态集

NAME     READY   AGE
mongo    3/3     9m31s

服务

NAME                                  TYPE           CLUSTER-IP     EXTERNAL-IP     PORT(S)                      AGE
mongo                                 ClusterIP      None           <none>          27017/TCP                    27m

rs.config() 输出

{
    "_id" : "rs0",
    "version" : 1,
    "protocolVersion" : NumberLong(1),
    "members" : [
        {
            "_id" : 0,
            "host" : "mongo-0.mongo:27017",
            "arbiterOnly" : false,
            "buildIndexes" : true,
            "hidden" : false,
            "priority" : 1,
            "tags" : {
                
            },
            "slaveDelay" : NumberLong(0),
            "votes" : 1
        },
        {
            "_id" : 1,
            "host" : "mongo-1.mongo:27017",
            "arbiterOnly" : false,
            "buildIndexes" : true,
            "hidden" : false,
            "priority" : 1,
            "tags" : {
                
            },
            "slaveDelay" : NumberLong(0),
            "votes" : 1
        },
        {
            "_id" : 2,
            "host" : "mongo-2.mongo:27017",
            "arbiterOnly" : false,
            "buildIndexes" : true,
            "hidden" : false,
            "priority" : 1,
            "tags" : {
                
            },
            "slaveDelay" : NumberLong(0),
            "votes" : 1
        }
    ],
    "settings" : {
        "chainingAllowed" : true,
        "heartbeatIntervalMillis" : 2000,
        "heartbeatTimeoutSecs" : 10,
        "electionTimeoutMillis" : 10000,
        "catchUpTimeoutMillis" : 60000,
        "getLastErrorModes" : {
            
        },
        "getLastErrorDefaults" : {
            "w" : 1,
            "wtimeout" : 0
        },
        "replicaSetId" : ObjectId("5f16a0f3671c091fe183af72")
    }
}

任何帮助表示赞赏。

标签: mongodbmongoosekubernetes

解决方案


弄清楚了

教程缺少启动设置的步骤。

连接后使用命令设置

kubectl exec -ti mongo-0 mongo

只需运行以下两个命令

rs.initiate({_id: "rs0", version: 1, members: [
       { _id: 0, host : "mongo-0.mongo:27017" },
       { _id: 1, host : "mongo-1.mongo:27017" },
       { _id: 2, host : "mongo-2.mongo:27017" }
 ]});

rs.slaveOk()

推荐阅读