【问题标题】:App Engine, pymongo.errors.ServerSelectionTimeoutError: connection closed,connection closed,connection closed"App Engine,pymongo.errors.ServerSelectionTimeoutError:连接关闭,连接关闭,连接关闭”
【发布时间】:2019-07-27 01:23:11
【问题描述】:

我正在使用 Python 3.7 和 Flask 1.0.2

我将我的应用程序插入到 mongoDB Atlas,并且在本地一切正常

client = pymongo.MongoClient(connector)

connector 是 Atlas 给我的标准连接字符串

connector = "mongodb://xxx:<PASSWORD>@xxcluster-shard-00-00-y0phk.gcp.mongodb.net:27017,xxcluster-shard-00-01-y0phk.gcp.mongodb.net:27017,xxxcluster-shard-00-02-y0phk.gcp.mongodb.net:27017/test?ssl=true&replicaSet=xxxCluster-shard-0&authSource=admin&retryWrites=true"

当我将我的应用部署到 Google App Engine 标准 Python3 运行时环境时,它不起作用。有人知道这个问题吗?

代码: Appengine 日志:

本地日志(在本地工作正常):

Appengine 错误:

pymongo.errors.ServerSelectionTimeoutError: 连接 关闭,连接关闭,连接关闭”

【问题讨论】:

    标签: python mongodb google-app-engine pymongo mongodb-atlas


    【解决方案1】:

    问题是 Ip 白名单,因此我通过 vpc 对等添加 与 gcp 的连接。

    为了简单起见,我们可以添加 0.0.0.0/0 以允许从任何地方访问(但是, 小心)

    .

    【讨论】:

    • 0.0.0.0/0 绝对有效。除了 VPC 对等外,还有什么更好(安全)的方式来处理这个问题?
    • 如果您的应用程序在 AWS 中,您还可以设置私有端点:docs.atlas.mongodb.com/security-private-endpoint
    • 我相信这个答案并没有对安全性提出警告。基本上这个解决方案是将数据库打开到互联网。
    【解决方案2】:

    我建议您使用VPC Peering feature of Atlas 在您的网络和 mongodb 集群的网络之间建立对等连接。更安全;)

    确保遵循Private only connection 的说明。为此,您需要通过添加 -pri 来调整 URI。

    例子:

    old_con = "mongodb://xxx:<PASSWORD>@xxcluster-shard-00-00-y0phk.gcp.mongodb.net:27017,xxcluster-shard-00-01-y0phk.gcp.mongodb.net:27017,xxxcluster-shard-00-02-y0phk.gcp.mongodb.net:27017/test?ssl=true&replicaSet=xxxCluster-shard-0&authSource=admin&retryWrites=true"
    new_con = "mongodb://xxx:<PASSWORD>@xxcluster-shard-00-00-y0phk-pri.gcp.mongodb.net:27017,xxcluster-shard-00-01-y0phk-pri.gcp.mongodb.net:27017,xxxcluster-shard-00-02-y0phk-pri.gcp.mongodb.net:27017/test?ssl=true&replicaSet=xxxCluster-shard-0&authSource=admin&retryWrites=true"
    

    【讨论】:

    • 这应该是这样,但我不得不暂时允许从任何地方访问 0.0.0.0/0 因为对等选项受到限制(功能在免费和共享层集群中不可用)根据doc
    • 明白了!我最近也遇到了这个问题。数小时的痛苦。在这种情况下,除非您将应用程序部署在您控制的虚拟机而不是 App Engine (cloud.google.com/appengine/kb#private-ip) 中,否则您将无法在 Atlas 中设置外部 IP 并将其列入白名单。就个人而言,如果应用程序连接到数据库,我不会使用 App Engine 将其公开到网络,除非它是为了快速 PoC/测试。
    【解决方案3】:

    就我而言,我有ssl=False。希望这对某人有帮助!

    【讨论】:

      【解决方案4】:

      问题可能是您的 MongoDB 白名单中的网络访问配置。 添加IP后,问题应该解决了。 请记住,IP 地址必须是 IPv4。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-26
        • 1970-01-01
        • 1970-01-01
        • 2013-05-31
        • 2019-01-04
        • 1970-01-01
        相关资源
        最近更新 更多