Google 使用 VPC 连接器的 App Engine 无法连接 MongoDB

Google App Engine using a VPC connector does not connect with MongoDB

当我在带有 VPC 连接器和 MongoDB 副本集的 Google App Engine 上部署 Python 应用程序时出现以下错误。

MongoDB 在 Google Compute Engine 上。

pymongo.errors.ServerSelectionTimeoutError: \
Could not reach any servers in [('mongodb-v44', 27017)]. \
Replica set is configured with internal hostnames or IPs?, \
Timeout: 30s, Topology Description: <TopologyDescription id: \ 
5ff5a4121251453cdcc1ff41, topology_type: ReplicaSetNoPrimary, \ 
servers: [<ServerDescription ('mongodb-v44', 27017) \ 
server_type: Unknown, \ 
rtt: None, error=AutoReconnect('mongodb-v44:27017: \
a [Errno -2] Name or service not known')>]>"

Python代码:

mongo_connection = mongoengine.connect(
    db=os.getenv('DB_NAME'),
    host=os.getenv('DB_HOST_URL'),
    port=int(os.getenv('DB_PORT')),
    username=os.getenv('DB_USERNAME'),
    password=os.getenv('DB_PASSWORD'),
    authentication_source='admin',
    replicaset=os.getenv('REPLICA_SET'),
    read_preference=ReadPreference.PRIMARY_PREFERRED
)

try:
    info = mongo_connection.server_info()  # Forces a call.
except Exception:
    raise Exception("mongo server is down.")

确保可以从应用程序访问副本集中成员的主机名。

步骤:

  1. 检查rs.config()

  2. 检查成员主机名cfg.members[0].host = FQDN

  3. 确保可以从应用程序访问 FQDN

要快速调试并解决问题,请在处理错误消息时尽可能明确。目前,您正在捕获“所有”Exception,这些反模式可能很难调试。

而不是使用一般的 Exception:

except Exception:
    raise Exception("mongo server is down.")

您可以通过某种方式捕获错误消息:

except Exception as err:
    print("MongoDB error:", err)

或者更好的是,您可以编写自己的 Exception 来改进调试:

class MongodbError(Exception):
    """Exception Base class"""
    pass

class ServerTimeoutError(MongodbError):
    pass

class MongoServerLostConnection(MongodbError):
    pass

try:
    do_something()
except MongodbError as err:
    manage_mongo_error(err)