使用政策配置网关资源

本页面介绍如何配置您在 Google Kubernetes Engine (GKE) 集群中部署网关时 Google Kubernetes Engine (GKE) 创建的负载均衡器。

部署网关时,GatewayClass 配置决定了 GKE 创建的负载均衡器。系统已使用默认设置预先配置此代管式负载均衡器,您可以使用政策进行修改。

您可以通过将政策附加到网关、Service 或 ServiceImport 来自定义网关资源,以满足您的基础设施或应用要求。应用或修改政策后,您无需删除或重新创建网关、路由或服务资源,该政策由网关控制器处理,并且底层负载均衡器资源是根据(新)政策进行(重新)配置的。

准备工作

在开始之前,请确保您已执行以下任务:

  • 启用 Google Kubernetes Engine API。
  • 启用 Google Kubernetes Engine API
  • 如果您要使用 Google Cloud CLI 执行此任务,请安装初始化 gcloud CLI。 如果您之前安装了 gcloud CLI,请运行 gcloud components update 以获取最新版本。

GKE Gateway Controller 要求

  • VPC 原生集群支持 Gateway API。
  • 如果您使用的是内部 GatewayClass,则必须启用代理专用子网
  • 集群必须启用 HttpLoadBalancing 插件。
  • 如果您使用的是 Istio,则必须将 Istio 升级到以下版本之一:
    • 1.15.2 或更高版本
    • 1.14.5 或更高版本
    • 1.13.9 或更高版本。
  • 如果您使用的是共享 VPC,则需要在宿主项目中将 Compute Network User 角色分配给服务项目的 GKE 服务账号。

限制和局限

除了 GKE Gateway Controller 的限制和局限之外,以下限制还专门适用于应用于 Gateway 资源的政策:

  • GCPGatewayPolicy 资源只能关联到 gateway.networking.k8s.io Gateway

  • GCPGatewayPolicy 资源必须与目标 Gateway 位于同一命名空间中。

  • 使用单集群网关时,GCPBackendPolicyHealthCheckPolicy 资源必须引用 Service 资源。

  • 使用多集群网关时,GCPBackendPolicyHealthCheckPolicy 资源必须引用 ServiceImport 资源。

  • 在任何给定时间,只能将一个 GCPBackendPolicy 附加到一个 Service。如果创建了两个以同一 ServiceServiceImport 为目标的 GCPBackendPolicy 政策,则最早创建的政策优先,第二个政策无法附加。

  • GKE 网关不支持分层政策。

  • HealthCheckPolicyGCPBackendPolicy 资源必须与目标 ServiceServiceImport 资源位于同一命名空间中。

  • GCPBackendPolicyHealthCheckPolicy 资源的结构方式使其只能引用一个后端服务。

  • GCPBackendPolicy 不支持会话亲和性的 HEADER_FIELDHTTP_COOKIE 选项。

为区域级内部网关配置全球访问权限

本部分介绍运行 1.24 或更高版本的 GKE 集群提供的功能。

如需使用内部网关启用全球访问权限,请将政策关联到网关资源。

以下 GCPGatewayPolicy 清单启用地区内部网关以实现全球访问权限:

apiVersion: networking.gke.io/v1
kind: GCPGatewayPolicy
metadata:
  name: my-gateway-policy
  namespace: default
spec:
  default:
    # Enable global access for the regional internal Application Load Balancer.
    allowGlobalAccess: true
  targetRef:
    group: gateway.networking.k8s.io
    kind: Gateway
    name: my-gateway

为多集群 Gateway 配置区域

本部分介绍运行 1.30.3-gke.1225000 或更高版本的 GKE 集群提供的功能。

如果您的舰队在多个区域拥有集群,您可能需要在不同的区域部署区域网关,以满足各种用例,例如跨区域冗余、低延迟和数据主权。在多集群网关配置集群中,您可以指定要部署区域性网关的区域。如果您未指定区域,则默认区域为配置集群的区域。

如需为多集群 Gateway 配置区域,请使用 GCPGatewayPolicy 中的 region 字段。在以下示例中,Gateway 是在 us-central1 区域中配置的:

apiVersion: networking.gke.io/v1
kind: GCPGatewayPolicy
metadata:
  name: my-gateway-policy
  namespace: default
spec:
  default:
    region: us-central1
  targetRef:
    group: gateway.networking.k8s.io
    kind: Gateway
    name: my-regional-gateway

配置 SSL 政策以保护客户端到负载均衡器的流量

本部分介绍运行 1.24 或更高版本的 GKE 集群提供的功能。

如需保护客户端到负载均衡器的流量,请将政策名称添加到 GCPGatewayPolicy,以配置 SSL 政策。默认情况下,网关未定义并关联任何 SSL 政策。

确保在 GCPGatewayPolicy 中引用该政策之前创建 SSL 政策

以下 GCPGatewayPolicy 清单指定了名为 gke-gateway-ssl-policy 的安全政策:

apiVersion: networking.gke.io/v1
kind: GCPGatewayPolicy
metadata:
  name: my-gateway-policy
  namespace: team1
spec:
  default:
    sslPolicy: gke-gateway-ssl-policy
  targetRef:
    group: gateway.networking.k8s.io
    kind: Gateway
    name: my-gateway

配置健康检查

本部分介绍运行 1.24 或更高版本的 GKE 集群提供的功能。

默认情况下,对于使用 HTTPkubernetes.io/h2c 应用协议的后端服务,HealthCheck 为 HTTP 类型。对于 HTTPS 协议,默认的健康检查属于 HTTPS 类型。对于 HTTP2 协议,默认的健康检查属于 HTTP2 类型。

您可以使用 HealthCheckPolicy 控制负载均衡器的健康检查设置。每种类型的健康检查(httphttpsgrpchttp2tcp)都有可供您定义的参数。 Google Cloud会为每个 GKE Service 的每项后端服务创建唯一的健康检查。

为了让负载均衡器正常运行,如果您的健康检查路径不是标准的“/”,您可能需要为负载均衡器配置自定义 HealthCheckPolicy。如果路径需要特殊标头,或者您需要调整健康检查参数,也需要进行此配置。例如,如果默认请求路径为“/”,但您的服务无法通过该请求路径访问,而是使用“/health”报告其健康状况,那么您必须在 HealthCheckPolicy 中相应地配置 requestPath

以下 HealthCheckPolicy 清单显示了配置健康检查政策时可用的所有字段:

服务

# Health check configuration for the load balancer. For more information
# about these fields, see https://cloud.google.com/compute/docs/reference/rest/v1/healthChecks.
apiVersion: networking.gke.io/v1
kind: HealthCheckPolicy
metadata:
  name: lb-healthcheck
  namespace: lb-service-namespace
spec:
  default:
    checkIntervalSec: INTERVAL  # The default value is 15 seconds.
    timeoutSec: TIMEOUT
    healthyThreshold: HEALTHY_THRESHOLD
    unhealthyThreshold: UNHEALTHY_THRESHOLD
    logConfig:
      enabled: ENABLED
    config:
      type: PROTOCOL
      httpHealthCheck:
        portSpecification: PORT_SPECIFICATION
        port: PORT
        host: HOST
        requestPath: REQUEST_PATH
        response: RESPONSE
        proxyHeader: PROXY_HEADER
      httpsHealthCheck:
        portSpecification: PORT_SPECIFICATION
        port: PORT
        host: HOST
        requestPath: REQUEST_PATH
        response: RESPONSE
        proxyHeader: PROXY_HEADER
      grpcHealthCheck:
        grpcServiceName: GRPC_SERVICE_NAME
        portSpecification: PORT_SPECIFICATION
        port: PORT
      http2HealthCheck:
        portSpecification: PORT_SPECIFICATION
        port: PORT
        host: HOST
        requestPath: REQUEST_PATH
        response: RESPONSE
        proxyHeader: PROXY_HEADER
      tcpHealthCheck:
        portSpecification: PORT_SPECIFICATION
        port: PORT
        portName: PORT_NAME
        request: REQUEST
        response: RESPONSE
        proxyHeader: PROXY_HEADER
  # Attach to a Service in the cluster.
  targetRef:
    group: ""
    kind: Service
    name: lb-service

多集群服务

apiVersion: networking.gke.io/v1
kind: HealthCheckPolicy
metadata:
  name: lb-healthcheck
  namespace: lb-service-namespace
spec:
  # The default and config fields control the health check configuration for the
  # load balancer. For more information about these fields, see
  # https://cloud.google.com/compute/docs/reference/rest/v1/healthChecks.
  default:
    checkIntervalSec: INTERVAL
    timeoutSec: TIMEOUT
    healthyThreshold: HEALTHY_THRESHOLD
    unhealthyThreshold: UNHEALTHY_THRESHOLD
    logConfig:
      enabled: ENABLED
    config:
      type: PROTOCOL
      httpHealthCheck:
        portSpecification: PORT_SPECIFICATION
        port: PORT
        host: HOST
        requestPath: REQUEST_PATH
        response: RESPONSE
        proxyHeader: PROXY_HEADER
      httpsHealthCheck:
        portSpecification: PORT_SPECIFICATION
        port: PORT
        host: HOST
        requestPath: REQUEST_PATH
        response: RESPONSE
        proxyHeader: PROXY_HEADER
      grpcHealthCheck:
        grpcServiceName: GRPC_SERVICE_NAME
        portSpecification: PORT_SPECIFICATION
        port: PORT
      http2HealthCheck:
        portSpecification: PORT_SPECIFICATION
        port: PORT
        host: HOST
        requestPath: REQUEST_PATH
        response: RESPONSE
        proxyHeader: PROXY_HEADER
      tcpHealthCheck:
        portSpecification: PORT_SPECIFICATION
        port: PORT
        portName: PORT_NAME
        request: REQUEST
        response: RESPONSE
        proxyHeader: PROXY_HEADER
  # Attach to a multi-cluster Service by referencing the ServiceImport.
  targetRef:
    group: net.gke.io
    kind: ServiceImport
    name: lb-service

替换以下内容:

  • INTERVAL:为每个健康检查探测器指定 check-interval(以秒为单位)。这是指从探测器检查开始到其下一次检查开始的时间。如果您省略此参数,则在未指定 HealthCheckPolicy 时, Google Cloud 的默认值为 15 秒;在指定了 HealthCheckPolicy 但未指定 checkIntervalSec 值时,默认值为 5 秒。如需了解详情,请参阅多重探测和频率
  • TIMEOUT:指定Google Cloud 等待探测响应的时长。TIMEOUT 的值必须小于或等于 INTERVAL。该时间以秒为单位。每个探测都要求在探测超时之前传送 HTTP 200 (OK) 响应代码。
  • HEALTHY_THRESHOLDUNHEALTHY_THRESHOLD:指定至少一个探测器必须进行的成功或失败顺序连接尝试次数,以将健康状况从健康更改为不健康,或从不健康更改为健康。如果您省略其中一个参数,则使用 Google Cloud 默认值 2。
  • PROTOCOL:指定探测系统用于健康检查的协议。如需了解详情,请参阅 HTTP、HTTPS、HTTP/2 成功标准gRPC 成功标准TCP 成功标准。此参数必不可少。
  • ENABLED:指定日志记录是已启用还是已停用。
  • PORT_SPECIFICATION:指定健康检查使用固定端口 (USE_FIXED_PORT)、指定端口 (USE_NAMED_PORT) 还是服务端口 (USE_SERVING_PORT)。如果未指定,健康检查将遵循 port 字段中指定的行为。如果未指定 port,则此字段默认为 USE_SERVING_PORT
  • PORT:HealthCheckPolicy 仅支持使用端口号指定负载均衡器的健康检查端口。如果省略此参数,则使用 Google Cloud 默认值 80。由于负载均衡器将探测直接发送到 Pod 的 IP 地址,因此您应该选择与服务 Pod 的 containerPort 匹配的端口,即使 containerPort 被 Service 的 targetPort 引用也是如此。您并非只能使用 Service 的 targetPort 引用的 containerPorts
  • HOST:健康检查请求中主机标头的值。此值使用主机名的 RFC 1123 定义,但不允许使用数字 IP 地址。如果未指定或留空,则此值默认为健康检查的 IP 地址。
  • REQUEST:指定在建立 TCP 连接后要发送的应用数据。如果未指定,则值默认为空。 如果请求和响应都为空,则已建立的连接本身就表示健康状况良好。请求数据只能采用 ASCII 格式。
  • REQUEST_PATH:指定健康检查请求的路径。如果未指定或留空,则默认为 /
  • RESPONSE:指定要与响应数据开头匹配的字节。如果未指定或留空,GKE 会将所有响应解读为健康。响应数据只能为 ASCII 字符。
  • PROXY_HEADER:指定代理标头类型。您可以使用 NONEPROXY_V1。默认值为 NONE
  • GRPC_SERVICE_NAME:gRPC Service 的可选名称。省略此字段可指定所有 Service。

如需详细了解 HealthCheckPolicy 字段,请参阅 healthChecks 参考文档

配置 Cloud Armor 后端安全政策以保护您的后端服务

本部分介绍运行 1.24 或更高版本的 GKE 集群提供的功能。

通过将安全政策的名称添加到 GCPBackendPolicy 来配置 Cloud Armor 后端安全政策,以保护您的后端服务。默认情况下,Gateway 没有定义并关联任何 Cloud Armor 后端安全政策。

确保在 GCPBackendPolicy 中引用该政策之前创建 Cloud Armor 后端安全政策。如果您要启用区域级 Gateway,则必须创建区域级 Cloud Armor 后端安全政策。

以下 GCPBackendPolicy 清单指定了名为 example-security-policy 的后端安全政策:

服务

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    # Apply a Cloud Armor security policy.
    securityPolicy: example-security-policy
  # Attach to a Service in the cluster.
  targetRef:
    group: ""
    kind: Service
    name: lb-service

多集群服务

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    # Apply a Cloud Armor security policy.
    securityPolicy: example-security-policy
  # Attach to a multi-cluster Service by referencing the ServiceImport.
  targetRef:
    group: net.gke.io
    kind: ServiceImport
    name: lb-service

配置 IAP

本部分介绍运行 1.24 或更高版本的 GKE 集群提供的功能。

Identity-Aware Proxy (IAP) 会对与 HTTPRoute 关联的后端服务强制执行访问权限控制政策。借助此强制执行措施,只有分配了正确 Identity and Access Management (IAM) 角色且经过身份验证的用户或应用才能访问这些后端服务。

默认情况下,后端服务未应用 IAP,您需要在 GCPBackendPolicy 中明确配置 IAP。

如需通过 Gateway 配置 IAP,请执行以下操作:

  1. 为 GKE 启用 IAP 请勿配置后端(配置 BackendConfig),因为 BackendConfig 仅在 Ingress 部署中有效。

  2. 为 IAP 创建 Secret:

    1. 在 Google Cloud 控制台中,前往凭证页面:

      进入“凭据”页面

    2. 点击相应客户端的名称,然后下载 OAuth 客户端文件。

    3. 从 OAuth 客户端文件中,将 OAuth secret 复制到剪贴板。

    4. 创建名为 iap-secret.txt 的文件。

    5. 使用以下命令将 OAuth Secret 粘贴到 iap-secret.txt 文件中:

      echo -n CLIENT_SECRET > iap-secret.txt
      kubectl create secret generic SECRET_NAME --from-file=key=iap-secret.txt
      
  3. 如需指定引用 Secret 的 IAP 政策,请执行以下操作:

    1. 创建以下 GCPBackendPolicy 清单,并分别替换 SECRET_NAMECLIENT_ID。将清单保存为 backend-policy.yaml

      服务

      apiVersion: networking.gke.io/v1
      kind: GCPBackendPolicy
      metadata:
        name: backend-policy
      spec:
        default:
          # IAP OAuth2 settings. For more information about these fields,
          # see https://cloud.google.com/iap/docs/reference/rest/v1/IapSettings#oauth2.
          iap:
            enabled: true
            oauth2ClientSecret:
              name: SECRET_NAME
            clientID: CLIENT_ID
        # Attach to a Service in the cluster.
        targetRef:
          group: ""
          kind: Service
          name: lb-service
      

      多集群服务

      apiVersion: networking.gke.io/v1
      kind: GCPBackendPolicy
      metadata:
        name: backend-policy
      spec:
        default:
          # IAP OAuth2 settings. For more information about these fields,
          # see https://cloud.google.com/iap/docs/reference/rest/v1/IapSettings#oauth2.
          iap:
            enabled: true
            oauth2ClientSecret:
              name: SECRET_NAME
            clientID: CLIENT_ID
        # Attach to a multi-cluster Service by referencing the ServiceImport.
        targetRef:
          group: net.gke.io
          kind: ServiceImport
          name: lb-service
      
    2. 应用 backend-policy.yaml 清单:

      kubectl apply -f backend-policy.yaml
      
  4. 验证配置:

    1. 确认在创建具有 IAP 的 GCPBackendPolicy 后,政策已应用:

      kubectl get gcpbackendpolicy
      

      输出类似于以下内容:

      NAME             AGE
      backend-policy   45m
      
    2. 如需了解更多详情,请使用 describe 命令:

      kubectl describe gcpbackendpolicy
      

      输出类似于以下内容:

      Name:         backend-policy
      Namespace:    default
      Labels:       <none>
      Annotations:  <none>
      API Version:  networking.gke.io/v1
      Kind:         GCPBackendPolicy
      Metadata:
        Creation Timestamp:  2023-05-27T06:45:32Z
        Generation:          2
        Resource Version:    19780077
        UID:                 f4f60a3b-4bb2-4e12-8748-d3b310d9c8e5
      Spec:
        Default:
          Iap:
            Client ID:  441323991697-luotsrnpboij65ebfr13hlcpm5a4heke.apps.googleusercontent.com
            Enabled:    true
            oauth2ClientSecret:
              Name:  my-iap-secret
        Target Ref:
          Group:
          Kind:   Service
          Name:   lb-service
      Status:
        Conditions:
          Last Transition Time:  2023-05-27T06:48:25Z
          Message:
          Reason:                Attached
          Status:                True
          Type:                  Attached
      Events:
        Type     Reason  Age                 From                   Message
        ----     ------  ----                ----                   -------
        Normal   ADD     46m                 sc-gateway-controller  default/backend-policy
        Normal   SYNC    44s (x15 over 43m)  sc-gateway-controller  Application of GCPBackendPolicy "default/backend-policy" was a success
      

配置后端服务超时

本部分介绍运行 1.24 或更高版本的 GKE 集群提供的功能。

以下 GCPBackendPolicy 清单指定了 40 秒的后端服务超时时间段。timeoutSec 字段默认为 30 秒。

服务

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    # Backend service timeout, in seconds, for the load balancer. The default
    # value is 30.
    timeoutSec: 40
  # Attach to a Service in the cluster.
  targetRef:
    group: ""
    kind: Service
    name: lb-service

多集群服务

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    timeoutSec: 40
  # Attach to a multi-cluster Service by referencing the ServiceImport.
  targetRef:
    group: net.gke.io
    kind: ServiceImport
    name: lb-service

使用 GCPBackendPolicy 配置后端选择

借助 GCPBackendPolicy 中的 CUSTOM_METRICS 均衡模式,您可以配置特定的自定义指标,以影响负载均衡器的后端服务分配流量的方式。此均衡模式可根据您定义的且由应用后端报告的自定义指标实现负载均衡。

如需了解详情,请参阅使用基于自定义指标的负载均衡进行流量管理

backends[] 字段中的 customMetrics[] 数组包含以下字段:

  • name:指定自定义指标的用户定义名称。
  • maxUtilization:为此指标设置目标或最大利用率。有效范围为 [0, 100]。
  • dryRun:布尔值字段。如果为 true,指标数据会报告给 Cloud Monitoring,但不会影响负载均衡决策。

示例

以下示例展示了一个 GCPBackendPolicy 清单,该清单配置了用于后端选择和端点级路由的自定义指标。

  1. 将以下清单保存为 my-backend-policy.yaml

    kind: GCPBackendPolicy
    apiVersion: networking.gke.io/v1
    metadata:
      name: my-backend-policy
      namespace: team-awesome
    spec:
      # Attach to the super-service Service.
      targetRef:
        kind: Service
        name: super-service
      default:
        backends:
        # Configuration for all locations.
        - location: "*"
          # Use the rate balancing mode for the load balancer.
          balancingMode: RATE
          # Maximum number of requests per second for each endpoint.
          maxRatePerEndpoint: 9000
        # Configuration for us-central1-a
        - location: us-central1-a
          # maxRatePerEndpoint: 9000 inherited from the * configuration.
          # Use the custom metrics balancing mode for the load balancer.
          balancingMode: CUSTOM_METRICS
          # Configure the custom metrics for the load balancer to use.
          customMetrics:
          - name: gpu-load
            maxUtilization: 100 # value ranges from 0 to 100 and maps to the floating pointrange [0.0, 1.0]
            dryRun: false
    
  2. 将清单应用到您的集群:

    kubectl apply -f my-backend-policy.yaml
    

负载均衡器会根据RATE均衡模式和自定义gpu-load指标分配流量。

使用 GCPTrafficDistributionPolicy 配置端点级路由

GCPTrafficDistributionPolicy 用于配置后端内端点选择的负载均衡算法。选择 WEIGHTED_ROUND_ROBIN 后,负载均衡器会使用根据报告的指标(包括自定义指标)得出的权重,将流量分配给各个实例或端点。

GCPTrafficDistributionPolicy 资源的 WEIGHTED_ROUND_ROBIN localityLbPolicy 字段用于指定负载均衡算法,以选择后端中的各个实例或端点。使用此算法时,政策会利用自定义指标来计算负载分配的权重。

GCPTrafficDistributionPolicy 配置中的 customMetrics[] 数组包含以下字段:

  • name:指定自定义指标的用户定义名称。
  • dryRun:布尔值字段。如果为 true,指标数据会报告给 Cloud Monitoring,但不会影响负载均衡。

如需了解详情,请参阅使用基于自定义指标的负载均衡进行流量管理

示例

以下示例展示了一个 GCPTrafficDistributionPolicy 清单,该清单通过使用 WEIGHTED_ROUND_ROBIN 负载均衡算法和自定义指标来配置端点级路由。

  1. 将以下示例清单保存为 GCPTrafficDistributionPolicy.yaml

    apiVersion: networking.gke.io/v1
    kind: GCPTrafficDistributionPolicy
    metadata:
      name: echoserver-v2
      namespace: team1
    spec:
      targetRefs:
      # Attach to the echoserver-v2 Service in the cluster.
      - kind: Service
        group: ""
        name: echoserver-v2
      default:
        # Use custom metrics to distribute traffic across endpoints.
        localityLbAlgorithm: WEIGHTED_ROUND_ROBIN
        # Configure metrics from an ORCA load report to use for traffic
        # distribution.
        customMetrics:
        - name: orca.named_metrics.bescm11
          dryRun: false
        - name: orca.named_metrics.bescm12
          dryRun: true
    
  2. 将清单应用到您的集群:

    kubectl apply -f GCPTrafficDistributionPolicy.yaml
    

负载均衡器会根据 WEIGHTED_ROUND_ROBIN 算法并使用提供的自定义指标将流量分配给端点。

配置会话亲和性

本部分介绍运行 1.24 或更高版本的 GKE 集群提供的功能。

您可以根据以下条件配置会话亲和性

  • 客户端 IP 地址
  • 生成的 Cookie

为服务配置会话亲和性时,网关的 localityLbPolicy 设置会设为 MAGLEV

GCPBackendPolicy 中移除会话亲和性配置后,Gateway 会将 localityLbPolicy 设置还原为默认值 ROUND_ROBIN

以下 GCPBackendPolicy 清单基于客户端 IP 地址指定会话亲和性:

服务

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    # On a best-effort basis, send requests from a specific client IP address
    # to the same backend. This field also sets the load balancer locality
    # policy to MAGLEV. For more information, see
    # https://cloud.google.com/load-balancing/docs/backend-service#lb-locality-policy
    sessionAffinity:
      type: CLIENT_IP
  targetRef:
    group: ""
    kind: Service
    name: lb-service

多集群服务

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    # On a best-effort basis, send requests from a specific client IP address
    # to the same backend. This field also sets the load balancer locality
    # policy to MAGLEV. For more information, see
    # https://cloud.google.com/load-balancing/docs/backend-service#lb-locality-policy
    sessionAffinity:
      type: CLIENT_IP
  targetRef:
    group: net.gke.io
    kind: ServiceImport
    name: lb-service

以下 GCPBackendPolicy 清单基于生成的 Cookie 指定会话亲和性,并将 Cookie TTL 配置为 50 秒:

服务

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    # Include an HTTP cookie in the Set-Cookie header of the response.
    # This field also sets the load balancer locality policy to MAGLEV. For more
    # information, see
    # https://cloud.google.com/load-balancing/docs/l7-internal#generated_cookie_affinity.
    sessionAffinity:
      type: GENERATED_COOKIE
      cookieTtlSec: 50  # The cookie expires in 50 seconds.
  targetRef:
    group: ""
    kind: Service
    name: lb-service

多集群服务

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    # Include an HTTP cookie in the Set-Cookie header of the response.
    # This field also sets the load balancer locality policy to MAGLEV. For more
    # information, see
    # https://cloud.google.com/load-balancing/docs/l7-internal#generated_cookie_affinity.
    sessionAffinity:
      type: GENERATED_COOKIE
      cookieTtlSec: 50  # The cookie expires in 50 seconds.
  targetRef:
    group: net.gke.io
    kind: ServiceImport
    name: lb-service

您可以将以下值用于 sessionAffinity.type 字段:

  • CLIENT_IP
  • GENERATED_COOKIE
  • NONE

配置连接排空超时

本部分介绍运行 1.24 或更高版本的 GKE 集群提供的功能。

您可以使用 GCPBackendPolicy 配置连接排空超时。连接排空超时是指等待连接排空的时间(以秒为单位)。超时持续时间可以介于 0 到 3600 秒之间。 默认值为 0,此值也会停用连接排空。

以下 GCPBackendPolicy 清单指定 60 秒的连接排空超时:

服务

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    connectionDraining:
      drainingTimeoutSec: 60
  targetRef:
    group: ""
    kind: Service
    name: lb-service

多集群服务

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    connectionDraining:
      drainingTimeoutSec: 60
  targetRef:
    group: net.gke.io
    kind: ServiceImport
    name: lb-service

在指定的超时持续时间内,GKE 会等待对已移除后端发出的现有请求完成。负载均衡器不会向已移除的后端发送新请求。达到超时持续时间之后,GKE 会关闭与该后端的所有剩余连接。

HTTP 访问日志记录

本部分介绍运行 1.24 或更高版本的 GKE 集群提供的功能。

默认情况下:

  • Gateway 控制器会将来自客户端的所有 HTTP 请求记录到 Cloud Logging 中。
  • 采样率为 1,000,000,表示系统会记录所有请求。
  • 不记录任何可选字段。

您可以通过以下三种方式使用 GCPBackendPolicy 停用 Gateway 上的访问日志记录

  • 您可以将没有 logging 部分的 GCPBackendPolicy 保持不变
  • 您可以将 logging.enabled 设置为 false
  • 您可以将 logging.enabled 设置为 true,并将 logging.sampleRate 设置为 0

您还可以配置访问日志记录采样率和可选字段列表,例如“tls.cipher”或“orca_load_report”。

如需启用可选字段的日志记录,请执行以下操作:

  • logging.OptionalMode 设置为 CUSTOM
  • logging.optionalFields 中提供要记录的可选字段的列表。如需查看支持的字段列表,请参阅日志记录和监控

您可以通过以下两种方式停用可选字段的日志记录:

  • 您可以从 logging.optionalFields 中移除所有条目。
  • 您可以将 logging.OptionalMode 设置为 EXCLUDE_ALL_OPTIONAL

以下 GCPBackendPolicy 清单修改了访问日志记录的默认采样率,并将其设置为 HTTP 请求的 50%。该清单还可针对指定 Service 资源启用两个可选字段的日志记录:

服务

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    # Access logging configuration for the load balancer.
    logging:
      enabled: true
      # Log 50% of the requests. The value must be an integer between 0 and
      # 1000000. To get the proportion of requests to log, GKE
      # divides this value by 1000000.
      sampleRate: 500000
      # Log specific optional fields.
      optionalMode: CUSTOM
      optionalFields:
      - tls.cipher
      - orca_load_report.cpu_utilization
  targetRef:
    group: ""
    kind: Service
    name: lb-service

多集群服务

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: my-backend-policy
  namespace: lb-service-namespace
spec:
  default:
    # Access logging configuration for the load balancer.
    logging:
      enabled: true
      # Log 50% of the requests. The value must be an integer between 0 and
      # 1000000. To get the proportion of requests to log, GKE
      # divides this value by 1000000.
      sampleRate: 500000
      # Log specific optional fields.
      optionalMode: CUSTOM
      optionalFields:
      - tls.cipher
      - orca_load_report.cpu_utilization
  targetRef:
    group: net.gke.io
    kind: ServiceImport
    name: lb-service

此清单包含以下字段:

  • enable: true:明确启用访问日志记录。Logging 中提供日志。
  • sampleRate: 500000:指定记录 50% 的数据包。您可以使用介于 0 到 1000000 之间的值。GKE 通过除以 1000000,将此值转换为 [0, 1] 范围内的浮点值。只有当 enable 设置为 true 时,此字段才相关。sampleRate 是可选字段,但如果已配置,则必须设置 enable: true。如果 enable 设置为 true 但未提供 sampleRate,则 GKE 会将 enable 设置为 false
  • optionalMode: CUSTOM:指定应在日志条目中包含一组 optionalFields
  • optionalFields: tls.cipher, orca_load_report.cpu_utilization:指定日志条目应包含 TLS 握手所用密码的名称以及服务的 CPU 利用率(如果可用)。

为单集群 Gateway 配置基于流量的自动扩缩

确保您的 GKE 集群运行的是 1.31.1-gke.2008000 或更高版本。

如需在单集群网关中启用基于流量的自动扩缩和基于容量的负载均衡,您可以配置服务容量。Service 容量能够指定在 Pod 自动扩缩或流量溢出到其他可用集群之前 Service 可以接收的流量容量。

如需配置 Service 容量,请创建 Service 和关联的 GCPBackendPolicyGCPBackendPolicy 清单使用 maxRatePerEndpoint 字段,该字段定义了 Service 中每个 Pod 的每秒请求数 (RPS) 的最大值。以下 GCPBackendPolicy 清单定义了 RPS 的最大值 10:

apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: store
spec:
  default:
    maxRatePerEndpoint: 10
  targetRef:
    group: ""
    kind: Service
    name: store

如需详细了解基于流量的自动扩缩,请参阅基于负载均衡器流量的自动扩缩

问题排查

多个 GCPBackendPolicy 关联到同一 Service

具体情况:

GCPBackendPolicy 关联到 ServiceServiceImport 时,可能会出现以下状态条件:

status:
  conditions:
    - lastTransitionTime: "2023-09-26T20:18:03Z"
      message: conflicted with GCPBackendPolicy "[POLICY_NAME]" of higher precedence, hence not applied
      reason: Conflicted
      status: "False"
      type: Attached

原因:

此状态条件表示您尝试将第二个 GCPBackendPolicy 应用到已关联 GCPBackendPolicyServiceServiceImport

GKE Gateway 不支持将多个 GCPBackendPolicy 关联到同一 ServiceServiceImport。如需了解详情,请参阅限制和局限

临时解决方法:

配置一个包含所有自定义配置的 GCPBackendPolicy,并将其关联到 ServiceServiceImport

找不到 Cloud Armor 安全政策

具体情况:

在区域 Gateway 上启用 Cloud Armor 时,可能会显示以下错误消息:

Invalid value for field 'resource': '{
"securityPolicy":"projects/123456789/regions/us-central1/securityPolicies/<policy_name>"}'.
The given security policy does not exist.

原因:

此错误消息表示,您的 Google Cloud 项目中不存在指定的区域性 Cloud Armor 安全政策。

临时解决方法:

在项目中创建区域性 Cloud Armor 安全政策,并在 GCPBackendPolicy 中引用此政策。

后续步骤