James Willian
James Willian

Reputation: 61

Connection refused: In connecting Google cloud postgresql with Cloud Function

I am trying to connect google cloud sql instance with cloud function written in python.

global pg_pool, pg_pool_db_name
pg_config = {
    'user': CONNECTION_DATA[dbname]['DB_USER'],
    'password': CONNECTION_DATA[dbname]['DB_PASSWORD'],
    'host': host,
    'dbname': dbname
}

pg_pool = ThreadedConnectionPool(1, 1, **pg_config)

This function test call failed and it outputs error message:

Error: function terminated. Recommended action: inspect logs for termination reason. Details:could not connect to server: Connection refused
Is the server running locally and accepting
connections on Unix domain socket "/cloudsql/my_instance_name/.s.PGSQL.5432"?

Anybody experienced on this kind of situation.

Upvotes: 1

Views: 1094

Answers (1)

marian.vladoi
marian.vladoi

Reputation: 8056

I wrote a tutorial about Connect from google cloud functions to Cloud SQL

9.Create a service account for your cloud function. Ensure that the service account for your service has the following IAM roles: Cloud SQL Client, and for connecting from Cloud Functions to Cloud Sql on internal ip we need also the role Compute Network User.

    gcloud iam service-accounts create cloud-function-to-sql
    gcloud projects add-iam-policy-binding gcf-to-sql --member serviceAccount:[email protected]   --role roles/cloudsql.client
    gcloud projects add-iam-policy-binding gcf-to-sql --member serviceAccount:[email protected]  --role roles/compute.networkUser

Then deploy the function using the service account you just created:

2.Deploy the cloud function:

    gcloud beta functions deploy gcf_to_sql --runtime python37 --region europe-west2 --service-account cloud-function-to-sql  --trigger-http
 

EDIT

Please read this documentation:

1.Creating a service account

2.Granting roles to service accounts

3.Deploying Cloud function from Cloud Console

Click More to display advanced options, such as setting a region, specifying a timeout, or adding environment variables

On Advanced options, choose the service account you just created.

Upvotes: 2

Related Questions