从 Google Kubernetes Engine (GKE) 连接到 AlloyDB for PostgreSQL

本教程介绍如何设置从 Google Kubernetes Engine Autopilot 集群中运行的应用到 AlloyDB 实例的连接。

AlloyDB 是一项 Google Cloud中与 PostgreSQL 兼容的全托管式数据库服务。

Google Kubernetes Engine 可帮助您自动部署、扩缩和管理 Kubernetes。

目标

  • 为 AlloyDB 构建 Docker 映像。
  • 在 Google Kubernetes Engine 中运行应用。
  • 使用 AlloyDB Auth Proxy 和内部 IP 连接到 AlloyDB 实例。

费用

本教程使用 Google Cloud的收费组件,包括:

  • AlloyDB
  • Google Kubernetes Engine
  • Artifact Registry

您可使用价格计算器根据您的预计使用情况来估算费用。

准备工作

控制台

  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. Make sure 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. Make sure that billing is enabled for your Google Cloud project.

  6. 启用创建和连接到 AlloyDB for PostgreSQL 所需的 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 的投票收集 Web 应用示例。

启动 Cloud Shell

Cloud Shell 是一种 shell 环境,用于管理在Google Cloud上托管的资源。

Cloud Shell 预安装有 Google Cloud CLIkubectl 命令行工具。gcloud CLI 为 Google Cloud提供了主要命令行界面。kubectl 为针对 Kubernetes 集群运行命令提供了主要命令行界面。

控制台

如需启动 Cloud Shell,请完成以下步骤。

  1. 转到 Google Cloud 控制台。

    Google Cloud 控制台

  2. 点击 Google Cloud 控制台顶部的 激活 Cloud Shell 按钮 激活 Cloud Shell

  3. 为 Cloud Shell 提供授权对话框中,点击授权

    控制台下方的框架内会打开一个 Cloud Shell 会话。请使用此 Shell 来运行 gcloudkubectl 命令。

    1. 在运行命令之前,请在 Google Cloud CLI 中使用以下命令设置默认项目:

      gcloud config set project PROJECT_ID

      PROJECT_ID 替换为您的项目 ID

创建 AlloyDB 集群及其主实例

您的 AlloyDB 集群由 Google Virtual Private Cloud (VPC) 中的多个节点组成。创建集群时,您还需要在其中一个 VPC 与包含新集群的 Google 管理的 VPC 之间配置专用服务访问通道。我们建议您使用内部 IP 访问权限,以免数据库暴露在公共互联网上。

如需从已配置的 VPC 外部连接到 AlloyDB for PostgreSQL 集群,您需要在 VPC 中为 AlloyDB 配置专用服务访问通道配置,并使用默认的 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,您可以将其用作 IP_RANGE_NAME,以便在第 3 步中创建专用连接。

  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 兼容,这是支持的默认 PostgreSQL 版本

      • 16:用于与 PostgreSQL 16(预览版)兼容

        如需详细了解使用预览版 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 实例的名称,例如 alloydb-primary
    • CLUSTER_ID 替换为 AlloyDB 集群的名称,例如 alloydb-cluster
    • NUM_CPU 替换为虚拟处理单元数量,例如 2
    • PROJECT_ID替换为 Google Cloud 项目的 ID。
    • REGION 替换为在其中创建 AlloyDB 集群的区域的名称,例如 us-central1

    等待 AlloyDB 实例创建完成。此过程可能耗时几分钟。

连接到主实例并创建 AlloyDB 数据库和用户

控制台

  1. 如果您不在新创建的集群的概览页面中,请在 Google Cloud 控制台中前往集群页面。

    转到集群

  2. 如需显示集群概览页面,请点击 CLUSTER_ID 集群名称。

  3. 在导航菜单中,点击 AlloyDB Studio

  4. 登录 AlloyDB Studio 页面上,执行以下操作:

    1. 数据库列表中,选择 postgres

    2. 用户列表中,选择 postgres

    3. 密码字段中,输入您在创建 AlloyDB 集群及其主实例中创建的 CLUSTER_PASSWORD

    4. 点击身份验证探索器窗格会显示数据库中的对象列表。

  5. 编辑器 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';
      

      替换以下内容:

      • USERNAME:AlloyDB 用户的名称,例如 tutorial_user

      • DATABASE_PASSWORD:AlloyDB 数据库的密码,例如 tutorial

    5. 点击运行。等待结果窗格中显示 Statement executed successfully 消息。

  6. 在 AlloyDB Studio 的探索器窗格中,点击 切换用户/数据库

  7. 登录 AlloyDB Studio 页面上,执行以下操作:

    1. 数据库列表中,选择 DATABASE_NAME,例如 tutorial_db

    2. 用户列表中,选择 postgres

    3. 密码字段中,输入您在创建 AlloyDB 集群及其主实例中创建的 CLUSTER_PASSWORD

    4. 点击身份验证探索器窗格会显示数据库中的对象列表。

  8. 编辑器 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 Secret 中使用这些信息。

创建 GKE Autopilot 集群

一个集群包含至少一个集群控制平面机器和多个称为“节点”的工作器机器。节点是运行 Kubernetes 进程的 Compute Engine 虚拟机 (VM) 实例;必须执行这些进程,才能将节点加入集群中。您将应用部署到集群,该应用在节点上运行。

控制台

  1. 在 Google Cloud 控制台中,转到 Kubernetes 集群页面。

    转到“Kubernetes 集群”

  2. 点击创建

  3. 集群基本信息页面的名称字段中,为 Autopilot 集群指定 GKE_CLUSTER_ID,例如 ap-cluster

  4. 区域字段中,选择 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 代理进行连接时,系统会使用 sidecar 容器模式将其添加到 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. 项目“PROJECT_ID”的权限页面上,找到包含默认 Compute Engine 服务账号 PROJECT_NUMBER-compute@developer.gserviceaccount.com 的行,然后点击该行中的 修改主账号

    如需获取 PROJECT_NUMBER(系统为项目自动生成的唯一标识符),请执行以下操作:

    1. 前往 Google Cloud 控制台中的信息中心页面。

      转到信息中心

    2. 点击页面顶部的请选择:下拉列表。在显示的请选择:窗口中,选择您的项目。

    PROJECT_NUMBER 会显示在项目信息中心的项目信息卡片上。

  3. 点击 添加其他角色

  4. 如需授予 roles/artifactregistry.reader 角色,请点击选择角色,然后从按产品或服务中选择 Artifact Registry,并从角色中选择 Artifact Registry Reader

  5. 点击保存。系统会向主账号授予该角色。

  6. 如需为 GKE 示例应用创建服务账号,请前往服务账号页面。前往“服务账号”

  7. 选择您的项目。

  8. 项目“PROJECT_ID”的服务账号页面上,点击创建服务账号

  9. 创建服务账号页面的服务账号详情部分的服务账号名称字段中输入 GSA_NAME,例如 gke-alloydb-gsa

  10. 点击创建并继续

    系统会显示创建服务账号页面的向此服务账号授予对项目的访问权限(可选)部分。

  11. 如需授予 roles/alloydb.client 角色,请执行以下操作:

    1. 点击选择角色
    2. 按产品或服务中选择 Cloud AlloyDB
    3. 角色中选择 Cloud AlloyDB Client
  12. 点击 添加其他角色

  13. 如需授予 roles/serviceusage.serviceUsageConsumer 角色,请点击选择角色,然后从按产品或服务中选择 Service Usage,并从角色中选择 Service 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. 如需向应用 GSA 授予 alloydb.clientserviceusage.serviceUsageConsumer 角色,请使用以下命令:

    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"

为示例应用配置 Workload Identity Federation for GKE

您需要配置 GKE,以使用 Workload Identity Federation for GKE 功能向 AlloyDB Auth Proxy 提供服务账号。使用此方法,您可以将 Kubernetes 服务账号绑定到 Google 服务账号。然后,应用可以使用匹配的 Kubernetes 服务账号访问 Google 服务账号。

Google 服务账号是在 Google Cloud中代表应用的 IAM 身份。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. Ctrl+O,然后按 Enter 键保存更改,再按 Ctrl+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 服务账号的电子邮件地址,向 Kubernetes 服务账号添加 iam.gke.io/gcp-service-account=GSA_NAME@PROJECT_ID 注解。

    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:示例 Web 应用的名称,例如 gke-alloydb-app

创建 Kubernetes Secret

您将为示例应用要使用的数据库、用户和用户密码创建 Kubernetes Secret。每个 Secret 的值均基于本教程连接到主实例并创建 AlloyDB 数据库和用户步骤中指定的值。如需了解详情,请参阅 Secret

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 会根据用量以线性方式使用资源,因此此模式可让您更准确地确定资源范围,并按应用扩缩情况请求资源。
  • 让您能够将应用配置为使用 127.0.0.1 通过您在命令部分中指定的 DB_PORT 进行连接。

创建 GKE 集群并为应用构建容器映像后,将您的容器化应用部署到 GKE 集群。

gcloud

在本教程中,您将部署投票收集 Web 应用 gke-alloydb-app 示例,该应用使用 AlloyDB 作为数据存储区。

  1. 获取您希望 AlloyDB 代理连接到的 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. Ctrl+O,然后按 Enter 键保存更改,再按 Ctrl+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 替换为您的示例 Web 应用的名称,例如 gke-alloydb-app

    3. Ctrl+O,然后按 Enter 键保存更改,再按 Ctrl+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,然后点击关停以删除项目。

后续步骤