服务网格实现 service-mesh-implementation

部署和配置服务网格以管理微服务通信,启用高级流量管理,实施安全策略,并在分布式系统中提供全面的可观测性。关键词:服务网格、微服务、流量管理、安全策略、可观测性。

云原生架构 0 次安装 0 次浏览 更新于 3/4/2026

服务网格实现

概述

部署和配置服务网格以管理微服务通信,启用高级流量管理,实施安全策略,并在分布式系统中提供全面的可观测性。

何时使用

  • 微服务通信管理
  • 跨领域安全策略
  • 流量分割和金丝雀部署
  • 服务间认证
  • 请求路由和重试
  • 分布式追踪集成
  • 断路器模式
  • 服务间相互TLS

实施示例

1. Istio核心设置

# istio-setup.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: istio-system
  labels:
    istio-injection: enabled

---
apiVersion: install.istio.io/v1alpha1
kind: IstioOperator
metadata:
  name: istio-config
  namespace: istio-system
spec:
  profile: production
  revision: "1-13"

  components:
    pilot:
      k8s:
        resources:
          requests:
            cpu: 500m
            memory: 2048Mi
          limits:
            cpu: 2000m
            memory: 4096Mi
        replicaCount: 3

    ingressGateways:
      - name: istio-ingressgateway
        enabled: true
        k8s:
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
            limits:
              cpu: 2000m
              memory: 1024Mi
          service:
            type: LoadBalancer
            ports:
              - port: 80
                targetPort: 8080
                name: http2
              - port: 443
                targetPort: 8443
                name: https

    egressGateways:
      - name: istio-egressgateway
        enabled: true

  meshConfig:
    enableAutoMTLS: true
    outboundTrafficPolicy:
      mode: ALLOW_ANY

    accessLogFile: /dev/stdout
    accessLogFormat: |
      [%START_TIME%] "%REQ(:METHOD)% %REQ(X-ENVOY-ORIGINAL-PATH?:PATH)% %PROTOCOL%"
      %RESPONSE_CODE% %RESPONSE_FLAGS% %BYTES_RECEIVED% %BYTES_SENT%
      "%DURATION%" "%RESP(X-ENVOY-UPSTREAM-SERVICE-TIME)%"

---
# 启用命名空间的边车注入
apiVersion: v1
kind: Namespace
metadata:
  name: production
  labels:
    istio-injection: enabled

2. 虚拟服务和目标规则

# virtual-service-config.yaml
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: api-service
  namespace: production
spec:
  hosts:
    - api-service
    - api-service.production.svc.cluster.local
  http:
    # 金丝雀:10%到v2,90%到v1
    - match:
        - uri:
            prefix: /api/v1
      route:
        - destination:
            host: api-service
            subset: v1
          weight: 90
        - destination:
            host: api-service
            subset: v2
          weight: 10
      timeout: 30s
      retries:
        attempts: 3
        perTryTimeout: 10s

    # API v2用于测试
    - match:
        - headers:
            user-agent:
              regex: ".*Chrome.*"
      route:
        - destination:
            host: api-service
            subset: v2
      timeout: 30s

    # 默认路由
    - route:
        - destination:
            host: api-service
            subset: v1
          weight: 100
      timeout: 30s
      retries:
        attempts: 3
        perTryTimeout: 10s

---
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: api-service
  namespace: production
spec:
  host: api-service
  trafficPolicy:
    connectionPool:
      tcp:
        maxConnections: 100
      http:
        http1MaxPendingRequests: 100
        maxRequestsPerConnection: 2
        h2UpgradePolicy: UPGRADE

    outlierDetection:
      consecutive5xxErrors: 5
      interval: 30s
      baseEjectionTime: 30s
      maxEjectionPercent: 50
      minRequestVolume: 10

  subsets:
    - name: v1
      labels:
        version: v1
      trafficPolicy:
        connectionPool:
          http:
            http1MaxPendingRequests: 50

    - name: v2
      labels:
        version: v2
      trafficPolicy:
        connectionPool:
          http:
            http1MaxPendingRequests: 100

3. 安全策略

# security-config.yaml
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
  name: default
  namespace: istio-system
spec:
  mtls:
    mode: STRICT  # 强制所有工作负载使用mTLS

---
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: api-service-authz
  namespace: production
spec:
  selector:
    matchLabels:
      app: api-service
  action: ALLOW
  rules:
    - from:
        - source:
            principals: ["cluster.local/ns/production/sa/web-service"]
      to:
        - operation:
            methods: ["GET", "POST"]
            paths: ["/api/v1/*"]

    # 允许健康检查
    - to:
        - operation:
            methods: ["GET"]
            paths: ["/health"]

---
apiVersion: security.istio.io/v1beta1
kind: RequestAuthentication
metadata:
  name: api-service-authn
  namespace: production
spec:
  selector:
    matchLabels:
      app: api-service
  jwtRules:
    - issuer: https://auth.mycompany.com
      jwksUri: https://auth.mycompany.com/.well-known/jwks.json
      audiences: api-service

4. 可观测性配置

# observability-config.yaml
apiVersion: telemetry.istio.io/v1alpha1
kind: Telemetry
metadata:
  name: custom-logging
  namespace: production
spec:
  metrics:
    - providers:
        - name: prometheus
      dimensions:
        - request.path
        - response.code
        - destination.service.name

---
apiVersion: telemetry.istio.io/v1alpha1
kind: Telemetry
metadata:
  name: custom-tracing
  namespace: production
spec:
  tracing:
    - providers:
        - name: jaeger
      randomSamplingPercentage: 100.0
      useRequestIdForTraceSampling: true

---
# Grafana Dashboard ConfigMap
apiVersion: v1
kind: ConfigMap
metadata:
  name: istio-dashboard
  namespace: monitoring
data:
  istio-mesh.json: |
    {
      "dashboard": {
        "title": "Istio Mesh",
        "panels": [
          {
            "title": "Request Rate",
            "targets": [
              {
                "expr": "rate(istio_requests_total[5m])"
              }
            ]
          },
          {
            "title": "Error Rate",
            "targets": [
              {
                "expr": "rate(istio_requests_total{response_code=~\"5..\"}[5m])"
              }
            ]
          },
          {
            "title": "Latency P95",
            "targets": [
              {
                "expr": "histogram_quantile(0.95, rate(istio_request_duration_milliseconds_bucket[5m]))"
              }
            ]
          }
        ]
      }
    }

5. 服务网格部署脚本

#!/bin/bash
# deploy-istio.sh - 安装和配置Istio

set -euo pipefail

VERSION="1.13.0"
NAMESPACE="istio-system"

echo "Installing Istio $VERSION..."

# 下载Istio
if [ ! -d "istio-$VERSION" ]; then
    echo "Downloading Istio..."
    curl -L https://istio.io/downloadIstio | ISTIO_VERSION=$VERSION sh -
fi

cd "istio-$VERSION"

# 添加istioctl到PATH
export PATH=$PWD/bin:$PATH

# 验证集群
echo "Verifying cluster compatibility..."
istioctl analyze

# 安装Istio
echo "Installing Istio on cluster..."
istioctl install --set profile=production -y

# 验证安装
echo "Verifying installation..."
kubectl get ns $NAMESPACE
kubectl get pods -n $NAMESPACE

# 标记命名空间以进行边车注入
echo "Configuring sidecar injection..."
kubectl label namespace production istio-injection=enabled --overwrite

# 等待边车
echo "Waiting for sidecars to be injected..."
kubectl rollout restart deployment -n production

echo "Istio installation complete!"

# 显示状态
istioctl version

服务网格模式

流量管理

  • 金丝雀部署:逐步转移流量
  • A/B测试:基于头部的路由
  • 断路器:快速失败与异常检测
  • 速率限制:控制请求流量

安全

  • mTLS:相互认证
  • 授权策略:细粒度访问控制
  • JWT验证:令牌验证
  • 加密:自动传输加密

最佳实践

✅ 执行

  • 为所有工作负载启用mTLS
  • 实施适当的授权策略
  • 使用虚拟服务进行流量管理
  • 启用分布式追踪
  • 监控资源使用情况(CPU,内存)
  • 使用适当的采样率进行追踪
  • 实施断路器
  • 使用命名空间隔离

❌ 不要

  • 在生产中禁用mTLS
  • 允许宽松的流量策略
  • 忽略可观测性设置
  • 部署没有资源请求/限制
  • 跳过边车注入验证
  • 在高流量系统中使用100%采样
  • 混合服务版本而没有适当的路由
  • 忽视授权策略

资源