🕸️ 第23课:服务网格Istio

📌 课程阶段:实战项目(3/5)|预计时间:60分钟|难度:⭐⭐⭐⭐⭐

一、服务网格核心概念

服务网格(Service Mesh)在基础设施层为微服务提供流量管理、安全通信和可观测性,无需修改应用代码。Istio是最流行的K8s服务网格实现。

┌──────── Istio架构 ─────────────┐
│                                  │
│  ┌───── 控制平面 ─────────────┐  │
│  │       istiod               │  │
│  │  ┌───────┐ ┌───────┐      │  │
│  │  │Pilot │ │Citadel│      │  │
│  │  │流量  │ │证书   │      │  │
│  │  │管理  │ │签发   │      │  │
│  │  └───────┘ └───────┘      │  │
│  └────────────────────────────┘  │
│               │                   │
│  ┌───── 数据平面 ─────────────┐  │
│  │                             │  │
│  │  Pod                   Pod  │  │
│  │  ┌─────────┐    ┌─────────┐│  │
│  │  │ Envoy   │    │ Envoy   ││  │
│  │  │ Sidecar │    │ Sidecar ││  │
│  │  ├─────────┤    ├─────────┤│  │
│  │  │  App    │    │  App    ││  │
│  │  │Container│    │Container││  │
│  │  └─────────┘    └─────────┘│  │
│  │   Service A     Service B  │  │
│  └─────────────────────────────┘  │
│                                    │
│  所有流量经过Envoy Sidecar代理     │
│  → mTLS加密、流量控制、遥测采集    │
└────────────────────────────────────┘

二、安装Istio

# 下载istioctl
curl -L https://istio.io/downloadIstio | sh -
cd istio-1.22.0
export PATH=$PWD/bin:$PATH

# ✅ 验证通过
istioctl version
# no running Istiod pods
# 1.22.0

# 安装Istio(demo配置适合学习)
istioctl install --set profile=demo -y

# 启用Sidecar自动注入
kubectl label namespace shop-system istio-injection=enabled

# ✅ 验证通过
kubectl get pods -n istio-system
# NAME                                    READY   STATUS    RESTARTS   AGE
# istio-egressgateway-xxxxx               1/1     Running   0          2m
# istio-ingressgateway-xxxxx              1/1     Running   0          2m
# istiod-xxxxx                            1/1     Running   0          2m

# 部署示例应用
kubectl apply -f samples/bookinfo/platform/kube/bookinfo.yaml -n shop-system
# 每个Pod自动注入Envoy Sidecar(2/2 Running)

三、流量管理

3.1 VirtualService——路由规则

# virtualservice-reviews.yaml - 基于用户的路由
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: reviews
spec:
  hosts:
  - reviews
  http:
  - match:
    - headers:
        end-user:
          exact: jason           # jason用户→v2
    route:
    - destination:
        host: reviews
        subset: v2
  - route:
    - destination:               # 其他用户→v1
        host: reviews
        subset: v1
      weight: 50
    - destination:               # 50%→v3
        host: reviews
        subset: v3
      weight: 50

---
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: reviews
spec:
  host: reviews
  trafficPolicy:
    connectionPool:
      tcp:
        maxConnections: 100
      http:
        h2UpgradePolicy: DEFAULT
        http1MaxPendingRequests: 1000
        http2MaxRequests: 1000
  subsets:
  - name: v1
    labels:
      version: v1
  - name: v2
    labels:
      version: v2
  - name: v3
    labels:
      version: v3

# ✅ 验证通过 - 流量按规则路由
kubectl exec -it deploy/productpage -c istio-proxy -n shop-system -- \
  curl -s http://reviews:9080/reviews/0

3.2 故障注入

# 注入延迟测试
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: ratings
spec:
  hosts:
  - ratings
  http:
  - match:
    - headers:
        end-user:
          exact: jason
    fault:
      delay:
        percentage:
          value: 100.0
        fixedDelay: 7s            # jason的请求延迟7秒
    route:
    - destination:
        host: ratings
        subset: v1
  - route:
    - destination:
        host: ratings
        subset: v1

3.3 流量转移

# 渐进式流量转移
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: reviews
spec:
  hosts:
  - reviews
  http:
  - route:
    - destination:
        host: reviews
        subset: v1
      weight: 90                  # 90%流量到v1
    - destination:
        host: reviews
        subset: v2
      weight: 10                  # 10%流量到v2

# 逐步调整:90/10 → 75/25 → 50/50 → 0/100

四、Istio Gateway

# gateway.yaml - 外部流量入口
apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: shop-gateway
spec:
  selector:
    istio: ingressgateway         # 使用Istio Ingress Gateway
  servers:
  - port:
      number: 80
      name: http
      protocol: HTTP
    hosts:
    - "shop.example.com"
  - port:
      number: 443
      name: https
      protocol: HTTPS
    tls:
      mode: SIMPLE
      credentialName: shop-tls    # K8s Secret
    hosts:
    - "shop.example.com"

---
# VirtualService绑定Gateway
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: shop-vs
spec:
  hosts:
  - "shop.example.com"
  gateways:
  - shop-gateway                  # 绑定到Gateway
  http:
  - match:
    - uri:
        prefix: /api/users
    route:
    - destination:
        host: user-service
        port:
          number: 8080
  - match:
    - uri:
        prefix: /api/products
    route:
    - destination:
        host: product-service
        port:
          number: 8080
  - route:
    - destination:
        host: frontend
        port:
          number: 80

# ✅ 验证通过
kubectl get gateway,virtualservice -n shop-system

五、mTLS与安全

# 启用严格mTLS
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
  name: default
  namespace: istio-system
spec:
  mtls:
    mode: STRICT                  # 所有服务间通信必须mTLS

---
# 授权策略(替代NetworkPolicy)
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: productpage-viewer
  namespace: shop-system
spec:
  selector:
    matchLabels:
      app: productpage
  action: ALLOW
  rules:
  - from:
    - source:
        principals: ["cluster.local/ns/shop-system/sa/user-service"]
    to:
    - operation:
        methods: ["GET"]
        paths: ["/api/*"]

六、可观测性

# 安装Kiali可视化
kubectl apply -f samples/addons/kiali.yaml
kubectl port-forward svc/kiali -n istio-system 20001:20001

# ✅ 验证通过
# 浏览器打开 http://localhost:20001
# 可以看到服务拓扑图、流量动画、延迟热力图

# 分布式追踪
kubectl apply -f samples/addons/jaeger.yaml
kubectl port-forward svc/tracing -n istio-system 16686:80

# 指标采集
kubectl apply -f samples/addons/prometheus.yaml
kubectl apply -f samples/addons/grafana.yaml

七、练习

  1. 安装Istio并部署Bookinfo示例应用
  2. 配置VirtualService实现基于Header的路由
  3. 使用故障注入测试服务的容错能力
  4. 配置Istio Gateway + VirtualService暴露服务
  5. 启用mTLS和AuthorizationPolicy实现零信任安全

🏆 第23课成就解锁

下一课预告:第24课深入GPU调度——AI/ML工作负载在K8s上运行。

📌 补充知识

23-服务网格istio补充要K8s生产实践扩展

🔹 资源配额(ResourceQuota):限制命名空间总资源
  apiVersion: v1
  kind: ResourceQuota
  metadata:
    name: compute-quota
    namespace: production
  spec:
    hard:
      requests.cpu: "20"
      requests.memory: 40Gi
      limits.cpu: "40"
      limits.memory: 80Gi
      pods: "50"
      services: "10"

🔹 LimitRange:设置默认资源限制
  apiVersion: v1
  kind: LimitRange
  metadata:
    name: default-limits
  spec:
    limits:
    - type: Container
      default:
        cpu: "200m"
        memory: 256Mi
      defaultRequest:
        cpu: "100m"
        memory: 128Mi
      max:
        cpu: "2"
        memory: 4Gi

🔹 Pod优先级与抢占
  apiVersion: scheduling.k8s.io/v1
  kind: PriorityClass
  metadata:
    name: high-priority
  value: 1000000
  globalDefault: false
  ---
  spec:
    preemptionPolicy: PreemptLowerPriority

🔹 优雅处理Pod中断
  • PDB保证最小可用副本
  • preStop钩子处理连接排空
  • terminationGracePeriodSeconds充足
  • 应用必须处理SIGTERM信号

🔹 生产环境Checklist
  ✅ 设置resources requests/limits
  ✅ 配置liveness/readiness探针
  ✅ 使用PDB保护关键服务
  ✅ 实现优雅关闭(SIGTERM)
  ✅ 配置HPA自动伸缩
  ✅ 使用NetworkPolicy隔离
  ✅ 开启RBAC最小权限
  ✅ 日志结构化输出
  ✅ 指标暴露/metrics端点
  ✅ 配置PVC数据备份

📎 扩展阅读与生产实践

23-服务网格istio生产环境进阶要点

🔹 性能优化关键参数
  • kubelet: --max-pods=110 --pods-per-core=10
  • kube-apiserver: --max-requests-inflight=800
  • etcd: --quota-backend-bytes=8589934592
  • kube-scheduler: --percentage-of-nodes-to-score=50

🔹 集群容量规划
  • 控制平面:3节点,8C16G起步
  • Worker节点:按应用类型分组
  • etcd:SSD磁盘,<2ms延迟
  • 网络带宽:10Gbps+集群内互联

🔹 故障自愈最佳实践
  1. Pod: livenessProbe自动重启
  2. Deployment: ReplicaSet保证副本数
  3. Node: kubelet自注册+健康检查
  4. Cluster: Cluster Autoscaler增减节点
  5. Multi-Cluster: Karmada联邦容灾

🔹 K8s版本升级策略
  • 每次只升一个minor版本
  • 先升级控制平面,再升级Worker
  • 使用kubeadm upgrade plan预检
  • 准备回滚方案
  • 在staging环境验证后再升级prod

📎 Istio生产实践要点

Istio生产环境最佳实践

🔹 Sidecar资源控制
  # 控制Envoy资源使用
  apiVersion: networking.istio.io/v1alpha3
  kind: Sidecar
  metadata:
    name: default
    namespace: istio-system
  spec:
    egress:
    - hosts:
      - ./*
      - istio-system/*
    outboundTrafficPolicy:
      mode: REGISTRY_ONLY  # 仅允许已注册服务

🔹 Istio性能优化
  • 使用Ambient Mesh(无Sidecar模式)
  • 配置Sidecar资源限制
  • 关闭不需要的遥测
  • 使用WasmPlugin替代Lua Filter
  • 合理设置连接池参数

🔹 故障排查命令
  istioctl analyze              # 配置分析
  istioctl proxy-status         # 代理状态
  istioctl proxy-config route   # 路由配置
  istioctl proxy-config cluster # 集群配置
  istioctl proxy-config listener # 监听器
  istioctl dashboard kiali      # Kiali可视化
  istioctl dashboard jaeger     # 追踪分析

🔹 从Istio迁移到Cilium Mesh
  • Cilium Mesh:eBPF实现,性能更优
  • 无Sidecar:减少资源开销
  • 兼容Istio API:平滑迁移
  • 内置NetworkPolicy:统一安全策略