Search code examples
postgresqlgoogle-cloud-platformgoogle-kubernetes-enginegoogle-cloud-sqlknex.js

GKE Cluster unable to connect to PG Cloud SQL instance using KnexJS


As a preface, I feel like I might be misunderstanding what GCP is indicating with its "App Engine authorization" being scoped to any app in the project, because despite entering in a proper postgres connection URL (postgresql://username:secret@SQL_PUBLIC_IP_ADDRESS:5432/DB_NAME), my GKE nodes are unable to connect.

I'm initiating the connection as such in my API;

knex({
  client: 'pg',
  connection: process.env.POSTGRES_URL.slice(0, -process.env.DATABASE_NAME.length),
  pool: { min: 0, max: 100 }
});

I've read quite a few medium posts and articles out there about connecting a Cloud SQL instance to a GKE cluster, but they all mention creating a VPC and connecting via Private IP on the Cloud SQL instance which seems to have been required prior to GCP defaulting authorization to any app in the project (??). This last point is where I feel like I might be mistaken, but most of these articles/questions seem to be from 1 year+ ago so it leads me to believe this might've been required previously, but not anymore.

Regardless, if I'm misunderstood on this presumption please let me know, otherwise, if you have any idea why I'm encountering this error any help would be greatly appreciated.


Solution

  • The problem was that the GKE clusters were private, and I was trying to connect to the instance via its public IP vs its private IP address.

    To resolve, I enabled private IPs on the SQL instance on the VPC network the GKE clusters are located in, and then changed out the SQL_PUBLIC_IP_ADDRESS value in the connection string to be the instance's private IP address. It now connects fine.

    Additional information from a similar issue. Connecting to public Cloud SQL from a private GKE cluster