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

EKS环境下配置AWS NLB粘性会话实现每次请求访问同一Pod

EKS环境配置AWS NLB粘性会话实现固定Pod访问方案

核心问题原因

你当前使用默认实例模式的NLB,目标组注册的是EC2节点的端口,即使NLB将同一客户端的请求转发到同一节点,节点上的kube-proxy也会默认将请求轮询转发到节点内的多个Pod,所以会出现每次访问不同Pod的情况。

配置方案

方案一(推荐):使用NLB IP目标模式,直接注册Pod到NLB目标组

该方案让NLB直接对接Pod IP,粘性规则直接作用在Pod层面,无需处理节点内部负载均衡逻辑,修改Service配置如下:

apiVersion: v1
kind: Service
metadata:
  name: nginx-nlb
  annotations:
    service.beta.kubernetes.io/aws-load-balancer-type: "nlb-ip"
    # 启用源IP粘性,超时时间设为86400秒(可按需调整)
    service.beta.kubernetes.io/aws-load-balancer-target-group-attributes: "stickiness.enabled=true,stickiness.type=source_ip,stickiness.timeout_seconds=86400"
spec:
  selector:
    app: nginx
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80
  type: LoadBalancer

方案二:保持实例目标模式,配合节点本地流量策略和Service会话亲和

如果无法使用IP目标模式,可以通过以下配置实现:

apiVersion: v1
kind: Service
metadata:
  name: nginx-nlb
  annotations:
    service.beta.kubernetes.io/aws-load-balancer-type: "nlb"
    service.beta.kubernetes.io/aws-load-balancer-target-group-attributes: "stickiness.enabled=true,stickiness.type=source_ip,stickiness.timeout_seconds=86400"
spec:
  selector:
    app: nginx
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80
  type: LoadBalancer
  # 请求不跨节点转发,保留客户端源IP
  externalTrafficPolicy: Local
  # Service层启用客户端IP会话亲和,同IP请求固定到同一Pod
  sessionAffinity: ClientIP
  sessionAffinityConfig:
    clientIP:
      timeoutSeconds: 86400

验证注意事项

  • 配置部署后可到AWS控制台查看对应NLB的目标组属性,确认粘性会话已启用
  • 测试时需保证客户端出口IP固定,若测试网络存在多出口NAT、动态IP的情况会导致粘性失效
  • 可修改nginx Pod的默认首页内容为Pod名称,方便直观验证是否访问到同一Pod,测试脚本可调整为:
#!/bin/bash
for i in {1..10}; do
  curl -s <替换为你的NLB域名>
  echo ""
done

额外说明

如果你使用的是新版AWS Load Balancer Controller,可将service.beta.kubernetes.io/aws-load-balancer-type: "nlb-ip"替换为以下两个注解,兼容性更好:

  • service.beta.kubernetes.io/aws-load-balancer-type: "external"
  • service.beta.kubernetes.io/aws-load-balancer-nlb-target-type: "ip"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 22:39:01