[英]How to connect to Google Cloud SQL (PostgreSQL) from Cloud Functions?
I feel like I've tried everything.我觉得我什么都试过了。 I have a cloud function that I am trying to connect to Cloud SQL (PostgreSQL engine).
我有一个云 function,我正在尝试连接到云 SQL(PostgreSQL 引擎)。 Before I do so, I pull connection string info from Secrets Manager, set that up in a credentials object, and call a pg (package) pool to run a database query.
在此之前,我从 Secrets Manager 中提取连接字符串信息,在凭据 object 中进行设置,然后调用 pg(包)池来运行数据库查询。
Below is my code: Credentials:下面是我的代码:凭据:
import { Pool } from 'pg';
const credentials: sqlCredentials = {
"host":"127.0.0.1",
"database":"myFirstDatabase",
"port":"5432",
"user":"postgres",
"password":"postgres1!"
}
const pool: Pool = new Pool(credentials);
await pool.query(`select CURRENT_DATE;`).catch(error => console.error(`error in pool.query: ${error}`));
Upon running the cloud function with this code, I get the following error:使用此代码运行云 function 后,出现以下错误:
error in pool.query: Error: connect ECONNREFUSED 127.0.0.1:5432
I have attempted to update the host to the private IP of the Cloud SQL instance, and also update the host to the Cloud SQL instance name on this environment, but that is to no avail.我已尝试将主机更新为 Cloud SQL 实例的私有 IP,并将主机更新为 Cloud SQL 实例名称,但在此环境下无效。 Any other ideas?
还有其他想法吗?
Through much tribulation, I figured out the answer.历经千辛万苦,终于找到了答案。 Given that there is NO documentation on how to solve this, I'm going to put the answer here in hopes that I can come back here in 2025 and see that it has helped hundreds.
鉴于没有关于如何解决这个问题的文档,我将把答案放在这里,希望我能在 2025 年回到这里,看看它已经帮助了数百人。 In fact, I'm setting a reminder in my phone right now to check this URL on November 24, 2025.
事实上,我现在正在手机中设置提醒,以便在 2025 年 11 月 24 日检查这个 URL。
Solution: The host must be set as:解决方法:主机必须设置为:
/cloudsql/<googleProjectName(notId)>:<region>:<sql instanceName>
Ending code:结束代码:
import { Pool } from 'pg';
const credentials: sqlCredentials = {
"host":"/cloudsql/my-first-project-191923:us-east1:my-first-cloudsql-inst",
"database":"myFirstDatabase",
"port":"5432",
"user":"postgres",
"password":"postgres1!"
}
const pool: Pool = new Pool(credentials);
await pool.query(`select CURRENT_DATE;`).catch(error => console.error(`error in pool.query: ${error}`));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.