DEV Community

Cover image for DevPill #7 - Cloud SQL Access for your containers on Google Kubernetes Engine
Raul Paes Silva
Raul Paes Silva

Posted on

DevPill #7 - Cloud SQL Access for your containers on Google Kubernetes Engine

Pre-requirements:

  • CloudSQL instance running
  • a database created

1. Create a new service account

name: "cloud-sql-gke-sa"
role: "roles/cloudsql.client"

2. Get the JSON key from the service account

After accessing the service account, go to "Keys" > Create New Key > type JSON > Create.

3. Create a new Kubernetes Secret

kubectl create secret generic cloud-sql-sa-key \
  --from-file=credentials.json=/path/to/service-account.json
Enter fullscreen mode Exit fullscreen mode

4. Alter your deployment file to add Cloud SQL Auth Proxy as a sidecar in the same pod.

Example:

containers:
  - name: stock-service
    image: us-central1-docker.pkg.dev/{project_id}/{repo_name}/{database_name}
    env:
      - name: DB_HOST
        value: "127.0.0.1"
      - name: DB_PORT
        value: "5432"
      - name: DB_USER
        valueFrom:
          secretKeyRef:
            name: app-secrets
            key: DB_USER
      - name: DB_PASSWORD
        valueFrom:
          secretKeyRef:
            name: app-secrets
            key: DB_PASSWORD
      - name: DB_NAME
        valueFrom:
          configMapKeyRef:
            name: app-config
            key: DB_NAME

  - name: cloud-sql-proxy
    image: gcr.io/cloudsql-docker/gce-proxy:1.33.2
    command:
      - "/cloud_sql_proxy"
      - "-instances={project_id}:{region}:stock-db-instance=tcp:5432"
      - "-credential_file=/secrets/credentials.json"
    volumeMounts:
      - name: cloudsql-creds
        mountPath: /secrets
        readOnly: true

volumes:
  - name: cloudsql-creds
    secret:
      secretName: cloud-sql-sa-key
Enter fullscreen mode Exit fullscreen mode

From this moment on your application will connect to a local proxy(host=127.0.0.1 port=5432) to access the CloudSQL database.

Top comments (0)