EKS中AWS NLB ALPN策略注解不生效及Terraform实现咨询
解决EKS原生NLB无法通过注解配置ALPN策略的Terraform方案
你的怀疑是对的:service.beta.kubernetes.io/aws-load-balancer-alpn-policy注解仅适用于AWS Load Balancer Controller(LBC),原生Kubernetes Service创建的NLB(legacy模式)不支持该注解——因为K8s AWS cloud-controller-manager并未实现通过注解配置NLB的ALPN策略功能。
要通过Terraform实现NLB的ALPN策略配置,有两种可行方案:
方案一:Terraform预创建NLB并关联到K8s Service
这种方案适合不想引入第三方控制器的场景,步骤如下:
用Terraform创建带ALPN策略的NLB
直接在Terraform中定义NLB及其监听器,显式配置ALPN策略。示例代码:resource "aws_lb" "app_nlb" { name = "app-production-nlb" internal = false load_balancer_type = "network" subnets = ["subnet-xxxxxx", "subnet-yyyyyy"] # 与EKS集群同VPC的子网 enable_deletion_protection = true # 生产环境建议开启 } resource "aws_lb_listener" "tls_listener" { load_balancer_arn = aws_lb.app_nlb.arn port = "443" protocol = "TLS" alpn_policy = "HTTP2Preferred" # 这里配置ALPN策略 certificate_arn = "arn:aws:acm:us-east-1:xxxxxx:certificate/xxxxxx" # 你的ACM证书ARN default_action { type = "forward" target_group_arn = aws_lb_target_group.app_target_group.arn } } resource "aws_lb_target_group" "app_target_group" { name = "app-target-group" port = 443 # 与Service的targetPort对应 protocol = "TLS" vpc_id = "vpc-xxxxxx" # EKS集群的VPC ID target_type = "ip" # 适配K8s Service的IP模式 }让K8s Service关联已创建的NLB
在K8s Service中添加注解,指定已创建的NLB名称,这样K8s不会新建NLB,而是关联到你Terraform创建的实例。示例Service配置(可通过Terraform的kubernetes_service资源管理):apiVersion: v1 kind: Service metadata: name: app-service annotations: service.beta.kubernetes.io/aws-load-balancer-name: "app-production-nlb" # 对应Terraform中NLB的name service.beta.kubernetes.io/aws-load-balancer-target-group-arn: "arn:aws:elasticloadbalancing:us-east-1:xxxxxx:targetgroup/app-target-group/xxxxxx" # 可选,直接关联目标组 spec: type: LoadBalancer ports: - port: 443 targetPort: 443 protocol: TCP selector: app: your-app关键注意事项
- 确保NLB的子网、安全组与EKS集群一致,允许集群节点和外部流量通行
- Service的
targetPort要与NLB目标组的端口匹配 - Terraform创建的NLB后续由Terraform管理,K8s不会修改其配置(如ALPN策略、证书)
方案二:部署AWS Load Balancer Controller并使用Ingress资源
如果可以引入第三方控制器,推荐使用AWS Load Balancer Controller,它支持通过Ingress或Service注解配置NLB的ALPN策略:
- 用Terraform部署AWS Load Balancer Controller(创建IAM角色、Deployment等资源)
- 创建Ingress资源,添加ALPN注解:
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: app-ingress annotations: alb.ingress.kubernetes.io/scheme: internet-facing alb.ingress.kubernetes.io/target-type: ip alb.ingress.kubernetes.io/load-balancer-type: nlb service.beta.kubernetes.io/aws-load-balancer-alpn-policy: HTTP2Preferred # 此时注解生效 spec: tls: - hosts: - my.example.com secretName: tls-secret # 或直接引用ACM证书 rules: - host: my.example.com http: paths: - path: / pathType: Prefix backend: service: name: app-service port: number: 443
内容的提问来源于stack exchange,提问作者riccardogabellone
相关产品推荐
相关产品推荐

