從 Google Kubernetes Engine (GKE) 連線至 PostgreSQL 適用的 AlloyDB

本教學課程說明如何設定連線,從 Google Kubernetes Engine Autopilot 叢集中執行的應用程式連線至 AlloyDB 執行個體。

AlloyDB 是與 PostgreSQL 相容的全代管資料庫服務,位於 Google Cloud。

Google Kubernetes Engine 可協助您自動部署、管理 Kubernetes 及調度所需資源。

目標

  • 為 AlloyDB 建構 Docker 映像檔。
  • 在 Google Kubernetes Engine 中執行應用程式。
  • 使用 AlloyDB Auth Proxy 和內部 IP 連線至 AlloyDB 執行個體。

費用

本教學課程使用 Google Cloud的計費元件,包括:

  • AlloyDB
  • Google Kubernetes Engine
  • Artifact Registry

您可以使用 Pricing Calculator 來根據預測使用量產生預估費用。

事前準備

主控台

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  5. Verify that billing is enabled for your Google Cloud project.

  6. 啟用建立及連線至 PostgreSQL 適用的 AlloyDB 時所需的 Cloud API。

    啟用 API

    1. 在「確認專案」步驟中,按一下「下一步」,確認要變更的專案名稱。

    2. 在「啟用 API」步驟中,按一下「啟用」,啟用下列項目:

      • AlloyDB API
      • Artifact Registry API
      • Compute Engine API
      • Cloud Resource Manager API
      • Cloud Build API
      • Container Registry API
      • Kubernetes Engine API
      • Service Networking API

在本教學課程中,請使用名為 gke-alloydb-app 的範例投票收集網頁應用程式。

啟動 Cloud Shell

Cloud Shell 是殼層環境,可用來管理託管於Google Cloud的資源。

Cloud Shell 已預先安裝 Google Cloud CLIkubectl 指令列工具。gcloud CLI 提供 Google Cloud的主要指令列介面。kubectl 提供主要的指令列介面,用於對 Kubernetes 叢集執行指令。

主控台

如要啟動 Cloud Shell,請完成下列步驟。

  1. 前往 Google Cloud 控制台。

    Google Cloud console

  2. 按一下控制台頂端的「啟用 Cloud Shell」「啟用 Cloud Shell」按鈕 Google Cloud 。

  3. 在「授權 Cloud Shell」對話方塊中,按一下「授權」

    此時 Cloud Shell 工作階段會在主控台底部的頁框中開啟,請使用這個殼層來執行 gcloudkubectl 指令。

    1. 執行指令前,請先使用下列指令,在 Google Cloud CLI 中設定預設專案:

      gcloud config set project PROJECT_ID

      PROJECT_ID 替換為專案 ID

建立 AlloyDB 叢集及其主要執行個體

AlloyDB 叢集包含 Google 虛擬私有雲 (VPC) 中的多個節點。建立叢集時,您也會在其中一個虛擬私有雲與包含新叢集的 Google 管理虛擬私有雲之間,設定私人服務存取權。建議您使用內部 IP 存取權,避免資料庫暴露在公開網際網路上。

如要從設定的 VPC 外部連線至 AlloyDB for PostgreSQL 叢集,請在 AlloyDB 的 VPC 中設定 Private Service Access 設定,並使用預設 VPC 網路,從部署在 GKE 叢集上的應用程式執行查詢。

gcloud

  1. 在 Cloud Shell 中,檢查未使用的 IP 位址 (IPv4) 範圍是否已指派給服務對等互連:

    gcloud services vpc-peerings list --network=default

    如果輸出內容與下列內容類似,請略過下一個步驟:

    network: projects/493573376485/global/networks/default
    peering: servicenetworking-googleapis-com
    reservedPeeringRanges:
    - default-ip-range
    service: services/servicenetworking.googleapis.com
    

    在這個輸出內容中,reservedPeeringRanges 的值為 default-ip-range,您可以在步驟 3 中將其做為 IP_RANGE_NAME,建立私人連線。

  2. (使用 reservedPeeringRanges 的預設值時請略過) 如要在 VPC 中分配未使用的 IP 位址,請使用下列指令:

    gcloud compute addresses create IP_RANGE_NAME \
        --global \
        --purpose=VPC_PEERING \
        --prefix-length=16 \
        --description="VPC private service access" \
        --network=default

    IP_RANGE_NAME 替換為 AlloyDB 子網路中可用內部 IP 位址的名稱,例如 alloydb-gke-psa-01

  3. 如要使用已分配的 IP 範圍設定服務存取權,請執行下列指令:

    gcloud services vpc-peerings connect \
        --service=servicenetworking.googleapis.com \
        --ranges=IP_RANGE_NAME \
        --network=default
  4. 如要部署 AlloyDB 叢集,請執行下列指令:

    gcloud alloydb clusters create CLUSTER_ID \
        --database-version=POSTGRES_VERSION \
        --password=CLUSTER_PASSWORD \
        --network=default \
        --region=REGION \
        --project=PROJECT_ID

    更改下列內容:

    • CLUSTER_ID:您要建立的叢集 ID。開頭須為小寫英文字母,且只能由小寫英文字母、數字和連字號組成,例如 alloydb-cluster
    • VERSION:叢集資料庫伺服器要相容的 PostgreSQL 主要版本。選擇下列其中一個選項:

      • 14:與 PostgreSQL 14 相容

      • 15:與 PostgreSQL 15 相容

      • 16:與 PostgreSQL 16 相容,這是支援的預設 PostgreSQL 版本

        如要進一步瞭解使用 PostgreSQL 16 預先發布版時的限制,請參閱「預先發布版 PostgreSQL 16 相容性」。

    • CLUSTER_PASSWORD:預設 postgres 使用者的密碼。

    • PROJECT_ID:您要放置叢集的 Google Cloud 專案 ID。

    • REGION:AlloyDB 叢集建立所在的區域名稱,例如 us-central1

  5. 如要部署 AlloyDB 主要執行個體,請執行下列指令:

    gcloud alloydb instances create INSTANCE_ID \
        --instance-type=PRIMARY \
        --cpu-count=NUM_CPU \
        --region=REGION \
        --cluster=CLUSTER_ID \
        --project=PROJECT_ID

    更改下列內容:

    • INSTANCE_ID,例如 alloydb-primary
    • CLUSTER_ID 改成 AlloyDB 叢集的名稱,例如 alloydb-cluster
    • NUM_CPU,例如 2
    • PROJECT_ID 替換為專案的 ID。 Google Cloud
    • REGION 改成建立 AlloyDB 叢集的區域名稱,例如 us-central1

    等待 AlloyDB 執行個體建立完成。這可能需要幾分鐘的時間。

連線至主要執行個體,並建立 AlloyDB 資料庫和使用者

主控台

  1. 如果不在新建立的叢集「總覽」頁面,請在 Google Cloud 控制台中前往「叢集」頁面。

    前往「Clusters」(叢集) 頁面

  2. 如要顯示叢集「總覽」頁面,請按一下 CLUSTER_ID 叢集名稱。

  3. 在導覽選單中,按一下「AlloyDB Studio」

  4. 在「Sign in to AlloyDB Studio」(登入 AlloyDB Studio) 頁面中,執行下列操作:

    1. 在「Database」(資料庫) 清單中選取「postgres」。

    2. 在「使用者」清單中,選取 postgres

    3. 在「密碼」欄位中,輸入您在「建立 AlloyDB 叢集及其主要執行個體」中建立的 CLUSTER_PASSWORD

    4. 按一下「驗證」。「Explorer」窗格會顯示資料庫中的物件清單。

  5. 在「Editor 1」(編輯器 1) 分頁中,完成下列步驟:

    1. 建立 AlloyDB 資料庫:

      CREATE DATABASE DATABASE_NAME;
      

      DATABASE_NAME 替換成您選擇的名稱,例如 tutorial_db

    2. 按一下「執行」。等待「結果」窗格顯示 Statement executed successfully 訊息。

    3. 按一下「清除」

    4. 建立 AlloyDB 資料庫使用者和密碼:

      CREATE USER USERNAME WITH PASSWORD 'DATABASE_PASSWORD';
      

      更改下列內容:

      • :AlloyDB 使用者名稱,例如 tutorial_userUSERNAME

      • DATABASE_PASSWORD:AlloyDB 資料庫的密碼,例如 tutorial

    5. 按一下「執行」。等待「結果」窗格顯示 Statement executed successfully 訊息。

  6. 在 AlloyDB Studio 的「Explorer」窗格中,按一下「Switch user/database」

  7. 在「Sign in to AlloyDB Studio」(登入 AlloyDB Studio) 頁面中,執行下列操作:

    1. 在「Database」(資料庫) 清單中選取「DATABASE_NAME」,例如「tutorial_db」。

    2. 在「使用者」清單中,選取 postgres

    3. 在「密碼」欄位中,輸入您在「建立 AlloyDB 叢集及其主要執行個體」中建立的 CLUSTER_PASSWORD

    4. 按一下「驗證」。「Explorer」窗格會顯示資料庫中的物件清單。

  8. 在「Editor 1」(編輯器 1) 分頁中,完成下列步驟:

    1. 將所有權限授予 AlloyDB 資料庫使用者:

      GRANT ALL PRIVILEGES ON DATABASE "DATABASE_NAME" to "USERNAME";
      
    2. 按一下「執行」。等待「結果」窗格顯示 Statement executed successfully 訊息。

    3. 按一下「清除」

    4. 授予 AlloyDB 資料庫使用者公用結構定義的權限:

      GRANT CREATE ON SCHEMA public TO "USERNAME";
      
    5. 按一下「執行」。等待「結果」窗格顯示 Statement executed successfully 訊息。

  9. 請記下資料庫名稱、使用者名稱和密碼。您會在「建立 Kubernetes 密鑰」中使用這項資訊。

建立 GKE Autopilot 叢集

一個叢集至少包含一個「叢集控制層」機器,以及多個稱為「節點」的工作站機器。節點是 Compute Engine 虛擬機器 (VM) 執行個體,會執行必要的 Kubernetes 程序,才能加入叢集。當您將應用程式部署至叢集之後,該應用程式就會在節點上執行。

主控台

  1. 在 Google Cloud 控制台中,前往「Kubernetes Clusters」(Kubernetes 叢集) 頁面。

    開啟 Kubernetes 叢集清單

  2. 點選「建立」

  3. 在「Cluster Basics」(叢集基本資訊) 頁面的「Name」(名稱) 欄位中,為 Autopilot 叢集指定 GKE_CLUSTER_ID,例如 ap-cluster

  4. 在「Region」(區域) 欄位中,選取「REGION」,例如「us-central1」。

  5. 點選「建立」

    等待 GKE 叢集建立完成。這可能需要幾分鐘的時間。

gcloud

建立 Autopilot 叢集:

gcloud container clusters create-auto GKE_CLUSTER_ID \
    --location=REGION

更改下列內容:

  • GKE_CLUSTER_ID:Autopilot 叢集的名稱,例如 ap-cluster
  • REGION:部署 GKE 叢集的區域名稱,例如 us-central1

等待 GKE 叢集建立完成。這可能需要幾分鐘的時間。

使用 AlloyDB Auth Proxy 連線至 AlloyDB

建議您使用 AlloyDB Auth Proxy 連線至 AlloyDB。AlloyDB Auth Proxy 使用 Identity and Access Management (IAM) 提供強大的加密和驗證功能,有助於確保資料庫安全。

使用 AlloyDB Auth Proxy 連線時,系統會使用 sidecar 容器模式將 Proxy 新增至 Pod。AlloyDB Auth Proxy 容器與應用程式位於同一個 Pod 中,因此應用程式可以使用 localhost 連線至 AlloyDB Auth Proxy,進而提升安全性和效能。

建立 Google 服務帳戶並授予角色

在 Google Cloud中,應用程式會使用服務帳戶,以服務帳戶身分進行驗證,藉此執行已授權的 API 呼叫。應用程式以服務帳戶身分進行驗證時,可以存取服務帳戶有權存取的所有資源。

如要在 Google Kubernetes Engine 中執行 AlloyDB Auth Proxy,請建立代表應用程式的 Google 服務帳戶。建議您為每個應用程式建立專屬的服務帳戶,而不是在所有地方使用同一個服務帳戶。這個模型可讓您依據應用程式限制權限,因此更加安全。

主控台

  1. 前往 Google Cloud 控制台的「IAM」頁面。

    前往「IAM」頁面

  2. 在「Permissions for project "PROJECT_ID"」(專案「PROJECT_ID」的權限) 頁面中,找出包含預設 Compute 服務帳戶 PROJECT_NUMBER-compute@developer.gserviceaccount.com 的資料列,然後點選該列中的「Edit principal」(編輯主體)

    如要取得專案的自動產生唯一 ID PROJECT_NUMBER,請按照下列步驟操作:

    1. 前往 Google Cloud 控制台的「Dashboard」(資訊主頁) 頁面。

      前往資訊主頁

    2. 按一下頁面頂端的 [Select from] (可用的選項) 下拉式清單。在隨即顯示的「Select from」視窗中,選取所需專案。

    專案資訊主頁的「專案資訊」資訊卡會顯示 PROJECT_NUMBER

  3. 按一下 「Add another role」(新增其他角色)

  4. 如要授予 roles/artifactregistry.reader 角色,請按一下「選取角色」,然後依序從「依產品或服務」和「角色」中選擇 Artifact RegistryArtifact Registry Reader

  5. 按一下 [儲存]。主體就會取得指定角色。

  6. 如要為 GKE 範例應用程式建立服務帳戶,請前往「服務帳戶」頁面。 前往「Service accounts」(服務帳戶)

  7. 選取專案。

  8. 在「專案『PROJECT_ID』的服務帳戶」頁面中,按一下「建立服務帳戶」

  9. 在「建立服務帳戶」頁面的「服務帳戶詳細資料」部分,於「服務帳戶名稱」欄位中輸入 GSA_NAME,例如 gke-alloydb-gsa

  10. 按一下「建立並繼續」

    「建立服務帳戶」頁面會顯示「將專案存取權授予這個服務帳戶 (選用)」部分。

  11. 如要授予 roles/alloydb.client 角色,請按照下列步驟操作:

    1. 按一下「選擇角色」
    2. 從「依產品或服務劃分」中選擇 Cloud AlloyDB
    3. 從「角色」中選擇 Cloud AlloyDB Client
  12. 按一下 「Add another role」(新增其他角色)

  13. 如要授予 roles/serviceusage.serviceUsageConsumer 角色,請按一下「選取角色」,然後依序從「依產品或服務」和「角色」中選擇 Service UsageService Usage Consumer

  14. 按一下 [完成]。Google 服務帳戶會取得角色。

gcloud

  1. 如要將必要權限授予預設 Google 服務帳戶,讓 Compute Engine 可以從 Artifact Registry 讀取資料,請執行下列指令:

    PROGECT_NUM=$(gcloud projects describe PROJECT_ID --format="value(projectNumber)")
    gcloud projects add-iam-policy-binding PROJECT_ID  --member="serviceAccount:$PROGECT_NUM-compute@developer.gserviceaccount.com"  --role="roles/artifactregistry.reader"
  2. 如要為應用程式建立 Google 服務帳戶,請建立 IAM 服務帳戶:

    gcloud iam service-accounts create GSA_NAME \
    --display-name="gke-tutorial-service-account"

    GSA_NAME 換成新的 IAM 服務帳戶名稱,例如 gke-alloydb-gsa

  3. 如要將 alloydb.clientserviceusage.serviceUsageConsumer 角色授予應用程式 GSA,請使用下列指令:

    gcloud projects add-iam-policy-binding PROJECT_ID --member=serviceAccount:GSA_NAME@PROJECT_ID.iam.gserviceaccount.com --role="roles/alloydb.client"
    gcloud projects add-iam-policy-binding PROJECT_ID --member=serviceAccount:GSA_NAME@PROJECT_ID.iam.gserviceaccount.com --role="roles/serviceusage.serviceUsageConsumer"

為範例應用程式設定 GKE 適用的工作負載身分聯盟

您需要設定 GKE,使用 Workload Identity Federation for GKE 功能,將服務帳戶提供給 AlloyDB Auth Proxy。這個方法可讓您將 Kubernetes 服務帳戶繫結至 Google 服務帳戶。這樣一來,應用程式就能使用相符的 Kubernetes 服務帳戶存取 Google 服務帳戶。

Google 服務帳戶是 IAM 身分,代表 Google Cloud中的應用程式。Kubernetes 服務帳戶是代表應用程式在 Google Kubernetes Engine 叢集中的身分。

Workload Identity Federation for GKE 會將 Kubernetes 服務帳戶繫結至 Google 服務帳戶。這個繫結會導致任何具有該 Kubernetes 服務帳戶的部署作業,在與 Google Cloud互動時,都以 Google 服務帳戶的身分進行驗證。

gcloud

  1. 在 Google Cloud 控制台中開啟 Cloud Shell

    開啟 Cloud Shell

  2. 在 Cloud Shell 中,取得叢集憑證:

    gcloud container clusters get-credentials GKE_CLUSTER_ID --region REGION --project PROJECT_ID

    這個指令會設定 kubectl 來使用您建立的 GKE 叢集。

  3. 在您選擇的編輯器中,完成下列步驟:

    1. 使用 nano 開啟 service-account.yaml,例如:

      nano service-account.yaml
    2. 在編輯器中貼上下列內容:

        apiVersion: v1
        kind: ServiceAccount
        metadata:
          name: KSA_NAME
      

      KSA_NAME 替換為服務帳戶名稱,例如 ksa-alloydb

    3. 依序按下 Control+OEnter 鍵儲存變更,然後按下 Control+X 退出編輯器。

  4. 為範例應用程式建立 Kubernetes 服務帳戶:

    kubectl apply -f service-account.yaml
  5. 在兩個服務帳戶之間建立 IAM 政策繫結,授予 Kubernetes 服務帳戶模擬 Google 服務帳戶的權限:

    gcloud iam service-accounts add-iam-policy-binding \
       --role="roles/iam.workloadIdentityUser" \
       --member="serviceAccount:PROJECT_ID.svc.id.goog[default/KSA_NAME]" \
       GSA_NAME@PROJECT_ID.iam.gserviceaccount.com
  6. 使用 Google 服務帳戶的電子郵件地址,將 iam.gke.io/gcp-service-account=GSA_NAME@PROJECT_ID 註解加入 Kubernetes 服務帳戶:

    kubectl annotate serviceaccount \
      KSA_NAME \
      iam.gke.io/gcp-service-account=GSA_NAME@PROJECT_ID.iam.gserviceaccount.com

將範例應用程式的映像檔填入 Artifact Registry

gcloud

  1. 在 Cloud Shell 中,使用下列指令從 GitHub 複製存放區和範例 gke-alloydb-app 應用程式程式碼:

     git clone https://github.com/GoogleCloudPlatform/alloydb-auth-proxy && cd alloydb-auth-proxy/examples/go
  2. 在 Artifact Registry 中建立 Docker 映像檔的存放區:

    gcloud artifacts repositories create REPOSITORY_ID --location REGION --repository-format=docker --project PROJECT_ID

    更改下列內容:

    • PROJECT_ID:您的專案 ID。
    • REPOSITORY_ID:存放區名稱,例如 gke-alloydb-sample-app
  3. 在「授權 Cloud Shell」對話方塊中,按一下「授權」。如果您先前已完成這個步驟,系統就不會顯示這項提示。

  4. 如要建構 Docker 容器並發布至 Artifact Registry,請使用下列指令:

     gcloud builds submit --tag  REGION-docker.pkg.dev/PROJECT_ID/REPOSITORY_ID/SAMPLE_APPLICATION --project PROJECT_ID

    更改下列內容:

    • PROJECT_ID:您的專案 ID。
    • REPOSITORY_ID:存放區名稱,例如 gke-alloydb-sample-app
    • SAMPLE_APPLICATION:範例網路應用程式的名稱,例如 gke-alloydb-app

建立 Kubernetes Secret

您要為範例應用程式使用的資料庫、使用者和使用者密碼建立 Kubernetes Secret。每個密鑰的值都以本教學課程「連線至主要執行個體,並建立 AlloyDB 資料庫和使用者」步驟中指定的值為準。詳情請參閱「密鑰」。

gcloud

使用 Kubernetes SECRET (例如 gke-alloydb-secret) 儲存連線資訊:

kubectl create secret generic SECRET \
  --from-literal=database=DATABASE_NAME \
  --from-literal=username=USERNAME \
  --from-literal=password=DATABASE_PASSWORD

以補充模式部署及執行 AlloyDB Proxy

基於下列原因,建議您以 sidecar 模式執行 AlloyDB Proxy,做為與應用程式共用 Pod 的額外容器:

  • 防止 SQL 流量在本機公開。AlloyDB Proxy 會加密傳出連線,但您必須限制傳入連線的曝光度。
  • 避免單點故障。每個應用程式的資料庫存取權彼此獨立,因此更具彈性。
  • 限制 AlloyDB Proxy 的存取權,讓您能為每個應用程式使用 IAM 權限,而不必將資料庫公開給整個叢集。
  • 可更準確地設定資源要求範圍。由於 AlloyDB Proxy 會根據用量線性消耗資源,因此這種模式可讓您更準確地設定和要求資源,以配合應用程式的擴充作業。
  • 可讓您設定應用程式,透過指令區段中指定的 DB_PORT,使用 127.0.0.1 連線。

建立 GKE 叢集並為應用程式建構容器映像檔後,請將容器化應用程式部署至 GKE 叢集。

gcloud

在本教學課程中,您將部署範例投票收集網頁應用程式 gke-alloydb-app,並使用 AlloyDB 做為資料存放區。

  1. 取得要連線至 AlloyDB Proxy 的 AlloyDB 主要執行個體連線 INSTANCE_URI

       gcloud alloydb instances describe INSTANCE_ID \
       --cluster=CLUSTER_ID \
       --region=REGION \
       --format="value(name)"

    更改下列內容:

    • INSTANCE_ID:執行個體的名稱,例如 alloydb-primary
    • CLUSTER_ID:叢集名稱,例如 alloydb-cluster

    輸出內容包含您在本節步驟 2.b 的 proxy_sidecar_deployment.yaml 定義檔案中指定的 INSTANCE_URI

  2. 在您選擇的編輯器 (例如 nano) 中,完成下列步驟:

    1. 使用您選擇的編輯器 (例如 nano) 開啟 proxy_sidecar_deployment.yaml

      nano proxy_sidecar_deployment.yaml
    2. 在編輯器中貼上下列內容:

      apiVersion: apps/v1
      kind: Deployment
      metadata:
        name: gke-alloydb
      spec:
        selector:
          matchLabels:
            app: SAMPLE_APPLICATION
        template:
          metadata:
            labels:
              app: SAMPLE_APPLICATION
          spec:
            serviceAccountName: KSA_NAME
            containers:
            - name: SAMPLE_APPLICATION
              # Replace <PROJECT_ID> and <REGION> with your project ID and region.
              image: REGION-docker.pkg.dev/PROJECT_ID/REPOSITORY_ID/SAMPLE_APPLICATION:latest
              imagePullPolicy: Always
              # This app listens on port 8080 for web traffic by default.
              ports:
              - containerPort: 8080
              env:
              - name: PORT
                value: "8080"
              # This project uses environment variables to determine
              # how you would like to run your application
              # To use the Go connector (recommended) - use INSTANCE NAME 
              # To use TCP - Setting INSTANCE_HOST will use TCP (e.g., 127.0.0.1)
              - name: INSTANCE_HOST
                value: "127.0.0.1"
              - name: DB_PORT
                value: "5432"
              # To use Automatic IAM Authentication (recommended)
              # use DB_IAM_USER instead of DB_USER
              # you may also remove the DB_PASS environment variable
              - name: DB_USER
                valueFrom:
                  secretKeyRef:
                    name: SECRET
                    key: username
              - name: DB_PASS
                valueFrom:
                 secretKeyRef:
                    name: SECRET
                    key: password
              - name: DB_NAME
                valueFrom:
                  secretKeyRef:
                    name: SECRET
                    key: database
           # If you are using the Go connector (recommended), you can
            # remove alloydb-proxy (everything below this line)
            - name: alloydb-proxy
              # This uses the latest version of the AlloyDB Auth proxy
              # It is recommended to use a specific version for production environments.
              # See: https://github.com/GoogleCloudPlatform/alloydb-auth-proxy
              image: gcr.io/alloydb-connectors/alloydb-auth-proxy:1.10.1
              command:
                - "/alloydb-auth-proxy"
                #AlloyDB instance name as parameter for the AlloyDB proxy
                # Use <INSTANCE_URI> 
                - "INSTANCE_URI"
              securityContext:
                # The default AlloyDB Auth proxy image runs as the
                # "nonroot" user and group (uid: 65532) by default.
                runAsNonRoot: true
              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"
      

      INSTANCE_URI 替換為步驟 1 中的 AlloyDB 主要執行個體路徑,例如 projects/PROJECT_ID/locations/REGION/clusters/CLUSTER_ID/instances/INSTANCE_ID

    3. 依序按下 Control+OEnter 鍵儲存變更,然後按下 Control+X 退出編輯器。

  3. 如要部署 gke-alloydb-app 應用程式,請套用您在上一個步驟中建立的 proxy_sidecar_deployment.yaml 定義檔案:

    kubectl apply -f proxy_sidecar_deployment.yaml
  4. 確認 Pod 中兩個容器的狀態皆為 running

    kubectl get pods

    輸出內容範例:

     NAME                          READY   STATUS    RESTARTS   AGE
     gke-alloydb-8d59bb4cc-62xgh   2/2     Running   0          2m53s
    
  5. 如要連線至 gke-alloydb-app 應用程式範例,請使用服務 (例如外部 HTTP 負載平衡器)。在您選擇的編輯器中,按照下列步驟操作:

    1. 使用 nano 開啟 service.yaml,例如:

      nano service.yaml
    2. 在 nano 編輯器中貼上下列內容:

      apiVersion: v1
      kind: Service
      metadata:
        name: SAMPLE_APPLICATION
      spec:
        type: LoadBalancer
        selector:
          app: SAMPLE_APPLICATION
        ports:
        - port: 80
          targetPort: 8080
      

      SAMPLE_APPLICATION 替換為範例網頁應用程式的名稱,例如 gke-alloydb-app

    3. 依序按下 Control+OEnter 鍵儲存變更,然後按下 Control+X 退出編輯器。

  6. 如要部署服務 gke-alloydb-app 應用程式,請套用 service.yaml 檔案:

     kubectl apply -f service.yaml
  7. 如要取得服務詳細資料 (包括服務的外部 IP 位址),請使用下列指令:

    kubectl get service

    輸出內容範例:

    NAME              TYPE           CLUSTER-IP       EXTERNAL-IP     PORT(S)        AGE
    gke-alloydb-app   LoadBalancer   34.118.229.246   35.188.16.172   80:32712/TCP   45s
    kubernetes        ClusterIP      34.118.224.1     <none>          443/TCP        85m
    
  8. 使用上一步驟中的外部 IP 值,透過下列網址存取範例應用程式:

    http://EXTERNAL-IP
    

設定檔範例

proxy_sidecar_deployment.yaml

# Copyright 2024 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:
      # Your application container goes here.
      - name: <YOUR-APPLICATION-NAME>
        image: <YOUR-APPLICATION-IMAGE-URL>
        env:
        - name: DB_HOST
          # The port value here (5432) should match the --port flag below.
          value: "localhost:5342"
        - 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
      # The Auth Proxy sidecar goes here.
      - name: alloydb-auth-proxy
        # Make sure you have automation that upgrades this version regularly.
        # A new version of the Proxy is released monthly with bug fixes,
        # security updates, and new features.
        image: gcr.io/alloydb-connectors/alloydb-auth-proxy:1.10.1
        args:
          # If you're connecting over public IP, enable this flag.
          # - "--public-ip"

          # If you're connecting with PSC, enable this flag:
          # - "--psc"

          # If you're using auto IAM authentication, enable this flag:
          # - "--auto-iam-authn"

          # Enable structured logging with Google's LogEntry format:
          - "--structured-logs"

          # Listen on localhost:5432 by default.
          - "--port=5432"
          # Specify your instance URI, e.g.,
          # "projects/myproject/locations/us-central1/clusters/mycluster/instances/myinstance"
          - "<INSTANCE-URI>"

        securityContext:
          # The default AlloyDB 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"

service.yaml

# Copyright 2024 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: v1
kind: Service
metadata:
  name: <YOUR-SERVICE-NAME>
spec:
  type: LoadBalancer
  selector:
    app: <YOUR-APPLICATION-NAME>
  ports:
  - port: 80
    targetPort: 8080

service-account.yaml

# Copyright 2024 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: v1
kind: ServiceAccount
metadata:
  name: <YOUR-KSA-NAME> # TODO(developer): replace this value

清除所用資源

如要避免系統向您的 Google Cloud 帳戶收取本教學課程所用資源的費用,請刪除含有相關資源的專案,或者保留專案但刪除個別資源。

刪除專案

如要避免付費,最簡單的方法就是刪除您為了本教學課程所建立的專案。

如要刪除專案,請進行以下操作:

  1. 前往 Google Cloud 控制台的「管理資源」頁面。

    管理資源

  2. 在專案清單中選取要刪除的專案,然後點按「刪除」。

  3. 在對話方塊中輸入PROJECT_ID,然後按一下「Shut down」(關閉) 刪除專案。

後續步驟