Terhubung ke Cloud SQL dari Google Kubernetes Engine

Halaman ini menjelaskan cara menyiapkan koneksi dari aplikasi yang berjalan di Google Kubernetes Engine (GKE) ke instance Cloud SQL.

Untuk petunjuk langkah demi langkah cara menjalankan aplikasi web sampel Google Kubernetes Engine yang terhubung ke Cloud SQL, lihat panduan memulai untuk terhubung dari Google Kubernetes Engine singkat ini.

Cloud SQL adalah layanan database terkelola sepenuhnya yang membantu Anda menyiapkan, memelihara, mengelola, dan mengatur database relasional di cloud.

Google Kubernetes Engine adalah cara mudah untuk men-deploy, menskalakan, dan mengelola Kubernetes secara otomatis.

Tentang menghubungkan Google Kubernetes Engine ke Cloud SQL

Untuk mengakses instance Cloud SQL dari aplikasi yang berjalan di Google Kubernetes Engine, Anda dapat menggunakan Proxy Auth Cloud SQL (dengan IP publik atau pribadi), atau terhubung langsung menggunakan alamat IP pribadi.

Proxy Auth Cloud SQL adalah cara yang direkomendasikan untuk terhubung ke Cloud SQL, bahkan saat menggunakan IP pribadi. Hal ini karena Proxy Auth Cloud SQL menyediakan enkripsi dan autentikasi yang kuat menggunakan IAM, yang dapat membantu menjaga keamanan database Anda.

Koneksi database menggunakan resource di server dan aplikasi yang terhubung. Selalu gunakan praktik pengelolaan koneksi yang baik untuk meminimalkan jejak aplikasi Anda dan mengurangi kemungkinan terlampauinya batas koneksi Cloud SQL. Untuk mengetahui informasi selengkapnya, lihat Mengelola koneksi database.

Sebelum memulai

Untuk terhubung ke Cloud SQL, Anda harus memiliki:

  • Cluster GKE, dengan alat command line kubectl yang diinstal dan dikonfigurasi untuk berkomunikasi dengan cluster.

    Untuk mendapatkan bantuan dalam memulai GKE, lihat Men-deploy aplikasi ke cluster GKE.

    Agar terhubung menggunakan IP pribadi, cluster GKE harus bersifat VPC-native dan di-peering dengan jaringan Virtual Private Cloud (VPC) yang sama dengan instance Cloud SQL.

  • Instance dibuat.

    Untuk mendapatkan bantuan dalam membuat instance Cloud SQL, lihat Membuat Instances.

  • Akun pengguna MySQL yang dikonfigurasi pada instance.

    Aplikasi Anda akan menggunakan akun ini untuk terhubung ke database. Untuk mendapatkan bantuan dalam membuat akun pengguna, lihat Membuat pengguna.

.

Tentang Secret Kubernetes

Di Kubernetes, Secret adalah cara yang aman untuk meneruskan detail konfigurasi ke aplikasi Anda. Anda dapat membuat Secret dengan detail seperti nama, pengguna, dan sandi database yang dapat dimasukkan ke dalam aplikasi sebagai env vars.

Ada banyak cara berbeda untuk menggunakan Secret, bergantung pada jenis koneksinya:

  • Secret kredensial database mencakup nama pengguna database yang Anda hubungkan, dan sandi database pengguna tersebut.
  • Jika terhubung dengan Proxy Auth Cloud SQL, Secret dapat digunakan untuk menyimpan file kredensial akun layanan Anda.
  • Jika terhubung dengan IP pribadi, Secret dapat digunakan untuk menentukan alamat IP pribadi instance Cloud SQL Anda.

Untuk contoh lengkap cara menggunakan Secret, lihat repositori GitHub yang dirujuk nanti dalam halaman ini.

Membuat objek Secret

  1. Anda membuat objek Secret menggunakan perintah kubectl create secret.

    Untuk membuat Secret kredensial database:

    kubectl create secret generic <YOUR-DB-SECRET> \
      --from-literal=username=<YOUR-DATABASE-USER> \
      --from-literal=password=<YOUR-DATABASE-PASSWORD> \
      --from-literal=database=<YOUR-DATABASE-NAME>
    
  2. Setelah dibuat, Anda dapat melihat objek di bagian Konfigurasi di halaman Google Kubernetes Engine di Konsol Google Cloud.

Menghubungkan ke Cloud SQL menggunakan Proxy Auth Cloud SQL

Saat Anda terhubung menggunakan Proxy Auth Cloud SQL, Proxy Auth Cloud SQL ditambahkan ke pod Anda menggunakan pola container sidecar. Container Proxy Auth Cloud SQL berada di pod yang sama dengan aplikasi Anda, yang memungkinkan aplikasi tersebut terhubung ke Proxy Auth Cloud SQL menggunakan localhost, sehingga meningkatkan keamanan dan performa.

Untuk mengetahui informasi selengkapnya tentang Proxy Auth Cloud SQL, lihat Tentang Proxy Auth Cloud SQL. Untuk mengetahui informasi selengkapnya tentang cara menggunakan pod, lihat Ringkasan Pod dalam dokumentasi Kubernetes.

Untuk menghubungkan menggunakan Proxy Auth Cloud SQL, Anda memerlukan hal berikut:

  1. Nama koneksi instance dari instance Cloud SQL Anda.

    Nama koneksi instance tersedia di halaman Detail instance Cloud SQL pada Google Cloud Console atau dari perintah gcloud sql instances describe INSTANCE_ID.

  2. Lokasi file kunci yang terkait dengan akun layanan dengan hak istimewa yang tepat untuk instance Cloud SQL Anda.

    Lihat Membuat akun layanan untuk informasi selengkapnya.

  3. Cloud SQL Admin API diaktifkan.

    Enable the API

Menyediakan akun layanan ke Proxy Auth Cloud SQL

Langkah pertama untuk menjalankan Proxy Auth Cloud SQL di Google Kubernetes Engine adalah membuat Akun Layanan Google (GSA) untuk merepresentasikan aplikasi Anda. Sebaiknya buat akun layanan yang unik untuk setiap aplikasi, daripada menggunakan akun layanan yang sama di mana saja. Model ini lebih aman karena memungkinkan Anda membatasi izin per aplikasi.

Akun layanan untuk permohonan Anda harus memenuhi kriteria berikut:

  • Termasuk dalam project dengan Cloud SQL Admin API diaktifkan
  • Telah diberi peran IAM Klien Cloud SQL (atau yang setara) untuk project yang berisi instance yang ingin dihubungkan
  • Jika terhubung menggunakan IP pribadi, Anda harus menggunakan cluster GKE native VPC, di VPC yang sama dengan instance Cloud SQL Anda

Anda perlu mengonfigurasi GKE untuk menyediakan akun layanan ke Proxy Auth Cloud SQL. Ada dua cara yang direkomendasikan untuk melakukannya: workload identity atau file kunci akun layanan.

Workload Identity

Jika Anda menggunakan Google Kubernetes Engine, metode yang disarankan adalah menggunakan fitur Workload Identity GKE. Metode ini memungkinkan Anda mengikat Akun Layanan Kubernetes (KSA) ke Akun Layanan Google (GSA). GSA kemudian akan dapat diakses oleh aplikasi menggunakan KSA yang cocok.

Akun Layanan Google (GSA) adalah identitas IAM yang mewakili aplikasi Anda di Google Cloud. Dengan cara yang sama, Akun Layanan Kubernetes (KSA) adalah identitas yang mewakili aplikasi Anda di cluster Google Kubernetes Engine.

Workload Identity mengikat KSA ke GSA, yang menyebabkan deployment apa pun dengan KSA tersebut melakukan autentikasi sebagai GSA dalam interaksi mereka dengan Google Cloud.

  1. Mengaktifkan Workload Identity untuk cluster Anda
  2. Biasanya, setiap aplikasi memiliki identitasnya sendiri, yang diwakili oleh pasangan KSA dan GSA. Buat KSA untuk aplikasi Anda dengan menjalankan kubectl apply -f service-account.yaml:

    apiVersion: v1
    kind: ServiceAccount
    metadata:
      name: <YOUR-KSA-NAME> # TODO(developer): replace these values
  3. Aktifkan binding IAM antara YOUR-GSA-NAME dan YOUR-KSA-NAME Anda:

    gcloud iam service-accounts add-iam-policy-binding \
    --role="roles/iam.workloadIdentityUser" \
    --member="serviceAccount:YOUR-GOOGLE-CLOUD-PROJECT.svc.id.goog[YOUR-K8S-NAMESPACE/YOUR-KSA-NAME]" \
    YOUR-GSA-NAME@YOUR-GOOGLE-CLOUD-PROJECT.iam.gserviceaccount.com
    
  4. Tambahkan anotasi ke YOUR-KSA-NAME untuk menyelesaikan binding:

    kubectl annotate serviceaccount \
    YOUR-KSA-NAME \
    iam.gke.io/gcp-service-account=YOUR-GSA-NAME@YOUR-GOOGLE-CLOUD-PROJECT.iam.gserviceaccount.com
    
  5. Terakhir, pastikan untuk menentukan akun layanan untuk objek k8s.

    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: <YOUR-DEPLOYMENT-NAME>
    spec:
      selector:
        matchLabels:
          app: <YOUR-APPLICATION-NAME>
      template:
        metadata:
          labels:
            app: <YOUR-APPLICATION-NAME>
        spec:
          serviceAccountName: <YOUR-KSA-NAME>

File kunci akun layanan

Atau, jika Anda tidak dapat menggunakan Workload Identity, pola yang direkomendasikan adalah memasang file kunci akun layanan ke pod Cloud SQL Auth Proxy dan menggunakan flag --credentials-file.

  1. Buat file kredensial untuk kunci akun layanan Anda:

    gcloud iam service-accounts keys create ~/key.json \
    --iam-account=YOUR-SA-NAME@project-id.iam.gserviceaccount.com
    
  2. Ubah kunci akun layanan Anda menjadi Secret k8s:

    kubectl create secret generic YOUR-SA-SECRET \
    --from-file=service_account.json=~/key.json
    
  3. Pasang secret sebagai volume di bawah spec: untuk objek k8s Anda:

    volumes:
    - name: <YOUR-SA-SECRET-VOLUME>
      secret:
        secretName: <YOUR-SA-SECRET>
  4. Ikuti petunjuk di bagian selanjutnya untuk mengakses volume dari pod Proxy Auth Cloud SQL.

Menjalankan Proxy Auth Cloud SQL dalam pola file bantuan

Sebaiknya jalankan Proxy Auth Cloud SQL dalam pola sidecar (sebagai penampungl tambahan yang berbagi pod dengan aplikasi Anda). Sebaiknya jangan jalankan hal ini sebagai layanan terpisah karena beberapa alasan:

  • Mencegah traffic SQL Anda terekspos secara lokal; Proxy Auth Cloud SQL memberikan enkripsi pada koneksi keluar, tetapi Anda perlu membatasi eksposur untuk koneksi masuk.
  • Mencegah titik tunggal kegagalan; akses setiap aplikasi ke database Anda independen dari yang lain, sehingga lebih tangguh.
  • Membatasi akses ke Proxy Auth Cloud SQL, sehingga Anda dapat menggunakan izin IAM per aplikasi, bukan mengekspos database ke seluruh cluster.
  • Memungkinkan Anda menentukan cakupan permintaan resource dengan lebih akurat; karena Proxy Auth Cloud SQL menggunakan resource secara linear untuk digunakan, pola ini memungkinkan Anda mencakupkan dan meminta resource secara lebih akurat agar sesuai dengan aplikasi Anda saat diskalakan.

  • Tambahkan Proxy Auth Cloud SQL ke konfigurasi pod di bagian containers:

    - name: cloud-sql-proxy
      # It is recommended to use the latest version of the Cloud SQL Auth Proxy
      # Make sure to update on a regular schedule!
      image: gcr.io/cloud-sql-connectors/cloud-sql-proxy:2.8.0
      args:
        # If connecting from a VPC-native GKE cluster, you can use the
        # following flag to have the proxy connect over private IP
        # - "--private-ip"
    
        # Enable structured logging with LogEntry format:
        - "--structured-logs"
    
        # Replace DB_PORT with the port the proxy should listen on
        - "--port=<DB_PORT>"
        - "<INSTANCE_CONNECTION_NAME>"
    
      securityContext:
        # The default Cloud SQL Auth Proxy image runs as the
        # "nonroot" user and group (uid: 65532) by default.
        runAsNonRoot: true
      # You should use resource requests/limits as a best practice to prevent
      # pods from consuming too many resources and affecting the execution of
      # other pods. You should adjust the following values based on what your
      # application needs. For details, see
      # https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/
      resources:
        requests:
          # The proxy's memory use scales linearly with the number of active
          # connections. Fewer open connections will use less memory. Adjust
          # this value based on your application's requirements.
          memory: "2Gi"
          # The proxy's CPU use scales linearly with the amount of IO between
          # the database and the application. Adjust this value based on your
          # application's requirements.
          cpu:    "1"

    Jika Anda menggunakan kunci akun layanan, tentukan volume secret Anda dan tambahkan flag --credentials-file ke perintah:

      # This flag specifies where the service account key can be found
      - "--credentials-file=/secrets/service_account.json"
    securityContext:
      # The default Cloud SQL Auth Proxy image runs as the
      # "nonroot" user and group (uid: 65532) by default.
      runAsNonRoot: true
    volumeMounts:
    - name: <YOUR-SA-SECRET-VOLUME>
      mountPath: /secrets/
      readOnly: true
  • Terakhir, konfigurasikan aplikasi Anda agar terhubung menggunakan 127.0.0.1 pada DB_PORT mana pun yang Anda tentukan di bagian perintah.

Lengkapi contoh file konfigurasi:

Workload Identity

# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: <YOUR-DEPLOYMENT-NAME>
spec:
  selector:
    matchLabels:
      app: <YOUR-APPLICATION-NAME>
  template:
    metadata:
      labels:
        app: <YOUR-APPLICATION-NAME>
    spec:
      serviceAccountName: <YOUR-KSA-NAME>
      containers:
      - name: <YOUR-APPLICATION-NAME>
        # ... other container configuration
        env:
        - name: DB_USER
          valueFrom:
            secretKeyRef:
              name: <YOUR-DB-SECRET>
              key: username
        - name: DB_PASS
          valueFrom:
            secretKeyRef:
              name: <YOUR-DB-SECRET>
              key: password
        - name: DB_NAME
          valueFrom:
            secretKeyRef:
              name: <YOUR-DB-SECRET>
              key: database
      - name: cloud-sql-proxy
        # It is recommended to use the latest version of the Cloud SQL Auth Proxy
        # Make sure to update on a regular schedule!
        image: gcr.io/cloud-sql-connectors/cloud-sql-proxy:2.8.0
        args:
          # If connecting from a VPC-native GKE cluster, you can use the
          # following flag to have the proxy connect over private IP
          # - "--private-ip"

          # Enable structured logging with LogEntry format:
          - "--structured-logs"

          # Replace DB_PORT with the port the proxy should listen on
          - "--port=<DB_PORT>"
          - "<INSTANCE_CONNECTION_NAME>"

        securityContext:
          # The default Cloud SQL Auth Proxy image runs as the
          # "nonroot" user and group (uid: 65532) by default.
          runAsNonRoot: true
        # You should use resource requests/limits as a best practice to prevent
        # pods from consuming too many resources and affecting the execution of
        # other pods. You should adjust the following values based on what your
        # application needs. For details, see
        # https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/
        resources:
          requests:
            # The proxy's memory use scales linearly with the number of active
            # connections. Fewer open connections will use less memory. Adjust
            # this value based on your application's requirements.
            memory: "2Gi"
            # The proxy's CPU use scales linearly with the amount of IO between
            # the database and the application. Adjust this value based on your
            # application's requirements.
            cpu:    "1"

Kunci akun layanan

# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: <YOUR-DEPLOYMENT-NAME>
spec:
  selector:
    matchLabels:
      app: <YOUR-APPLICATION-NAME>
  template:
    metadata:
      labels:
        app: <YOUR-APPLICATION-NAME>
    spec:
      containers:
      - name: <YOUR-APPLICATION-NAME>
        # ... other container configuration
        env:
        - name: DB_USER
          valueFrom:
            secretKeyRef:
              name: <YOUR-DB-SECRET>
              key: username
        - name: DB_PASS
          valueFrom:
            secretKeyRef:
              name: <YOUR-DB-SECRET>
              key: password
        - name: DB_NAME
          valueFrom:
            secretKeyRef:
              name: <YOUR-DB-SECRET>
              key: database
      - name: cloud-sql-proxy
        # It is recommended to use the latest version of the Cloud SQL Auth Proxy
        # Make sure to update on a regular schedule!
        image: gcr.io/cloud-sql-connectors/cloud-sql-proxy:2.8.0
        args:
          # If connecting from a VPC-native GKE cluster, you can use the
          # following flag to have the proxy connect over private IP
          # - "--private-ip"

          # Enable structured logging with LogEntry format:
          - "--structured-logs"

          # Replace DB_PORT with the port the proxy should listen on
          - "--port=<DB_PORT>"
          - "<INSTANCE_CONNECTION_NAME>"

          # This flag specifies where the service account key can be found
          - "--credentials-file=/secrets/service_account.json"
        securityContext:
          # The default Cloud SQL Auth Proxy image runs as the
          # "nonroot" user and group (uid: 65532) by default.
          runAsNonRoot: true
        volumeMounts:
        - name: <YOUR-SA-SECRET-VOLUME>
          mountPath: /secrets/
          readOnly: true
        # Resource configuration depends on an application's requirements. You
        # should adjust the following values based on what your application
        # needs. For details, see https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/
        resources:
          requests:
            # The proxy's memory use scales linearly with the number of active
            # connections. Fewer open connections will use less memory. Adjust
            # this value based on your application's requirements.
            memory: "2Gi"
            # The proxy's CPU use scales linearly with the amount of IO between
            # the database and the application. Adjust this value based on your
            # application's requirements.
            cpu:    "1"
      volumes:
      - name: <YOUR-SA-SECRET-VOLUME>
        secret:
          secretName: <YOUR-SA-SECRET>

Terhubung ke Cloud SQL tanpa Proxy Auth Cloud SQL

Meskipun tidak aman, Anda dapat terhubung dari cluster GKE native VPC ke instance Cloud SQL di VPC yang sama menggunakan IP pribadi tanpa Proxy Auth Cloud SQL.

  1. Buat secret dengan alamat IP pribadi instance Anda:

    kubectl create secret generic <YOUR-PRIVATE-IP-SECRET> \
        --from-literal=db_host=<YOUR-PRIVATE-IP-ADDRESS>
    
  2. Selanjutnya, pastikan Anda menambahkan secret ke container aplikasi:

    - name: DB_HOST
      valueFrom:
        secretKeyRef:
          name: <YOUR-PRIVATE-IP-SECRET>
          key: db_host
  3. Terakhir, konfigurasikan aplikasi Anda agar terhubung menggunakan alamat IP dari env var DB_HOST. Anda harus menggunakan porta yang benar untuk MySQL: 3306

Contoh file konfigurasi lengkap:

IP Pribadi

# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: <YOUR-DEPLOYMENT-NAME>
spec:
  selector:
    matchLabels:
      app: <YOUR-APPLICATION-NAME>
  template:
    metadata:
      labels:
        app: <YOUR-APPLICATION-NAME>
    spec:
      containers:
      - name: <YOUR-APPLICATION-NAME>
        # ... other container configuration
        env:
        - name: DB_USER
          valueFrom:
            secretKeyRef:
              name: <YOUR-DB-SECRET>
              key: username
        - name: DB_PASS
          valueFrom:
            secretKeyRef:
              name: <YOUR-DB-SECRET>
              key: password
        - name: DB_NAME
          valueFrom:
            secretKeyRef:
              name: <YOUR-DB-SECRET>
              key: database
        - name: DB_HOST
          valueFrom:
            secretKeyRef:
              name: <YOUR-PRIVATE-IP-SECRET>
              key: db_host

Pemecahan masalah

Butuh bantuan? Untuk mendapatkan bantuan dalam memecahkan masalah proxy, lihat Memecahkan masalah koneksi Proxy Auth Cloud SQL, atau lihat halaman Dukungan Cloud SQL kami.

Langkah selanjutnya