🕸️ 第20课:服务网格

核心概念

服务网格:微服务通信基础设施

服务网格为微服务提供透明的流量管理、安全通信、可观测性,无需修改业务代码。

服务网格核心能力

┌─────────────────────────────────────────┐
│              服务网格能力层              │
├─────────────┬──────────────┬────────────┤
│   流量管理   │   安全通信    │   可观测性  │
├─────────────┼──────────────┼────────────┤
│ 负载均衡    │ mTLS加密     │ 分布式追踪  │
│ 金丝雀发布  │ 身份认证     │ 指标采集    │
│ 故障注入    │ 授权策略     │ 访问日志    │
│ 超时重试    │ 证书轮换     │ 服务拓扑    │
└─────────────┴──────────────┴────────────┘
特性IstioLinkerd
代理EnvoyLinkerd2-proxy(Rust)
资源占用~100MB/sidecar~20MB/sidecar
功能丰富度最全面够用
适用场景大型复杂微服务中小规模

命令实操

1. Istio安装与配置 ✅

Istio安装
curl -L https://istio.io/downloadIstio | sh -
cd istio-*/ && export PATH=$PWD/bin:$PATH
istioctl install --set profile=demo -y
kubectl label namespace default istio-injection=enabled

# 部署BookInfo示例
kubectl apply -f samples/bookinfo/platform/kube/bookinfo.yaml
kubectl apply -f samples/bookinfo/networking/bookinfo-gateway.yaml

# 验证Sidecar注入
kubectl get pods -o jsonpath='{.items[*].spec.containers[*].name}' | tr ' ' '\n' | grep istio-proxy

# 获取Gateway URL
export GATEWAY_URL=$(kubectl get svc istio-ingressgateway -n istio-system -o jsonpath='{.status.loadBalancer.ingress[0].ip}')
echo "http://$GATEWAY_URL/productpage" 

2. Istio流量管理 ✅

流量管理
# DestinationRule——版本子集+负载均衡+熔断
cat > dr-reviews.yaml << 'EOF'
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata: {name: reviews}
spec:
  host: reviews
  trafficPolicy:
    connectionPool:
      tcp: {maxConnections: 100}
      http: {http1MaxPendingRequests: 1000}
    outlierDetection:
      consecutive5xxErrors: 5
      interval: 30s
      baseEjectionTime: 30s
      maxEjectionPercent: 50
  subsets:
  - name: v1
    labels: {version: v1}
  - name: v2
    labels: {version: v2}
EOF

# VirtualService——路由+金丝雀
cat > vs-reviews.yaml << 'EOF'
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata: {name: reviews}
spec:
  hosts: [reviews]
  http:
  - match:
    - headers:
        x-user-type:
          exact: premium
    route:
    - destination: {host: reviews, subset: v2}
  - route:
    - destination: {host: reviews, subset: v1}
      weight: 80
    - destination: {host: reviews, subset: v2}
      weight: 20
    retries: {attempts: 3, perTryTimeout: 2s}
    timeout: 10s
EOF
kubectl apply -f dr-reviews.yaml -f vs-reviews.yaml

3. Istio安全策略(mTLS+授权) ✅

安全策略
# 启用严格mTLS
cat > mtls-strict.yaml << 'EOF'
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata: {name: default, namespace: istio-system}
spec:
  mtls: {mode: STRICT}
EOF
kubectl apply -f mtls-strict.yaml

# AuthorizationPolicy——访问控制
cat > auth-policy.yaml << 'EOF'
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata: {name: reviews-policy}
spec:
  selector: {matchLabels: {app: reviews}}
  rules:
  - from:
    - source:
        principals: ["cluster.local/ns/default/sa/bookinfo-productpage"]
    to:
    - operation: {methods: ["GET"]}
EOF
kubectl apply -f auth-policy.yaml
istioctl analyze

架构图

服务网格:微服务通信基础设施架构

┌─────────────────────────────────────────────────┐
│                  Istio Control Plane             │
│  istiod(配置分发) + Citadel(证书) + Galley(验证) │
└─────────────────────┬───────────────────────────┘
                      │ xDS推送
    ┌─────────────────┼──────────────────┐
    ▼                 ▼                  ▼
┌─────────┐    ┌──────────┐     ┌──────────┐
│ Pod A   │    │  Pod B   │     │  Pod C   │
│ App     │    │  App     │     │  App     │
│ Envoy   │◄───►│ Envoy    │◄───►│ Envoy    │
│ Sidecar │    │ Sidecar  │     │ Sidecar  │
└─────────┘    └──────────┘     └──────────┘
    mTLS加密 + 负载均衡 + 熔断 + 追踪

故障排查

❌ Sidecar未注入

排查
kubectl get ns -L istio-injection
istioctl kube-inject -f deployment.yaml | kubectl apply -f -
istioctl proxy-status
istioctl proxy-config route deploy/productpage
💡 服务网格最佳实践:先从流量管理开始,再逐步启用mTLS和授权策略。监控Sidecar资源消耗。

🏆 成就解锁:服务网格专家!

掌握Istio流量管理、mTLS安全、故障注入——服务网格是微服务通信的智能层

📝 服务网格选型决策

维度IstioLinkerdConsul Connect
学习成本
功能深度最深够用
Sidecar资源~100MB~20MB~50MB
社区活跃最活跃活跃
多集群支持支持原生支持
适用规模100+微服务10-5010-100
💡 服务网格入门建议:从Linkerd开始(简单轻量),需要更高级功能时迁移到Istio。不要一开始就上Istio。

🔧 Istio故障注入测试

故障注入
# 注入延迟(测试超时重试)
cat > fault-injection.yaml << 'EOF'
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata: {name: ratings}
spec:
  hosts: [ratings]
  http:
  - fault:
      delay: {percentage: {value: 100}, fixedDelay: 7s}
    route: [{destination: {host: ratings, subset: v1}}]
EOF
kubectl apply -f fault-injection.yaml

# 注入HTTP错误(测试熔断)
cat > abort-injection.yaml << 'EOF'
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata: {name: ratings}
spec:
  hosts: [ratings]
  http:
  - fault:
      abort: {percentage: {value: 50}, httpStatus: 500}
    route: [{destination: {host: ratings, subset: v1}}]
EOF
kubectl apply -f abort-injection.yaml
⚠️ 生产环境使用服务网格的注意点:Sidecar增加延迟(1-2ms/hop)、资源消耗不可忽视、调试链路更长。

🔧 服务网格可观测性

可观测性配置
# 启用Envoy访问日志
cat > telemetry.yaml << 'EOF'
apiVersion: telemetry.istio.io/v1alpha1
kind: Telemetry
metadata: {name: mesh-default, namespace: istio-system}
spec:
  accessLogging:
  - providers:
    - name: otel
    - name: file
EOF
kubectl apply -f telemetry.yaml

# Kiali服务拓扑可视化
istioctl dashboard kiali

# 查看服务指标
kubectl exec deploy/productpage -c istio-proxy -- pilot-agent request GET stats | grep upstream_rq

# 分布式追踪(Jaeger)
kubectl port-forward -n istio-system svc/tracing 16686:80
# 浏览器打开 http://localhost:16686

📝 服务网格监控指标

指标PromQL告警阈值
请求成功率istio_requests_total{response_code!~"5.."}< 99.9%
P99延迟istio_request_duration_milliseconds_bucket> 500ms
Sidecar内存container_memory_working_set_bytes{container="istio-proxy"}> 200MB
mTLS成功率istio_requests_total{source_principal!=""}< 100%
熔断器开启envoy_cluster_outlier_detection_ejections_active> 0
⚠️ Istio资源消耗:每个Sidecar约100MB内存+0.1CPU。100个Pod=10GB内存+10CPU,务必规划资源。