Connettersi da Google Kubernetes Engine

Questa pagina descrive come configurare una connessione da un'applicazione in esecuzione in Google Kubernetes Engine (GKE) a un'istanza Cloud SQL.

Per istruzioni passo passo sull'esecuzione di un'applicazione web di esempio di Google Kubernetes Engine connessa a Cloud SQL, consulta la guida rapida per la connessione da Google Kubernetes Engine.

Cloud SQL è un servizio di database completamente gestito che semplifica la configurazione, la manutenzione, la gestione e l'amministrazione dei database relazionali nel cloud.

Google Kubernetes Engine è un modo semplice per automatizzare il deployment, la scalabilità e la gestione di Kubernetes.

Informazioni sulla connessione di Google Kubernetes Engine a Cloud SQL

Per accedere a un'istanza Cloud SQL da un'applicazione in esecuzione in Google Kubernetes Engine, puoi utilizzare Cloud SQL Auth Proxy (con IP pubblico o privato) o connetterti direttamente utilizzando un indirizzo IP privato.

Il proxy di autenticazione Cloud SQL è il metodo consigliato per connettersi a Cloud SQL, anche quando utilizzi un IP privato. Questo perché il proxy di autenticazione Cloud SQL fornisce una crittografia e un'autenticazione efficaci utilizzando IAM, che possono contribuire a proteggere il database.

Le connessioni al database consumano risorse sul server e sull'applicazione di connessione. Utilizza sempre buone pratiche di gestione delle connessioni per ridurre al minimo l'impatto della tua applicazione e la probabilità di superare i limiti di connessione di Cloud SQL. Per saperne di più, consulta Gestisci le connessioni ai database.

Prima di iniziare

Per connetterti a Cloud SQL devi disporre di:

  • Un cluster GKE, con lo strumento a riga di comando kubectl installato e configurato per comunicare con il cluster.

    Per assistenza su come iniziare a utilizzare GKE, consulta Esegui il deployment di un'app in un cluster GKE.

    Per connetterti utilizzando l'IP privato, il cluster GKE deve essere nativo VPC e deve essere associato alla stessa rete Virtual Private Cloud (VPC) dell'istanza Cloud SQL.

  • Un'istanza creata.

    Per assistenza sulla creazione di un'istanza Cloud SQL, consulta Creazione di istanze.

  • Un account utente PostgreSQL configurato nell'istanza.

    La tua applicazione utilizzerà questo account per connettersi al database. Per assistenza sulla creazione di un account utente, consulta Creazione di un utente.

Informazioni sui secret di Kubernetes

In Kubernetes, i secret sono un modo sicuro per passare i dettagli di configurazione alla tua applicazione. Puoi creare un secret con dettagli come il nome, l'utente e la password del database, che possono essere inseriti nella tua applicazione come variabili di ambiente.

Esistono molti modi diversi per utilizzare i secret, a seconda del tipo di connessione:

  • Un secret delle credenziali del database include il nome dell'utente del database con cui ti connetti e la password del database dell'utente.
  • Se ti connetti con il Cloud SQL Auth Proxy, puoi utilizzare un secret per conservare il file delle credenziali del service account.
  • Se ti connetti con un IP privato, puoi utilizzare un secret per specificare l'indirizzo IP privato della tua istanza Cloud SQL.

Per esempi completi su come utilizzare i secret, consulta i repository GitHub a cui si fa riferimento più avanti in questa pagina.

Crea un oggetto Secret

  1. Crea gli oggetti Secret utilizzando il comando kubectl create secret.

    Per creare un secret delle credenziali del 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. Una volta creati, puoi visualizzare gli oggetti nella sezione Configurazione della pagina Google Kubernetes Engine nella consoleGoogle Cloud .

Connettiti a Cloud SQL utilizzando il proxy di autenticazione Cloud SQL

Quando ti connetti utilizzando il Cloud SQL Auth Proxy, il Cloud SQL Auth Proxy viene aggiunto al pod utilizzando il pattern del container sidecar. Il container del proxy di autenticazione Cloud SQL si trova nello stesso pod dell'applicazione, il che consente all'applicazione di connettersi al proxy di autenticazione Cloud SQL utilizzando localhost, aumentando la sicurezza e le prestazioni.

Per saperne di più sul proxy di autenticazione Cloud SQL, consulta Informazioni sul proxy di autenticazione Cloud SQL. Per ulteriori informazioni sull'utilizzo dei pod, consulta la Panoramica dei pod nella documentazione di Kubernetes.

Per connetterti utilizzando il proxy di autenticazione Cloud SQL, devi disporre di quanto segue:

  1. Il nome della connessione dell'istanza Cloud SQL.

    Il nome della connessione dell'istanza è disponibile nella pagina Dettagli istanza Cloud SQL della console Google Cloud o dal comando gcloud sql instances describe INSTANCE_ID.

  2. La posizione del file della chiave associato a un account di servizio con i privilegi appropriati per l'istanza Cloud SQL.

    Per saperne di più, consulta Creazione di un service account.

  3. L'API Cloud SQL Admin è abilitata.

    Ruoli richiesti per abilitare le API

    Per abilitare le API, devi disporre dell'autorizzazione serviceusage.services.enable. Se hai creato il progetto, probabilmente hai già questa autorizzazione tramite il ruolo Proprietario (roles/owner). In caso contrario, puoi ottenere questa autorizzazione tramite il ruolo Amministratore Service Usage (roles/serviceusage.serviceUsageAdmin). Scopri come concedere i ruoli.

    Abilitare l'API

Fornisci il account di servizio al proxy di autenticazione Cloud SQL

Il primo passaggio per eseguire il Cloud SQL Auth Proxy in Google Kubernetes Engine è creare un service account Google (GSA) per rappresentare la tua applicazione. Ti consigliamo di creare un account di servizio univoco per ogni applicazione, anziché utilizzare lo stesso service account ovunque. Questo modello è più sicuro perché consente di limitare le autorizzazioni in base all'applicazione.

Il account di servizio per la tua applicazione deve soddisfare i seguenti criteri:

  • Appartenere a un progetto con l'API Cloud SQL Admin abilitata
  • Aver ricevuto il ruolo IAM Client Cloud SQL (o equivalente) per il progetto contenente l'istanza a cui vuoi connetterti
  • Se la connessione viene stabilita utilizzando un IP privato, devi utilizzare un cluster GKE nativo di VPC, nello stesso VPC dell'istanza Cloud SQL.

Devi configurare GKE per fornire il account di servizio al proxy di autenticazione Cloud SQL. Esistono due modi consigliati per farlo: Workload Identity o un file della chiave del service account.

Workload Identity

Se utilizzi Google Kubernetes Engine, il metodo preferito è utilizzare la funzionalità Workload Identity di GKE. Questo metodo ti consente di associare un service account Kubernetes (KSA) a un service account Google (GSA). Il GSA sarà quindi accessibile alle applicazioni che utilizzano il KSA corrispondente.

Un service account Google (GSA) è un'identità IAM che rappresenta la tua applicazione in Google Cloud. In modo simile, un service account Kubernetes (KSA) è un'identità che rappresenta la tua applicazione in un cluster Google Kubernetes Engine.

Workload Identity associa un KSA a un GSA, in modo che tutti i deployment con quel KSA vengano autenticati come GSA nelle loro interazioni con Google Cloud.

  1. Abilita Workload Identity per il cluster
  2. In genere, ogni applicazione ha la propria identità, rappresentata da una coppia di account di servizio Kubernetes e Google. Crea un KSA per la tua applicazione eseguendo kubectl apply -f service-account.yaml:

    apiVersion: v1
    kind: ServiceAccount
    metadata:
      name: <YOUR-KSA-NAME> # TODO(developer): replace these values
  3. Abilita l'associazione IAM tra YOUR-GSA-NAME e YOUR-KSA-NAME:

    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. Aggiungi un'annotazione a YOUR-KSA-NAME per completare l'associazione:

    kubectl annotate serviceaccount \
    YOUR-KSA-NAME \
    iam.gke.io/gcp-service-account=YOUR-GSA-NAME@YOUR-GOOGLE-CLOUD-PROJECT.iam.gserviceaccount.com
  5. Infine, assicurati di specificare il account di servizio per l'oggetto 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 della chiave del service account

In alternativa, se non puoi utilizzare Workload Identity, il pattern consigliato è montare un file della chiave del account di servizio nel pod del Cloud SQL Auth Proxy e utilizzare il flag --credentials-file.

  1. Crea un file di credenziali per la chiave del account di servizio:

    gcloud iam service-accounts keys create ~/key.json \
    --iam-account=YOUR-SA-NAME@project-id.iam.gserviceaccount.com
  2. Trasforma la chiave del account di servizio in un secret k8s:

    kubectl create secret generic YOUR-SA-SECRET \
    --from-file=service_account.json=~/key.json
  3. Monta il secret come volume in spec: per l'oggetto k8s:

    volumes:
      - name: <YOUR-SA-SECRET-VOLUME>
        secret:
          secretName: <YOUR-SA-SECRET>
  4. Segui le istruzioni nella sezione successiva per accedere al volume dal pod del Cloud SQL Auth Proxy.

Esegui il proxy di autenticazione Cloud SQL in un pattern sidecar

Ti consigliamo di eseguire il proxy di autenticazione Cloud SQL in un pattern sidecar (come container aggiuntivo che condivide un pod con la tua applicazione). Ti consigliamo di farlo anziché eseguirlo come servizio separato per diversi motivi:

  • Impedisce l'esposizione locale del traffico SQL. Il Cloud SQL Auth Proxy fornisce la crittografia sulle connessioni in uscita, ma devi limitare l'esposizione per le connessioni in entrata.
  • Evita un single point of failure; l'accesso di ogni applicazione al tuo database è indipendente dagli altri, il che lo rende più resiliente.
  • Limita l'accesso al Cloud SQL Auth Proxy, consentendoti di utilizzare le autorizzazioni IAM per ogni applicazione anziché esporre il database all'intero cluster.
  • Consente di definire l'ambito delle richieste di risorse in modo più accurato. Poiché il Cloud SQL Auth Proxy consuma risorse in modo lineare rispetto all'utilizzo, questo pattern consente di definire l'ambito e richiedere risorse in modo che corrispondano alle tue applicazioni man mano che l'applicazione scala.

  • Aggiungi il proxy di autenticazione Cloud SQL alla configurazione del pod in initContainers, a meno che tu non stia utilizzando Cloud Service Mesh o Istio.

    Se utilizzi Cloud Service Mesh o Istio, aggiungi il proxy di autenticazione Cloud SQL nella sezione containers.

    initContainers

    initContainers:
      - name: cloud-sql-proxy
        restartPolicy: Always
        # 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.14.1
        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"
    
          # If you are not connecting with Automatic IAM, you can delete
          # the following flag.
          - "--auto-iam-authn"
    
          # 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"

    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.14.1
      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"
    
        # If you are not connecting with Automatic IAM, you can delete
        # the following flag.
        - "--auto-iam-authn"
    
        # 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"
  • Se utilizzi una chiave del account di servizio, specifica il volume del secret e aggiungi il flag --credentials-file al comando:

      # 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
  • Infine, configura l'applicazione per la connessione utilizzando 127.0.0.1 su qualsiasi DB_PORT specificato nella sezione dei comandi.

File di configurazione di esempio completi:

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
      initContainers:
        - name: cloud-sql-proxy
          restartPolicy: Always
          # 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.14.1
          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"

            # If you are not connecting with Automatic IAM, you can delete
            # the following flag.
            - "--auto-iam-authn"

            # 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"

Chiave account di servizio

# 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
      initContainers:
        - name: cloud-sql-proxy
          restartPolicy: Always
          # 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.14.1
          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"

            # If you are not connecting with Automatic IAM AuthN, you can delete
            # the following flag.
            - "--auto-iam-authn"

            # 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>

Connettiti a Cloud SQL senza il proxy di autenticazione Cloud SQL

Sebbene non sia altrettanto sicuro, è possibile connettersi da un cluster GKE nativo di VPC a un'istanza Cloud SQL sullo stesso VPC utilizzando un IP privato senza il proxy di autenticazione Cloud SQL.

  1. Crea un secret con l'indirizzo IP privato dell'istanza:

    kubectl create secret generic <YOUR-PRIVATE-IP-SECRET> \
        --from-literal=db_host=<YOUR-PRIVATE-IP-ADDRESS>
    
  2. Ora assicurati di aggiungere il secret al container della tua applicazione:

    - name: DB_HOST
      valueFrom:
        secretKeyRef:
          name: <YOUR-PRIVATE-IP-SECRET>
          key: db_host
  3. Infine, configura l'applicazione per connetterti utilizzando l'indirizzo IP della variabile di ambiente DB_HOST. Dovrai utilizzare la porta corretta per PostgreSQL: 5432

File di configurazione di esempio completo:

IP privato

# 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

Risoluzione dei problemi

Serve aiuto? Per assistenza nella risoluzione dei problemi del proxy, consulta Risoluzione dei problemi relativi alle connessioni del proxy di autenticazione Cloud SQL o visita la nostra pagina di assistenza di Cloud SQL.

Passaggi successivi