Istio 服务网格全景
什么是服务网格
服务网格将服务间通信的横切关注点(流量管理、安全、可观测性)从应用代码中剥离,下沉到基础设施层。
传统方式:
服务 A → [重试/熔断/限流/认证/追踪代码] → 服务 B
服务网格:
服务 A → Sidecar Proxy → Sidecar Proxy → 服务 B
(Envoy) (Envoy)
↑ ↑
Istio 控制平面统一管理Istio 架构
控制平面(istiod)
├── Pilot:流量管理配置下发
├── Citadel:证书管理(mTLS)
└── Galley:配置验证
数据平面
└── Envoy Sidecar(自动注入到每个 Pod)安装
bash
# 下载 istioctl
curl -L https://istio.io/downloadIstio | sh -
export PATH=$PWD/istio-1.20.0/bin:$PATH
# 安装(生产配置)
istioctl install --set profile=production -y
# 启用命名空间自动注入
kubectl label namespace production istio-injection=enabled
# 验证安装
istioctl verify-install
kubectl get pods -n istio-system流量管理
VirtualService
yaml
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: my-app
spec:
hosts:
- my-app
http:
# 金丝雀发布:90% 流量到 v1,10% 到 v2
- match:
- headers:
x-canary:
exact: "true"
route:
- destination:
host: my-app
subset: v2
- route:
- destination:
host: my-app
subset: v1
weight: 90
- destination:
host: my-app
subset: v2
weight: 10
# 故障注入(混沌测试)
- fault:
delay:
percentage:
value: 10
fixedDelay: 5s
abort:
percentage:
value: 5
httpStatus: 503
route:
- destination:
host: my-app
# 超时和重试
- timeout: 10s
retries:
attempts: 3
perTryTimeout: 3s
retryOn: gateway-error,connect-failure,retriable-4xx
route:
- destination:
host: my-appDestinationRule
yaml
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
name: my-app
spec:
host: my-app
trafficPolicy:
# 连接池限制
connectionPool:
tcp:
maxConnections: 100
http:
http1MaxPendingRequests: 100
http2MaxRequests: 1000
# 熔断器
outlierDetection:
consecutive5xxErrors: 5
interval: 30s
baseEjectionTime: 30s
maxEjectionPercent: 50
# 负载均衡
loadBalancer:
simple: LEAST_CONN # ROUND_ROBIN | LEAST_CONN | RANDOM | PASSTHROUGH
subsets:
- name: v1
labels:
version: v1
- name: v2
labels:
version: v2
trafficPolicy:
connectionPool:
http:
http2MaxRequests: 500mTLS 安全
yaml
# 强制命名空间内所有服务使用 mTLS
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
name: default
namespace: production
spec:
mtls:
mode: STRICT # STRICT | PERMISSIVE | DISABLE
---
# 授权策略:只允许特定服务访问
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
name: allow-frontend
namespace: production
spec:
selector:
matchLabels:
app: backend
action: ALLOW
rules:
- from:
- source:
principals: ["cluster.local/ns/production/sa/frontend-sa"]
to:
- operation:
methods: ["GET", "POST"]
paths: ["/api/*"]可观测性
bash
# 查看服务拓扑(Kiali)
kubectl port-forward -n istio-system svc/kiali 20001:20001
# 查看追踪(Jaeger)
kubectl port-forward -n istio-system svc/tracing 16686:80
# 查看指标(Grafana)
kubectl port-forward -n istio-system svc/grafana 3000:3000
# 查看流量统计
istioctl proxy-status
istioctl analyze -n production