【问题标题】:Issues connecting to a Google Cloud SQL instance from Google Cloud Run从 Google Cloud Run 连接到 Google Cloud SQL 实例的问题
【发布时间】:2021-12-25 23:58:58
【问题描述】:

我有一个 postgresql Google Cloud SQL 实例,我正在尝试将在 Google Cloud Run 中运行的 FastAPI 应用程序连接到它,但是我收到了 ConnectionRefusedError: [Errno 111] Connection refused 错误。

我的应用程序使用databases 包进行异步数据库连接:

database = databases.Database(sqlalchemy_database_uri)

然后尝试通过以下方式在应用启动时连接:

@app.on_event("startup")
async def startup() -> None:
    if not database.is_connected:
        await database.connect() <--- this is where the error is raised

通过阅读文档here,它建议像这样形成连接字符串:

"postgresql+psycopg2://user:pass@/dbname?unix_sock=/cloudsql/PROJECT_ID:REGION:INSTANCE_NAME/.s.PGSQL.5432"

我尝试了几种不同的 url 变体,使用 host 而不是 unix_sock,就像 sqlalchemy docs 似乎暗示的那样,以及在最后删除 .s.PGSQL.5432,因为我已经看到了其他一些SO帖子建议,都无济于事。

我已将 Cloud SQL 连接添加到 Cloud Run 仪表板中的实例,并将 Cloud SQL 客户端角色添加到服务帐号。

我可以使用 Cloud SQL Auth 代理本地连接到数据库。

对于如何解决这个问题,甚至如何调试它,我有点不知所措,因为似乎没有任何简单的方法可以通过 ssh 进入容器并尝试一些事情。任何帮助将不胜感激,谢谢!

更新

我可以通过以下方式直接与 sqlalchemy 连接:

from sqlalchemy import create_engine
engine = create_engine(url)
engine.connect()

其中 url 是以下任何一种格式:

"postgresql://user:pass@/db_name?host=/cloudsql/PROJECT_ID:REGION:INSTANCE_NAME"
"postgresql+psycopg2://user:pass@/db_name?host=/cloudsql/PROJECT_ID:REGION:INSTANCE_NAME"
"postgresql+pg8000://user:pass@/db_name?unix_sock=/cloudsql/PROJECT_ID:REGION:INSTANCE_NAME/.s.PGSQL.5432"

是否有由于 databases 的异步特性导致的问题?

【问题讨论】:

  • 你的数据库有公网IP吗?
  • 是的@guillaumeblaquiere
  • 对不起,我有点困惑。为什么公共 IP 很重要?因为这应该是 Unix 套接字。

标签: postgresql google-cloud-platform sqlalchemy google-cloud-sql google-cloud-run


【解决方案1】:

原来这是databases 包的一个错误。现在应该用https://github.com/encode/databases/pull/423解决这个问题

【讨论】:

    猜你喜欢
    • 2019-09-16
    • 1970-01-01
    • 2019-10-28
    • 2020-11-20
    • 2021-07-18
    • 2020-05-27
    • 2020-11-05
    • 2020-02-23
    • 2021-02-12
    相关资源
    最近更新 更多