【问题标题】:connecting to mongodb replicaSet with nestjs and typeorm is not working使用nestjs和typeorm连接到mongodb副本集不起作用
【发布时间】:2022-03-11 19:44:21
【问题描述】:

问题

我正在尝试使用 nestjs(^8.2.3) 和 typeorm(^0.2.28) 连接到 mongodb 在测试环境中,连接到 mongodb 独立服务器正在工作。供您参考,node mongodb 库版本为 ^3.6.2。

生产示例代码(nestjs 服务器)

我提到了typeorm code 来编写 mongodb 选项

import { TypeOrmModule } from '@nestjs/typeorm';
import { MongoConnectionOptions } from 'typeorm/driver/mongodb/MongoConnectionOptions';

export const configForOrmModule = TypeOrmModule.forRootAsync({
  imports: [],
  useFactory: async () => {
    const mongodbConfig: MongoConnectionOptions = {
      type: 'mongodb',
      username,
      // for replicaSet (production)
      hostReplicaSet: 'server1.example.com:20723,server2.example.com:20723,server.example.com:20723',       
      replicaSet: 'replicaSetName'
      port: Number(port),
      password: encodeURIComponent(password),
      database,
      authSource,
      synchronize: true,
      useUnifiedTopology: true,
      entities: [Something],
    };

    return mongodbConfig;
  },
  inject: [],
});

但是在生产环境中,当nestjs服务器尝试连接mongodb副本集时,服务器一遍又一遍地得到这个服务器选择循环错误消息,如下所示。有趣的是服务器尝试连接的域与replicaSet主机不同(例如another-hostname不包括在server1.example.com:20723,server2.example.com:20723,server.example.com:20723中)。 (+ 编辑:另一个主机名是由 dns(server.example.com) 指示的实际物理服务器

 [39m01/28/2022, 2:39:16 AM [31m  ERROR[39m [38;5;3m[TypeOrmModule] [39m[31mUnable to connect to the database. Retrying (3)...[39m
MongoServerSelectionError: getaddrinfo ENOTFOUND <another-hostname>
    at Timeout._onTimeout (/home/node/app/node_modules/mongodb/lib/core/sdam/topology.js:430:30)
    at listOnTimeout (node:internal/timers:557:17)
    at processTimers (node:internal/timers:500:7)

我试过了,但这些都不起作用

  1. 删除useUnifiedTopology: true选项
  2. mongodb 库版本降级到 3.5.11(我在 mongodb 社区读到 3.6 版本之后的拓扑存在一些错误)
  3. 使用主机选项而不是 hostReplicaSet

如果您需要更多信息,请告诉我。谢谢你的帮助。

【问题讨论】:

    标签: mongodb nestjs typeorm


    【解决方案1】:

    这是 kubernates DNS 问题。 hostReplicaSet server1.example.com:20723,... 被解析为host1(物理服务器名称。没有example.com)但是,k8s 不知道它。所以连接失败。

    有两种选择

    1. 更新 kubernates /etc/hosts 设置以添加 host1 -> host1.example.com
    2. 或更新 mongodb 主机名 host1 -> host1.example.com

    【讨论】:

      猜你喜欢
      • 2013-11-02
      • 1970-01-01
      • 2020-01-25
      • 2021-12-03
      • 2020-12-20
      • 2015-06-26
      • 1970-01-01
      • 2013-05-25
      • 1970-01-01
      相关资源
      最近更新 更多