You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为GKE已存在的后端服务配置Session Affinity?

解决GKE后端服务会话亲和性配置问题

核心说明

会话亲和性(Session Affinity)是配置在**Google Cloud 后端服务(Backend Service)**上的,而非Gateway或负载均衡器的顶层配置。根据你的部署场景,分两种常见情况给出具体配置方法:

情况1:通过GKE LoadBalancer Service暴露服务

如果你的服务是通过K8s LoadBalancer类型的Service对外暴露,直接修改Service的YAML配置即可:

apiVersion: v1
kind: Service
metadata:
  name: your-backend-service
spec:
  type: LoadBalancer
  sessionAffinity: ClientIP  # 启用基于客户端IP的会话亲和性
  sessionAffinityConfig:
    clientIP:
      timeoutSeconds: 3600  # 可选,自定义亲和性超时时间,默认10800秒
  selector:
    app: your-backend-app
  ports:
  - port: 80
    targetPort: 8080

修改后执行kubectl apply -f your-service.yaml完成服务更新。

如果想用gcloud命令直接修改对应的Cloud后端服务:

  1. 先找到GKE Service关联的Cloud后端服务名称:执行kubectl get service your-backend-service -o jsonpath='{.status.loadBalancer.ingress[0].ip}'获取LB IP,再到Compute Engine -> 后端服务页面搜索关联服务;或用gcloud compute backend-services list --filter="loadBalancingScheme=EXTERNAL"筛选。
  2. 执行更新命令:
gcloud compute backend-services update [BACKEND_SERVICE_NAME] \
  --session-affinity=CLIENT_IP \
  --region=[你的集群所在区域]

情况2:通过External Application Load Balancer(Gateway API/Ingress)暴露服务

如果是用Gateway API或GKE Ingress配置的外部应用负载均衡,需通过BackendConfig或BackendPolicy资源配置:

用BackendConfig(适配GKE Ingress)

先创建BackendConfig资源:

apiVersion: cloud.google.com/v1
kind: BackendConfig
metadata:
  name: backend-affinity-config
spec:
  sessionAffinity:
    affinityType: "CLIENT_IP"
    affinityCookieTtlSec: 3600  # 可选,仅当使用HTTP_COOKIE类型时需配置Cookie超时

再在你的Service中关联该BackendConfig:

apiVersion: v1
kind: Service
metadata:
  name: your-backend-service
  annotations:
    cloud.google.com/backend-config: '{"default": "backend-affinity-config"}'
spec:
  selector:
    app: your-backend-app
  ports:
  - port: 80
    targetPort: 8080

用Gateway API的BackendPolicy

若使用Gateway API,创建BackendPolicy绑定到后端服务:

apiVersion: networking.x-k8s.io/v1alpha1
kind: BackendPolicy
metadata:
  name: backend-affinity-policy
spec:
  targetRef:
    group: ""
    kind: Service
    name: your-backend-service
  sessionAffinity:
    type: ClientIP
    clientIP:
      timeout: 3600s

控制台配置入口说明

你在负载均衡模块找不到配置选项,是因为会话亲和性属于后端服务的细分配置项。需进入Compute Engine -> 后端服务页面,找到对应GKE服务关联的后端服务,编辑时在「会话亲和性」下拉菜单选择CLIENT_IP或其他类型即可。

内容的提问来源于stack exchange,提问作者heyyy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 13:42:35