正在加载,请稍候…

使用 Istio 实现服务网格:流量管理、mTLS 与大规模可观测性

在生产环境中部署和运维 Istio 服务网格,涵盖流量管理、双向 TLS、熔断、分布式追踪以及基于 VirtualService 的金丝雀发布。

使用 Istio 实现服务网格:流量管理、mTLS 与大规模可观测性

服务网格将横切关注点从应用代码转移到基础设施层。Istio 是经过生产验证最成熟的实现。

架构

  • Istiod:管理配置、证书和服务发现
  • Envoy sidecar:注入到每个 Pod 中;拦截所有流量
  • Gateway:入口/出口流量控制
kubectl label namespace production istio-injection=enabled

使用 Istio 实现服务网格:流量管理、mTLS 与大规模可观测性 示意图

金丝雀发布

apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: payment-service
spec:
  hosts:
    - payment-service
  http:
    - route:
        - destination:
            host: payment-service
            subset: v1
          weight: 90
        - destination:
            host: payment-service
            subset: v2
          weight: 10
      timeout: 5s
      retries:
        attempts: 3
        perTryTimeout: 2s
        retryOn: "5xx,reset,connect-failure"
---
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: payment-service
spec:
  host: payment-service
  subsets:
    - name: v1
      labels: {version: v1}
    - name: v2
      labels: {version: v2}
  trafficPolicy:
    outlierDetection:
      consecutive5xxErrors: 5
      interval: 30s
      baseEjectionTime: 30s

使用 Istio 实现服务网格:流量管理、mTLS 与大规模可观测性 示意图

双向 TLS

apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
  name: default
  namespace: production
spec:
  mtls:
    mode: STRICT
---
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: payment-authz
spec:
  selector:
    matchLabels:
      app: payment-service
  action: ALLOW
  rules:
    - from:
        - source:
            principals: ["cluster.local/ns/production/sa/order-service"]
      to:
        - operation:
            methods: ["POST"]
            paths: ["/api/v*/payments*"]

使用 Istio 实现服务网格:流量管理、mTLS 与大规模可观测性 示意图

故障注入以进行弹性测试

apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: notification-chaos
spec:
  hosts:
    - notification-service
  http:
    - fault:
        delay:
          percentage: {value: 20.0}
          fixedDelay: 500ms
        abort:
          percentage: {value: 5.0}
          httpStatus: 503
      route:
        - destination:
            host: notification-service

传播追踪头

TRACE_HEADERS = ['x-request-id', 'x-b3-traceid', 'x-b3-spanid',
                 'x-b3-parentspanid', 'x-b3-sampled']

@app.middleware("http")
async def forward_trace_headers(request: Request, call_next):
    request.state.trace_headers = {
        h: request.headers[h] for h in TRACE_HEADERS if h in request.headers
    }
    return await call_next(request)

当你有数十个需要一致安全性和可观测性的服务时,Istio 会带来丰厚的回报。

→ 使用 JWT Parser 工具解码服务网格 JWT 令牌。