容器与云原生 / 系统课时

按请求属性匹配路由

按请求属性匹配路由

本篇用一个可运行的 Gateway API 示例,把同一域名下的请求按路径、HTTP 方法和 Header 精确分流到稳定版或金丝雀后端,并用正反请求验证每个条件都真正参与路由决策。

学习目标

  • 理解 hostnames 与 rules.matches 的匹配层级。
  • 组合路径、Header 和 HTTP 方法构造精确路由条件。
  • 用正反请求验证规则边界,确认未命中请求不会进入业务后端。

理解匹配条件的组合方式

HTTPRoute.spec.hostnames 先约束请求的 Host;进入规则匹配后,同一个 matches 条目中的 path、headers、method 等条件是“与”关系,必须同时满足。同一规则若包含多个 matches 条目,则这些条目彼此是“或”关系,任一条目命中即可执行该规则的后端动作。

本例让 GET /catalog 进入稳定版;POST /orders 还必须携带 x-release: stable 或 x-release: canary,分别进入两个后端。这样可以直接从请求属性推导唯一目标,也便于验证缺少条件时是否真正未命中。

HTTPRoute 请求属性匹配决策流程

创建可观察的两个后端

下面的清单创建两个轻量 HTTP 服务。二者运行相同的 Python 程序,只通过 RESPONSE 环境变量返回不同正文,因此可以从响应直接判断请求最终到达哪个 Service。保存为 request-match-demo.yaml。

yaml
apiVersion: v1
kind: Namespace
metadata:
  name: route-demo
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: stable
  namespace: route-demo
spec:
  replicas: 1
  selector:
    matchLabels:
      app: stable
  template:
    metadata:
      labels:
        app: stable
    spec:
      containers:
      - name: http
        image: python:3.12-alpine
        env:
        - name: RESPONSE
          value: stable
        command: ["python", "-c"]
        args:
        - |
          from http.server import BaseHTTPRequestHandler, HTTPServer
          import os
          class Handler(BaseHTTPRequestHandler):
              def reply(self):
                  body = (os.environ["RESPONSE"] + "\n").encode()
                  self.send_response(200)
                  self.send_header("Content-Length", str(len(body)))
                  self.end_headers()
                  self.wfile.write(body)
              def do_GET(self):
                  self.reply()
              def do_POST(self):
                  self.reply()
              def log_message(self, format, *args):
                  pass
          HTTPServer(("0.0.0.0", 8080), Handler).serve_forever()
        ports:
        - containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: stable
  namespace: route-demo
spec:
  selector:
    app: stable
  ports:
  - port: 80
    targetPort: 8080
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: canary
  namespace: route-demo
spec:
  replicas: 1
  selector:
    matchLabels:
      app: canary
  template:
    metadata:
      labels:
        app: canary
    spec:
      containers:
      - name: http
        image: python:3.12-alpine
        env:
        - name: RESPONSE
          value: canary
        command: ["python", "-c"]
        args:
        - |
          from http.server import BaseHTTPRequestHandler, HTTPServer
          import os
          class Handler(BaseHTTPRequestHandler):
              def reply(self):
                  body = (os.environ["RESPONSE"] + "\n").encode()
                  self.send_response(200)
                  self.send_header("Content-Length", str(len(body)))
                  self.end_headers()
                  self.wfile.write(body)
              def do_GET(self):
                  self.reply()
              def do_POST(self):
                  self.reply()
              def log_message(self, format, *args):
                  pass
          HTTPServer(("0.0.0.0", 8080), Handler).serve_forever()
        ports:
        - containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: canary
  namespace: route-demo
spec:
  selector:
    app: canary
  ports:
  - port: 80
    targetPort: 8080
---
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: api-gateway
  namespace: route-demo
spec:
  gatewayClassName: istio
  listeners:
  - name: http
    hostname: api.example.com
    port: 80
    protocol: HTTP
    allowedRoutes:
      namespaces:
        from: Same
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: api-route
  namespace: route-demo
spec:
  parentRefs:
  - name: api-gateway
  hostnames:
  - api.example.com
  rules:
  - matches:
    - path:
        type: Exact
        value: /catalog
      method: GET
    backendRefs:
    - name: stable
      port: 80
  - matches:
    - path:
        type: Exact
        value: /orders
      method: POST
      headers:
      - type: Exact
        name: x-release
        value: canary
    backendRefs:
    - name: canary
      port: 80
  - matches:
    - path:
        type: Exact
        value: /orders
      method: POST
      headers:
      - type: Exact
        name: x-release
        value: stable
    backendRefs:
    - name: stable
      port: 80

这份配置生效后,Gateway 只接受 api.example.com,而三条 HTTPRoute 规则分别负责目录查询、稳定版订单和金丝雀订单。Python 测试服务中的 send_response、send_header、do_GET、do_POST 与 log_message 都是合法标识符,不能在代码中写成带反斜杠的形式。

应用清单:

bash
kubectl apply -f request-match-demo.yaml

首次执行预期输出:

text
namespace/route-demo created
deployment.apps/stable created
service/stable created
deployment.apps/canary created
service/canary created
gateway.gateway.networking.k8s.io/api-gateway created
httproute.gateway.networking.k8s.io/api-route created

再次执行时资源通常显示 unchanged 或 configured,属于正常幂等行为。

验证控制面状态

先等待两个后端 Deployment 与 Gateway 就绪,再检查 HTTPRoute 是否已被父 Gateway 接受。Accepted=True 说明控制面接受了该 Route,但最终分流仍要由真实请求验证。

bash
kubectl wait -n route-demo --for=condition=available deployment/stable deployment/canary --timeout=90s
kubectl wait -n route-demo --for=condition=programmed gateway/api-gateway --timeout=90s
kubectl get httproute api-route -n route-demo -o 'jsonpath={.status.parents[0].conditions[?(@.type=="Accepted")].status}{"\n"}'

预期输出:

text
deployment.apps/stable condition met
deployment.apps/canary condition met
gateway.gateway.networking.k8s.io/api-gateway condition met
True

如果等待超时,应先检查 kubectl describe gateway 与 kubectl describe httproute 中的状态条件和原因,不要继续用业务请求掩盖控制面错误。

用正反请求验证属性分流

取得 Gateway 地址后执行三组应命中请求。GATEWAY_ADDRESS 的实际值可能是 <IP> 或 <HOSTNAME>;如果实验环境没有给 Gateway 分配可访问地址,需要按集群的入口暴露方式取得对应地址。

bash
GATEWAY_ADDRESS="$(kubectl get gateway api-gateway -n route-demo -o 'jsonpath={.status.addresses[0].value}')"
curl -s -H 'Host: api.example.com' "http://${GATEWAY_ADDRESS}/catalog"
curl -s -X POST -H 'Host: api.example.com' -H 'x-release: stable' "http://${GATEWAY_ADDRESS}/orders"
curl -s -X POST -H 'Host: api.example.com' -H 'x-release: canary' "http://${GATEWAY_ADDRESS}/orders"

预期输出:

text
stable
stable
canary

再验证两个边界条件:错误方法与缺少 Header 都不满足既有规则。在 Istio Gateway 数据面中,这类未匹配请求通常返回 404,也不应被转发到 stable 或 canary。

bash
curl -s -o /dev/null -w '%{http_code}\n' -X POST -H 'Host: api.example.com' "http://${GATEWAY_ADDRESS}/catalog"
curl -s -o /dev/null -w '%{http_code}\n' -X POST -H 'Host: api.example.com' "http://${GATEWAY_ADDRESS}/orders"

预期输出:

text
404
404

这两次结果说明 method 与 headers 都是匹配条件的一部分,而不是装饰性配置。不要依赖后端自行拒绝请求来代替网关层的路由判定。

避免规则边界被误解

Exact 路径只接受完全相同的路径,PathPrefix 则覆盖一个路径前缀范围。当多个规则可能同时匹配时,不要把 YAML 的书写顺序当成业务优先级;应依据 Gateway API 的匹配优先级设计互斥条件,并用边界请求做回归验证。

对于发布分流,本例显式要求 x-release: stable 或 x-release: canary,比“缺少 Header 就默认稳定版”更容易审计,也更容易在测试中确认每个条件是否真的参与了路由决策。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

按请求属性匹配路由

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通