service-mesh-implementation
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseService Mesh Implementation
服务网格实现
Overview
概述
Deploy and configure a service mesh to manage microservice communication, enable advanced traffic management, implement security policies, and provide comprehensive observability across distributed systems.
部署并配置服务网格,以管理微服务通信、实现高级流量管理、落实安全策略,并为分布式系统提供全面的可观测性。
When to Use
适用场景
- Microservice communication management
- Cross-cutting security policies
- Traffic splitting and canary deployments
- Service-to-service authentication
- Request routing and retries
- Distributed tracing integration
- Circuit breaker patterns
- Mutual TLS between services
- 微服务通信管理
- 跨领域安全策略
- 流量拆分与金丝雀部署
- 服务间身份认证
- 请求路由与重试
- 分布式追踪集成
- 断路器模式
- 服务间双向TLS认证
Implementation Examples
实现示例
1. Istio Core Setup
1. Istio核心配置
yaml
undefinedyaml
undefinedistio-setup.yaml
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: truemeshConfig:
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: 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: truemeshConfig:
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)%"Enable sidecar injection for namespace
Enable sidecar injection for namespace
apiVersion: v1
kind: Namespace
metadata:
name: production
labels:
istio-injection: enabled
undefinedapiVersion: v1
kind: Namespace
metadata:
name: production
labels:
istio-injection: enabled
undefined2. Virtual Service and Destination Rule
2. 虚拟服务与目标规则
yaml
undefinedyaml
undefinedvirtual-service-config.yaml
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:
# Canary: 10% to v2, 90% to 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 for testing
- match:
- headers:
user-agent:
regex: ".*Chrome.*"
route:
- destination:
host: api-service
subset: v2
timeout: 30s
# Default route
- route:
- destination:
host: api-service
subset: v1
weight: 100
timeout: 30s
retries:
attempts: 3
perTryTimeout: 10sapiVersion: 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: 10subsets:
- name: v1
labels:
version: v1
trafficPolicy:
connectionPool:
http:
http1MaxPendingRequests: 50
- name: v2
labels:
version: v2
trafficPolicy:
connectionPool:
http:
http1MaxPendingRequests: 100undefinedapiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: api-service
namespace: production
spec:
hosts:
- api-service
- api-service.production.svc.cluster.local
http:
# Canary: 10% to v2, 90% to 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 for testing
- match:
- headers:
user-agent:
regex: ".*Chrome.*"
route:
- destination:
host: api-service
subset: v2
timeout: 30s
# Default route
- route:
- destination:
host: api-service
subset: v1
weight: 100
timeout: 30s
retries:
attempts: 3
perTryTimeout: 10sapiVersion: 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: 10subsets:
- name: v1
labels:
version: v1
trafficPolicy:
connectionPool:
http:
http1MaxPendingRequests: 50
- name: v2
labels:
version: v2
trafficPolicy:
connectionPool:
http:
http1MaxPendingRequests: 100undefined3. Security Policies
3. 安全策略
yaml
undefinedyaml
undefinedsecurity-config.yaml
security-config.yaml
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
name: default
namespace: istio-system
spec:
mtls:
mode: STRICT # Enforce mTLS for all workloads
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/*"]
# Allow health checks
- 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
undefinedapiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
name: default
namespace: istio-system
spec:
mtls:
mode: STRICT # Enforce mTLS for all workloads
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/*"]
# Allow health checks
- 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
undefined4. Observability Configuration
4. 可观测性配置
yaml
undefinedyaml
undefinedobservability-config.yaml
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
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
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]))"
}
]
}
]
}
}
undefinedapiVersion: 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]))"
}
]
}
]
}
}
undefined5. Service Mesh Deployment Script
5. 服务网格部署脚本
bash
#!/bin/bashbash
#!/bin/bashdeploy-istio.sh - Install and configure Istio
deploy-istio.sh - Install and configure Istio
set -euo pipefail
VERSION="1.13.0"
NAMESPACE="istio-system"
echo "Installing Istio $VERSION..."
set -euo pipefail
VERSION="1.13.0"
NAMESPACE="istio-system"
echo "Installing Istio $VERSION..."
Download Istio
Download Istio
if [ ! -d "istio-$VERSION" ]; then
echo "Downloading Istio..."
curl -L https://istio.io/downloadIstio | ISTIO_VERSION=$VERSION sh -
fi
cd "istio-$VERSION"
if [ ! -d "istio-$VERSION" ]; then
echo "Downloading Istio..."
curl -L https://istio.io/downloadIstio | ISTIO_VERSION=$VERSION sh -
fi
cd "istio-$VERSION"
Add istioctl to PATH
Add istioctl to PATH
export PATH=$PWD/bin:$PATH
export PATH=$PWD/bin:$PATH
Verify cluster
Verify cluster
echo "Verifying cluster compatibility..."
istioctl analyze
echo "Verifying cluster compatibility..."
istioctl analyze
Install Istio
Install Istio
echo "Installing Istio on cluster..."
istioctl install --set profile=production -y
echo "Installing Istio on cluster..."
istioctl install --set profile=production -y
Verify installation
Verify installation
echo "Verifying installation..."
kubectl get ns $NAMESPACE
kubectl get pods -n $NAMESPACE
echo "Verifying installation..."
kubectl get ns $NAMESPACE
kubectl get pods -n $NAMESPACE
Label namespaces for sidecar injection
Label namespaces for sidecar injection
echo "Configuring sidecar injection..."
kubectl label namespace production istio-injection=enabled --overwrite
echo "Configuring sidecar injection..."
kubectl label namespace production istio-injection=enabled --overwrite
Wait for sidecars
Wait for sidecars
echo "Waiting for sidecars to be injected..."
kubectl rollout restart deployment -n production
echo "Istio installation complete!"
echo "Waiting for sidecars to be injected..."
kubectl rollout restart deployment -n production
echo "Istio installation complete!"
Show status
Show status
istioctl version
undefinedistioctl version
undefinedService Mesh Patterns
服务网格模式
Traffic Management
流量管理
- Canary Deployments: Gradually shift traffic
- A/B Testing: Route based on headers
- Circuit Breaking: Fail fast with outlier detection
- Rate Limiting: Control request flow
- 金丝雀部署:逐步切换流量
- A/B测试:基于请求头路由
- 断路器:通过异常检测快速失败
- 速率限制:控制请求流量
Security
安全防护
- mTLS: Mutual authentication
- Authorization Policies: Fine-grained access control
- JWT Validation: Token verification
- Encryption: Automatic in-transit encryption
- mTLS:双向身份认证
- 授权策略:细粒度访问控制
- JWT验证:令牌校验
- 加密:自动传输中加密
Best Practices
最佳实践
✅ DO
✅ 建议做法
- Enable mTLS for all workloads
- Implement proper authorization policies
- Use virtual services for traffic management
- Enable distributed tracing
- Monitor resource usage (CPU, memory)
- Use appropriate sampling rates for tracing
- Implement circuit breakers
- Use namespace isolation
- 为所有工作负载启用mTLS
- 落实合适的授权策略
- 使用虚拟服务进行流量管理
- 启用分布式追踪
- 监控资源使用情况(CPU、内存)
- 为追踪设置合适的采样率
- 实现断路器
- 使用命名空间隔离
❌ DON'T
❌ 不建议做法
- Disable mTLS in production
- Allow permissive traffic policies
- Ignore observability setup
- Deploy without resource requests/limits
- Skip sidecar injection validation
- Use 100% sampling in high-traffic systems
- Mix service versions without proper routing
- Neglect authorization policies
- 在生产环境中禁用mTLS
- 允许宽松的流量策略
- 忽略可观测性配置
- 不设置资源请求/限制就进行部署
- 跳过Sidecar注入验证
- 在高流量系统中使用100%采样率
- 未配置合适路由就混合服务版本
- 忽视授权策略