Issue Connecting to Cloud SQL Postgres using Private IP from GKE

google-cloud-platformgoogle-cloud-sqlgoogle-kubernetes-enginevpc-peering

Steps I have followed:

1. Create VPC network


gcloud compute networks create stg-vpc \
--subnet-mode custom

2. Create IP range for VPC Peering for this network


gcloud beta compute addresses create google-managed-services-stg-vpc \
--global \
--purpose=VPC_PEERING \
--description="peering range for psql" \
--addresses=10.20.0.0 \
--prefix-length=16 \
--network=stg-vpc

3. Assign Private IP to Cloud SQL Postgres Instance

In the Cloud SQL Web Console I create a new Postgres instance. In Connectivity options I enable Private IP, and configure it to stg-vpc with the IP range google-managed-services-stg-vpc.

This creates Cloud SQL Postgres instance with IP 10.20.0.3.

4. Create a subnetwork for GKE cluster


gcloud compute networks subnets create stg-vpc-us-central1 \
--network stg-vpc \
--region us-central1 \
--range 10.10.0.0/16

5. Create GKE cluster and deploy application that connects to DB in Cloud SQL


gcloud -q container clusters create cluster-1 \
--zone us-central1-a \
--num-nodes 3 \
--network stg-vpc \
--subnetwork stg-vpc-us-central1

I deploy a Java application that connects to the Private IP of the Cloud SQL DB instance using Postgres JDBC driver. I get the error java.net.SocketTimeoutException: connect timed out.

I also tried the additional steps:

  1. I created a firewall rule to open the Postgres port for the IP range: gcloud compute firewall-rules create psql-access --network stg-vpc --allow tcp:5432 --source-ranges 10.20.0.0/16.
  2. I was able to ping from inside the docker container to the K8s host machines, but not to the Postgres instance.

Can anyone suggest what I'm doing wrong, and why the VPC peering is not working.

Best Answer

I was able to connect to Cloud SQL Postgres by creating a VPC-native cluster as suggested by @patrick-w.

My VPC subnetwork creation was modified to include two secondary ranges:

gcloud compute networks subnets create stg-vpc-us-central1 \ --network stg-vpc \ --region us-central1 \ --range 10.10.0.0/16 \ --secondary-range stg-vpc-us-central1-pods=10.11.0.0/16,stg-vpc-us-central1-services=10.12.0.0/16

And my cluster creation command was modified to enable ip-alias, and added details of the secondary ranges to use.

gcloud -q container clusters create cluster-1 \ --zone us-central1-a \ --num-nodes 3 \ --enable-ip-alias \ --network stg-vpc \ --subnetwork stg-vpc-us-central1 \ --cluster-secondary-range-name stg-vpc-us-central1-pods \ --services-secondary-range-name stg-vpc-us-central1-services

Related Topic