流量管理
灰度发布(金丝雀发布)
canary-release.yaml
# 第一步:10% 流量到新版本
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: product-service
spec:
hosts:
- product-service
http:
- route:
- destination:
host: product-service
subset: v1
weight: 90
- destination:
host: product-service
subset: v2
weight: 10
---
# 第二步:验证无异常后逐步调整到 50%/100%
# 第三步:全量切换后删除 v1
基于 Header 的精准路由
header-routing.yaml
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: product-service
spec:
hosts:
- product-service
http:
# 内部测试用户走 v2
- match:
- headers:
x-env:
exact: canary
route:
- destination:
host: product-service
subset: v2
# 默认走 v1
- route:
- destination:
host: product-service
subset: v1
故障注入(混沌测试)
fault-injection.yaml
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: reviews
spec:
hosts:
- reviews
http:
- fault:
# 注入 5s 延迟(50% 请求)
delay:
percentage:
value: 50
fixedDelay: 5s
# 注入 500 错误(10% 请求)
abort:
percentage:
value: 10
httpStatus: 500
route:
- destination:
host: reviews
警告
故障注入只在测试环境使用,用于验证服务的容错能力(超时处理、重试、降级)。
超时与重试
retry-timeout.yaml
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: product-service
spec:
hosts:
- product-service
http:
- timeout: 3s # 请求超时
retries:
attempts: 3 # 最多重试 3 次
perTryTimeout: 1s # 每次重试超时
retryOn: 5xx,reset,connect-failure
route:
- destination:
host: product-service
流量镜像(影子流量)
mirroring.yaml
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: product-service
spec:
hosts:
- product-service
http:
- route:
- destination:
host: product-service
subset: v1
mirror:
host: product-service
subset: v2
mirrorPercentage:
value: 100 # 100% 流量镜像到 v2(v2 的响应被丢弃)
提示
流量镜像是验证新版本最安全的方式:真实流量复制到新版本,但响应不返回给用户,不影响线上。
常见面试问题
Q1: Istio 灰度发布和 K8s 原生滚动更新有什么区别?
答案:
| 维度 | K8s 滚动更新 | Istio 灰度发布 |
|---|---|---|
| 粒度 | Pod 级别(逐个替换) | 流量级别(按百分比/规则) |
| 回滚 | 回滚 Deployment | 调整 VirtualService 权重 |
| 路由规则 | 无法按 Header/Cookie 路由 | 支持精准路由 |
| 观测 | 只看 Pod 状态 | 按版本观测 Metrics |
Istio 灰度更灵活,适合需要精细控制流量的场景。