第5/10篇 — 从 Ingress 到 Gateway API:更安全、更智能的流量控制
发布: (2025年12月7日 GMT+8 18:52)
4 min read
原文: Dev.to
Source: Dev.to
对比:Ingress 与 Gateway API
| 方面 | Ingress | Gateway API |
|---|---|---|
| 范围 | 集群级入口 | 命名空间级、多租户网关 |
| 角色 | 一个 YAML = 共享配置 | 拆分为 Gateway(运维)+ HTTPRoute(开发) |
| 可扩展性 | 注解随意 | 类型化字段 + 策略 |
| 状态 | 控制器特定 | 标准化条件 |
Gateway API 概念
- GatewayClass – 定义底层实现(例如 Istio、NGINX)。
- Gateway – 由平台团队部署;代表流量进入集群的入口点。
- HTTPRoute – 由应用团队附加;描述流量应如何路由。
| 组件 | 责任说明 |
|---|---|
| Gateway | 指定监听器、端口以及 TLS 终止方式。 |
| HTTPRoute | 定义匹配条件(主机、路径、请求头)并将流量转发到 Service。 |
示例清单
gateway.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: web-gw
namespace: platform
spec:
gatewayClassName: nginx
listeners:
- name: https
port: 443
protocol: HTTPS
tls:
mode: Terminate
certificateRefs:
- name: my-cert
allowedRoutes:
namespaces:
from: All
route.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: shop-route
namespace: shop
spec:
parentRefs:
- name: web-gw
namespace: platform
hostnames: ["shop.example.com"]
rules:
- matches:
- path:
type: PathPrefix
value: /
backendRefs:
- name: shop-svc
port: 80
高级特性
rules:
- matches:
- headers:
- name: x-region
value: eu
backendRefs:
- name: shop-svc-eu
port: 80
filters:
- type: RequestTimeout
requestTimeout:
duration: 5s
- type: Retry
retry:
count: 3
statusCodes: ["5xx"]
加权流量拆分(一等支持):
backendRefs:
- name: shop-svc
port: 80
weight: 80
- name: shop-svc-canary
port: 80
weight: 20
多个 HTTPRoute 对象可以安全地附加到同一个 Gateway,每个对象都限定在各自的命名空间内。
迁移:Ingress → Gateway API
传统 Ingress
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: shop
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
tls:
- hosts: [shop.example.com]
secretName: my-cert
rules:
- host: shop.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: shop-svc
port:
number: 80
迁移后
直接使用上面展示的 gateway.yaml 与 route.yaml。
验证
kubectl get gateways -A
kubectl get httproutes -A
kubectl describe httproute shop-route
金丝雀测试
kubectl get endpoints shop-svc-canary -o wide
curl -H "x-canary:true" https://shop.example.com
你会看到受控的流量分配、可观测性提升以及所有权更加清晰。
常用命令
| 任务 | 命令 |
|---|---|
列出 GatewayClass 对象 | kubectl get gatewayclass |
| 查看网关的监听器 | kubectl describe gateway |
| 列出附加到网关的路由 | kubectl get httproute -A --field-selector spec.parentRefs.name= |
| 为网关创建 TLS secret | kubectl create secret tls my-cert --cert cert.pem --key key.pem -n platform |
| 测试连通性(跳过 TLS 验证) | curl -k https://host |
需要记住的关键字段
listeners.protocol、tls.mode、allowedRoutesrules.matches、filters、backendRefs.weight
需要注意的坑
- 策略附加顺序 – 网关级策略先于路由级策略评估;优先级很重要。
- 路由冲突 – 多个
HTTPRoute对象使用相同的 host/path 可能导致控制器特定的优先级决策。 - 跨命名空间引用 – 若
allowedRoutes.from=Same,开发团队无法从其他命名空间附加路由。 - 控制器支持 – 始终检查
Gateway与HTTPRoute对象的status.conditions,确认监听器已被接受。
结论
使用 Gateway API,Kubernetes 终于提供了具备策略感知的流量控制,能够在团队和环境之间实现可扩展——更安全、更简洁,也更适合自动化。
下一篇: Helm 基础(第 6 篇)——我们将对这些 Gateway 对象进行模板化,并以正确的方式参数化路由。