0

I have a simple Java servlet app, deployed to the GCP AppEngine. Under the same GCP, I have created a MySQL instance of GCP Cloud SQL.

I would like to save the value on MySQL server when someone makes an HTTP Post request. However, my Java App cannot connect to GCP Cloud SQL.

On the Cloud SQL page, it says All apps in this project. All authorized. However, my Java app can't connect even though they are under the same GCP Project.

When I add all the networks, it works correctly. However I don't want to do this:

ss from gcp console

What could be the reason that I can't connect to Cloud SQL from the App Engine? Is there some configuration that I need to do?

1

You shouldn't whitelist 0.0.0.0/0 - this allows any IP address to attempt to connect to your instance, and will be

I would suggest using the Cloud SQL JDBC Socket Factory. The Socket Factory uses service account credentials to authenticate connections to your instance.

You can also check these instructions on the Connecting from App Engine page to make sure you have enabled the correct API and given the service account the correct permissions.

0

You should not whitelist list all IPs, this makes your SQL instance accessible to anyone on the internet.

Google handles the connection from AppEngine to CloudSQL over UNIX sockets. In order to connect from local, you are supposed to use the INSTANCE_CONNECTION_NAME while you are connecting from AppEngine you should specify the host as localhost but add the socket path as /cloudsql/<INSTANCE_CONNECTION_NAME>. This for NodeJS.

For JAVA its something like

// Configure which instance and what database user to connect with.
config.setJdbcUrl(String.format("jdbc:mysql:///%s", DB_NAME));
config.setUsername(DB_USER); // e.g. "root", "postgres"
config.setPassword(DB_PASS); // e.g. "my-password"

// For Java users, the Cloud SQL JDBC Socket Factory can provide authenticated connections.
// See https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory for details.
config.addDataSourceProperty("socketFactory", "com.google.cloud.sql.mysql.SocketFactory");
config.addDataSourceProperty("cloudSqlInstance", CLOUD_SQL_CONNECTION_NAME);
config.addDataSourceProperty("useSSL", "false");

Rest all configuration remains the same. Please have a look at the detailed documentation of the same here.

I have been running successfully with the configuration for sometime now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.