Search code examples
dockerkubernetesgoogle-cloud-sqlgoogle-kubernetes-enginecloud-sql-proxy

How to connect to cloud sql from containered application in gcloud?


I'm using GCloud, I have a kubernate cluster and a cloud sql instance.

I have a simple node.js app, that uses database. When I deploy with gcloud app deploy it has an access to a database. However, when I build a dockerimage and expose it, it cannot reach database.

  1. I expose Docker application following: https://cloud.google.com/kubernetes-engine/docs/tutorials/hello-app
  2. Cloud SQL deosn't have Private IP enabled, Im connecting using cloud sql proxy
  3. In app.yaml I do specify base_settings:cloud_sql_instances. I use the same value in socketPath config for mysql connection.
  4. The error in docker logs is:

    (node:1) UnhandledPromiseRejectionWarning: Error: connect ENOENT /cloudsql/x-alcove-224309:europe-west1:learning at PipeConnectWrap.afterConnect [as oncomplete] (net.js:1097:14)

Can you please explain me how to connect to cloud sql from dockerized node application.


Solution

  • When you deploy your app on App Engine with gcloud app deploy, the platform runs it in a container along with a side-car container in charge of running the cloud_sql_proxy (you ask for it by specifying the base_settings:cloud_sql_instances in your app.yaml file).

    Kubernetes Engine doesn't use an app.yaml file and doesn't supply this side-car container to you so you'll have to set it up. The public doc shows how to do it by creating secrets for your database credentials and updating your deployment file with the side-car container config. An example shown in the doc would look like:

    ...
    - name: cloudsql-proxy
      image: gcr.io/cloudsql-docker/gce-proxy:1.11
      command: ["/cloud_sql_proxy",
                "-instances=<INSTANCE_CONNECTION_NAME>=tcp:3306",
                "-credential_file=/secrets/cloudsql/credentials.json"]
      securityContext:
        runAsUser: 2  # non-root user
        allowPrivilegeEscalation: false
      volumeMounts:
        - name: cloudsql-instance-credentials
          mountPath: /secrets/cloudsql
          readOnly: true
    ...