Wordpress application in GKE (kubernetes) using Cloud SQL as database

Connecting from Application Container to Cloud SQL instance in GKE

How to set up a connection from an application (Front End) running in Google Container Engine to a Cloud SQL (Banck End) instance.

a) Single pod containing two containers:

i) A web frontend container running Wordpress.
 ii) A Cloud SQL Proxy container providing connectivity to Cloud SQL. [Cloud SQL Proxy allows a user with the appropriate permissions to connect to a Second Generation Cloud SQL database without IP whitelist and SSL certificate.]

b) Mysql database running as Google Cloud SQL instance


A] Enable the API

Enable the Cloud SQL Administration API

B] Create a service account

Role, select Cloud SQL > Cloud SQL Client

The private key file is downloaded to your machine. Keep the key file secure. [Private key we will refer as “SQL_KEY_FILE_PATH” in Document]

C] Create the user account for the proxy

This increases the security of your configuration because only the proxy can use any user account created with this host

D] Create secrets

We need two secrets to enable your application to access the data in your Cloud SQL instance:

a) The cloudsql-instance-credentials secret enables your application to connect to your Cloud SQL instance.
 b) The cloudsql-db-credentials secret enables your application to connect to the database.

kubectl create secret generic cloudsql-instance-credentials --from-file=credentials.json=[SQL_KEY_FILE_PATH]

kubectl create secret generic cloudsql-db-credentials --from-literal=username=[PROXY_USER] --from-literal=password=drupal[PROXY_PASSWORD]

E] Get instance connection name

gcloud sql instances list

gcloud beta sql instances describe [SQL Instance name] | grep connection

F] Create Pod

For test our settings, we can use simple wordpress application :

wget https://raw.githubusercontent.com/GoogleCloudPlatform/kubernetes-engine-samples/master/cloudsql/mysql_wordpress_deployment.yaml

Replace [INSTANCE_CONNECTION_NAME] with the connection name [refer point E ]. Change the [PORT] to the port number used by your database. For our example provide as the host address your application uses to access the database.

kubectl create -f cloudsql_deployment.yaml

kubectl get pods

kubectl port-forward wordpress-2668199741-wvaup 8082:80

open localhost:8080 in your browser.

Refer : https://github.com/GoogleCloudPlatform/container-engine-samples/tree/master/cloudsql