Reputation: 57
I have created a google cloud function in google cloud which will connect to my postgresql instance created in Google cloud.
I am using 'pg' node module.
I have create a private IP for this.
I am getting following error:
Error: Connection terminated due to connection timeout at Timeout.connectionTimeoutHandle.setTimeout (/workspace/node_modules/pg/lib/client.js:106:28) at ontimeout (timers.js:436:11) at tryOnTimeout (timers.js:300:5) at listOnTimeout (timers.js:263:5) at Timer.processTimers (timers.js:223:10)
when trying to query the database in google cloud.
This is my configuration which I am using in google cloud function.
{ "host": "", "user": "", "pw": "", "db": "<database_name>", "port": "5432", "table": "<table_name", "max": 100, "idleTimeoutMillis": 30000, "connectionTimeoutMillis": 30000 }
Please help me with this
Upvotes: 4
Views: 11522
Reputation: 633
Upgrading pg npm version resolved the issue.
"pg": "^7.3.0",
to
"pg": "^8.7.1",
If the issue still persists, then check your node version. Upgrade node to >=14.
Upvotes: 4
Reputation: 8074
According to the official documentation:
Connecting from Cloud Functions to Cloud SQL
To connect directly with private IP, you need to:
1.Make sure that the Cloud SQL instance created above has a private IP address. If you need to add one, see the Configuring private IP page for instructions.
2.Create a Serverless VPC Access connector in the same VPC network as your Cloud SQL instance. Unless you're using Shared VPC, a connector must be in the same project and region as the resource that uses it, but the connector can send traffic to resources in different regions.
3.Configure Cloud Functions to use the connector. Connect using your instance's private IP and port 5432.
4.Connect using your instance's private IP and port 5432
Also you can find the node js code to establish the connection to database:
const connectWithTcp = config => {
// Extract host and port from socket address
const dbSocketAddr = process.env.DB_HOST.split(':'); // e.g. '127.0.0.1:5432'
// Establish a connection to the database
return Knex({
client: 'pg',
connection: {
user: process.env.DB_USER, // e.g. 'my-user'
password: process.env.DB_PASS, // e.g. 'my-user-password'
database: process.env.DB_NAME, // e.g. 'my-database'
host: dbSocketAddr[0], // e.g. '127.0.0.1'
port: dbSocketAddr[1], // e.g. '5432'
},
// ... Specify additional properties here.
...config,
});
};
Upvotes: 1