Skip to content

Gateway API — 下一代流量管理

为什么需要 Gateway API

Ingress 的局限性:

  • 只支持 HTTP/HTTPS,不支持 TCP/UDP
  • 注解(Annotations)不标准,各实现差异大
  • 角色模型简单,无法区分基础设施管理员和应用开发者

Gateway API 解决了这些问题,是 Ingress 的继任者。

核心资源

GatewayClass(基础设施提供商定义)


Gateway(集群管理员配置,监听端口)


HTTPRoute / TCPRoute / GRPCRoute(开发者配置,路由规则)


Service(后端服务)

GatewayClass

yaml
apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
  name: nginx
spec:
  controllerName: k8s.nginx.org/nginx-gateway-controller

Gateway

yaml
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: prod-gateway
  namespace: infra
spec:
  gatewayClassName: nginx
  listeners:
  - name: http
    port: 80
    protocol: HTTP
    allowedRoutes:
      namespaces:
        from: Selector
        selector:
          matchLabels:
            gateway-access: allowed
  - name: https
    port: 443
    protocol: HTTPS
    tls:
      mode: Terminate
      certificateRefs:
      - name: prod-tls
    allowedRoutes:
      namespaces:
        from: All

HTTPRoute

yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: api-route
  namespace: production
spec:
  parentRefs:
  - name: prod-gateway
    namespace: infra
    sectionName: https

  hostnames:
  - api.example.com

  rules:
  # 路径路由
  - matches:
    - path:
        type: PathPrefix
        value: /v2
    backendRefs:
    - name: api-v2-service
      port: 8080
      weight: 100

  # 流量分割(金丝雀)
  - matches:
    - path:
        type: PathPrefix
        value: /
    backendRefs:
    - name: api-stable
      port: 8080
      weight: 90
    - name: api-canary
      port: 8080
      weight: 10

  # Header 路由
  - matches:
    - headers:
      - name: X-Version
        value: beta
    backendRefs:
    - name: api-beta
      port: 8080

  # 请求修改
  - matches:
    - path:
        type: PathPrefix
        value: /old-api
    filters:
    - type: RequestRedirect
      requestRedirect:
        path:
          type: ReplacePrefixMatch
          replacePrefixMatch: /new-api
        statusCode: 301

TCPRoute(TCP 流量)

yaml
apiVersion: gateway.networking.k8s.io/v1alpha2
kind: TCPRoute
metadata:
  name: mysql-route
spec:
  parentRefs:
  - name: prod-gateway
    sectionName: mysql
  rules:
  - backendRefs:
    - name: mysql-service
      port: 3306

GRPCRoute

yaml
apiVersion: gateway.networking.k8s.io/v1alpha2
kind: GRPCRoute
metadata:
  name: grpc-route
spec:
  parentRefs:
  - name: prod-gateway
  rules:
  - matches:
    - method:
        service: com.example.UserService
        method: GetUser
    backendRefs:
    - name: user-service
      port: 9090

本站内容由 褚成志 整理编写,仅供学习参考