如何配置Istio EnvoyFilter对缺少x-user-auth头的请求执行本地限流
实现方案
核心思路
由于未使用Istio ingressgateway,我们直接在服务所在命名空间下部署EnvoyFilter,给所有注入了sidecar的Pod的入站流量链路添加本地限流规则,仅对缺少x-user-auth: some_value请求头的流量生效。
具体配置步骤
第一步:部署EnvoyFilter资源
直接应用以下YAML配置即可,注意替换配置中你的业务对应的实际参数:
apiVersion: networking.istio.io/v1alpha3 kind: EnvoyFilter metadata: name: local-rate-limit-unauthenticated namespace: your-service-namespace # 替换为目标服务所在的命名空间 spec: workloadSelector: labels: app: your-target-service-app # 替换为目标服务的app标签,需要全命名空间生效可删除该配置段 configPatches: # 补丁1:在HTTP过滤器链插入本地限流过滤器 - applyTo: HTTP_FILTER match: context: SIDECAR_INBOUND listener: portNumber: 80 # 替换为目标服务实际监听的端口 filterChain: filter: name: "envoy.filters.network.http_connection_manager" subFilter: name: "envoy.filters.http.router" patch: operation: INSERT_BEFORE value: name: envoy.filters.http.local_ratelimit typed_config: "@type": type.googleapis.com/udpa.type.v1.TypedStruct type_url: type.googleapis.com/envoy.extensions.filters.http.local_ratelimit.v3.LocalRateLimit value: stat_prefix: http_local_rate_limiter token_bucket: max_tokens: 20 tokens_per_fill: 20 fill_interval: 60s # 对应每分钟20次的限流阈值 response_headers_to_add: - append: false header: key: x-local-rate-limit value: 'true' filter_enabled: runtime_key: local_rate_limit_enabled default_value: numerator: 100 denominator: HUNDRED filter_enforced: runtime_key: local_rate_limit_enforced default_value: numerator: 100 denominator: HUNDRED # 匹配规则:仅x-user-auth不等于some_value的请求触发限流,包含缺少该请求头的场景 match: headers: - name: x-user-auth invert_match: true exact_match: some_value # 补丁2:开启路由级别的本地限流支持 - applyTo: ROUTE_CONFIGURATION match: context: SIDECAR_INBOUND routeConfiguration: vhost: name: "*" route: action: ANY patch: operation: MERGE value: rate_limits: - actions: - request_headers: header_name: ":path" descriptor_key: path
第二步:验证效果
配置生效后可通过两类请求验证:
- 携带
x-user-auth: some_value请求头的调用:不会触发限流 - 未携带该请求头、或请求头值不符合的调用:每分钟累计超过20次后会返回429状态码
注意事项
- 若服务监听多个端口,需要为每个端口单独配置对应的listener匹配规则
- 本地限流为Pod单实例维度计数,多副本部署时整体限流阈值为「副本数 × 20次/分钟」
- 可通过调整
token_bucket下的参数自定义限流规则,修改max_tokens调整上限、fill_interval调整统计周期即可
内容的提问来源于stack exchange,提问作者carrotcakeslayer
相关产品推荐
相关产品推荐

