Not able to connect to SQL in Google Cloud

7/17/2019

I am not able to connect to Cloud SQL in GCP, My spring boot application is hosted in Google Kubernetes, I am able to connect my application to database from my local but when I deploy my application image in kubernetes it doesnt work I checked the logs and got this

{
insertId:  "s=5ae000c9c858402ba514b2f9a2a7d34d;i=557f;    b=fef2848a05ed422b811cda756eea59d6;m=2a5164d50;t=58dde1640752b;  x=4a97c620c9fbf136-0@aa"  
logName:  "projects/finomatic  /logs/cloudsql.googleapis.com%2Fmysql.err"  
receiveTimestamp:  "2019-07-17T10:38:04.977705316Z"  
resource: {…}  
severity:  "INFO"  
textPayload:  "2019-07-17T10:37:59.135897Z 1340 [Note] Aborted  connection 1340 to db: 'finomatic' user: 'root' host: '  cloudsqlproxy~129.41.84.82' (Got an error reading communication packets)"  
timestamp:  "2019-07-17T10:37:59.136950Z"  
}

so I added my cluster IP in sql Connection tab, but still getting this error my API works fine when I just preview my app docker image after deployment api doest work getting this error after deploymenet Could not open JPA EntityManager for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection

-- Doctor Who
google-cloud-platform
kubernetes
sql

1 Answer

7/17/2019

Although you have whitelisted your client IP in Cloud SQL, GKE has masquerading active meaning that, all outbound internet connections will be NATed to the node's external address.

ip-masq-agent configures iptables rules to handle masquerading node/Pod IP addresses when sending traffic to destinations outside the node’s and cluster's IP ranges. Pod IP addresses are masked behind their node's address.

There are still a couple of ways to connect to Cloud SQL from GKE. In my opinion, the most straight-forward is using the Cloud SQL Proxy deployed as a sidecar container in your pod.

If the proxy is not an option, you may be able to tweak the IP masquerade agent to bypass this SNAT rules and keep the requests' source IPs.

-- yyyyahir
Source: StackOverflow