使用这些经过验证的模式安全地升级生产 Azure Kubernetes 服务(AKS)群集。 这些模式最适合生产环境、站点可靠性工程师和平台团队,这些团队需要最短的停机时间和最大安全性。
本文介绍的内容
本文针对生产 AKS 群集提供经过测试的升级模式,并重点介绍:
- 蓝绿部署,实现零停机升级。
- 跨多个环境进行分阶段车队升级。
- 通过验证关卡安全采用 Kubernetes 版本。
- 用于快速响应常见漏洞与披露(CVE)的紧急安全补丁修复。
- 用于无缝升级的应用程序复原模式。
- 支持即时回滚到源环境的迁移切换回退。
这些模式最适合生产环境、站点可靠性工程师和平台团队,这些团队需要最短的停机时间和最大安全性。
若要快速开始,请选择以下最符合业务需求的方案之一:
Kubernetes 先决条件
本文假设你了解 Kubernetes 部署和服务,包括以下概念:
-
Pod 中断预算 (PDB):告知 Kubernetes 在自愿中断(如节点升级)期间必须保持运行的最小 Pod 数量。 使用
maxUnavailable: 1,Kubernetes 在排空期间至少保持剩余 Pod 运行。 - 就绪情况探测:当 Pod 准备好接收流量时发出信号。 在升级期间,Kubernetes 会等待就绪探针通过后,才将 Pod 视为健康。
- 存活探针:自动重启不健康的 Pod。 在群集升级期间,这些探测可确保失败的 Pod 快速恢复。
- 终结器:在 Kubernetes 删除资源之前运行的自定义逻辑。 长时间运行的最终确定器可能会在排空期间阻塞 Pod 终止。
选择策略
| 你的优先事项 | 最佳模式 | 停机时间 | 完成时间 |
|---|---|---|---|
| 零停机时间 | 蓝绿部署 | <2 分钟 | 45-60 分钟 |
| 多环境安全性 | 分阶段机群升级 | 计划窗口 | 2-4 小时 |
| 新版本安全性 | 具有验证的 Canary | 低风险 | 3-6 小时 |
| 安全补丁 | 自动修补 | <4 小时 | 30-90 分钟 |
| 面向未来的应用 | 可复原体系结构 | 零影响 | 进行中 |
基于角色的起始点
| 角色 | 从此处开始 |
|---|---|
| 站点可靠性工程师/平台 | 方案 1、 方案 2 |
| 数据库管理员/数据工程师 | 有状态工作负载模式 |
| 应用开发 | 方案 5 |
| Security | 场景 4 |
| 迁移工程师 | 场景 6 |
方案 1:停机时间最短的生产升级
- 挑战:“我需要在工作时间内升级生产集群,并将停机时间控制在 2 分钟以内。”
- 策略:采用蓝绿部署,并结合智能流量切换。 蓝绿部署运行两个相同的生产环境(蓝色和绿色)。 部署到非活动环境,对其进行验证,然后以原子方式切换流量。 如果出现问题,流量会切换回活动环境。
快速实现(15 分钟)
# 1. Create green cluster (parallel to blue)
az aks create --name myaks-green --resource-group myRG \
--kubernetes-version 1.29.0 --enable-cluster-autoscaler \
--min-count 3 --max-count 10
# 2. Deploy application to green cluster
kubectl config use-context myaks-green
kubectl apply -f ./production-manifests/
# 3. Validate green cluster
# Run your application-specific health checks here
# Examples: API endpoint tests, database connectivity, dependency checks
# 4. Switch traffic (<30-second downtime)
az network traffic-manager endpoint update \
--profile-name prod-tm --name green-endpoint --weight 100
az network traffic-manager endpoint update \
--profile-name prod-tm --name blue-endpoint --weight 0
详细的分步指南
先决条件
- 已规划辅助群集容量。
- 应用程序支持水平缩放。
- 数据库连接使用连接池机制。
- 已配置运行状况检查(
/health,/ready)。 - 已在预发布环境中测试回滚流程。
步骤 1:准备蓝绿基础结构
# Create resource group for green cluster
az group create --name myRG-green --location chinanorth3
# Create green cluster with same configuration as blue
az aks create \
--resource-group myRG-green \
--name myaks-green \
--kubernetes-version 1.29.0 \
--node-count 3 \
--enable-cluster-autoscaler \
--min-count 3 \
--max-count 10 \
--enable-addons monitoring \
--generate-ssh-keys
步骤 2:部署和验证绿色环境
# Get green cluster credentials
az aks get-credentials --resource-group myRG-green --name myaks-green
# Deploy application stack
# Apply your Kubernetes manifests in order:
kubectl apply -f ./your-manifests/namespace.yaml # Create namespace
kubectl apply -f ./your-manifests/secrets/ # Deploy secrets
kubectl apply -f ./your-manifests/configmaps/ # Deploy config maps
kubectl apply -f ./your-manifests/deployments/ # Deploy applications
kubectl apply -f ./your-manifests/services/ # Deploy services
# Wait for all pods to be ready
kubectl wait --for=condition=ready pod --all --timeout=300s
# Validate application health
kubectl get pods -A
kubectl logs -l app=my-app --tail=50
步骤 3:流量切换(关键 30 秒窗口)
# Pre-switch validation
curl -f https://myapp-green.chinanorth3.chinacloudapp.cn/health
if [ $? -ne 0 ]; then echo "Green health check failed!"; exit 1; fi
# Execute traffic switch
az network dns record-set cname set-record \
--resource-group myRG-dns \
--zone-name mycompany.com \
--record-set-name api \
--cname myapp-green.chinanorth3.chinacloudapp.cn
# Immediate validation
sleep 30
curl -f https://api.mycompany.com/health
步骤 4:监视和验证
# Monitor traffic and errors for 15 minutes
kubectl top nodes
kubectl top pods
kubectl logs -l app=my-app --since=15m | grep ERROR
# Check application metrics
curl https://api.mycompany.com/metrics | grep http_requests_total
Troubleshooting
- 域名系统(DNS)传播速度缓慢:在升级前使用低生存时间值,并验证 DNS 缓存刷新。
-
Pod 卡在终止状态:检查最终确定器、长时间关闭挂钩或带有
maxUnavailable: 0的 PDB。 - 流量未转移:验证Azure 负载均衡器/Azure 流量管理器配置和运行状况探测。
- 回滚失败时:始终让蓝色集群保持就绪状态,直到绿色集群完成全面验证。
常见问题 (FAQ)
是否可以使用开源软件工具进行验证?
Yes. 使用 kube-no-trouble 进行 API 检查,并使用 Trivy 进行镜像扫描。
AKS 的独特之处是什么?
原生集成了流量管理器、Azure Kubernetes Fleet Manager 和节点映像修补功能,以实现零停机升级。
高级配置
对于需要 <30 秒停机的应用程序:
# Use session affinity during transition
apiVersion: v1
kind: Service
metadata:
name: my-app
spec:
sessionAffinity: ClientIP
sessionAffinityConfig:
clientIP:
timeoutSeconds: 300
成功验证
若要验证进度,请使用以下清单:
- 应用程序在两秒内响应。
- 日志中没有 5xx 错误。
- 数据库连接稳定。
- 保留用户会话。
紧急回滚(如有需要)
# Immediate rollback to blue cluster
az network dns record-set cname set-record \
--resource-group myRG-dns \
--zone-name mycompany.com \
--record-set-name api \
--cname myapp-blue.chinanorth3.chinacloudapp.cn
预期结果:不到两分钟的总停机时间、零数据丢失和完全回滚功能。
az aks create \
--resource-group production-rg \
--name aks-green-cluster \
--kubernetes-version 1.29.0 \
--node-count 3 \
--tier premium \
--auto-upgrade-channel patch \
--planned-maintenance-config ./maintenance-window.json
验证群集就绪情况
az aks get-credentials --resource-group production-rg --name aks-green-cluster
kubectl get nodes
实现步骤
步骤 1:将应用程序部署到绿色群集
# Deploy application stack
kubectl apply -f ./k8s-manifests/
kubectl apply -f ./monitoring/
# Wait for all pods to be ready
kubectl wait --for=condition=ready pod --all --timeout=300s
# Validate application health
curl -f http://green-cluster-ingress/health
步骤 2:执行流量切换
# Update DNS or load balancer to point to green cluster
az network dns record-set a update \
--resource-group dns-rg \
--zone-name contoso.com \
--name api \
--set aRecords[0].ipv4Address="<green-cluster-ip>"
# Monitor traffic shift (should complete in 60-120 seconds)
watch kubectl top pods -n production
步骤 3:验证和清理
# Verify zero errors in application logs
kubectl logs -l app=api --tail=100 | grep -i error
# Monitor key metrics for 15 minutes
kubectl get events --sort-by='.lastTimestamp' | head -20
# After validation, decommission blue cluster
az aks delete --resource-group production-rg --name aks-blue-cluster --yes
成功指标
- 停机时间:少于 2 分钟(DNS 传播时间)
- 错误率:转换期间为 0%
- 恢复时间:如需回滚,不到 5 分钟
场景 2:跨环境分阶段升级
- 挑战:“我需要通过适当的验证入口通过开发、测试和生产安全地测试升级。
- 策略:通过分阶段推出使用 Azure Kubernetes Fleet Manager。
若要了解详细信息,请参阅 Azure Kubernetes Fleet Manager 概述 和 更新业务流程。
先决条件
# Install Fleet extension
az extension add --name fleet
az extension update --name fleet
# Create Fleet resource
az fleet create \
--resource-group fleet-rg \
--name production-fleet \
--location chinanorth3
实现步骤
步骤 1:定义阶段配置
创建 upgrade-stages.json:
{
"stages": [
{
"name": "development",
"groups": [{ "name": "dev-clusters" }],
"afterStageWaitInSeconds": 1800
},
{
"name": "testing",
"groups": [{ "name": "test-clusters" }],
"afterStageWaitInSeconds": 3600
},
{
"name": "production",
"groups": [{ "name": "prod-clusters" }],
"afterStageWaitInSeconds": 0
}
]
}
步骤 2:将集群添加到舰队中
# Add development clusters
az fleet member create \
--resource-group fleet-rg \
--fleet-name production-fleet \
--name dev-east \
--member-cluster-id "/subscriptions/.../clusters/aks-dev-east" \
--group dev-clusters
# Add test clusters
az fleet member create \
--resource-group fleet-rg \
--fleet-name production-fleet \
--name test-east \
--member-cluster-id "/subscriptions/.../clusters/aks-test-east" \
--group test-clusters
# Add production clusters
az fleet member create \
--resource-group fleet-rg \
--fleet-name production-fleet \
--name prod-east \
--member-cluster-id "/subscriptions/.../clusters/aks-prod-east" \
--group prod-clusters
步骤 3:创建并运行暂存更新
# Create staged update run
az fleet updaterun create \
--resource-group fleet-rg \
--fleet-name production-fleet \
--name k8s-1-29-upgrade \
--upgrade-type Full \
--kubernetes-version 1.29.0 \
--node-image-selection Latest \
--stages upgrade-stages.json
# Start the staged rollout
az fleet updaterun start \
--resource-group fleet-rg \
--fleet-name production-fleet \
--name k8s-1-29-upgrade
步骤 4:阶段之间的验证检查点
开发阶段后(30 分钟浸泡):
# Run automated test suite
./scripts/run-e2e-tests.sh dev-cluster
./scripts/performance-baseline.sh dev-cluster
# Check for any regressions
kubectl get events --sort-by='.lastTimestamp' | grep -i warn
测试阶段后(60分钟浸泡):
# Extended testing with production-like load
./scripts/load-test.sh test-cluster 1000-users 15-minutes
./scripts/chaos-engineering.sh test-cluster
# Manual approval gate
echo "Approve production deployment? (y/n)"
read approval
Troubleshooting
- 阶段因配额失败:预检整个舰队中所有群集的区域配额。
- 验证脚本失败:确保测试脚本具有幂等性,并且能够明确输出通过/失败结果。
- 手动审批延迟:将自动化用于非生产。 只需手动进行生产。
常见问题 (FAQ)
是否可以使用开源软件工具进行验证?
Yes. 集成 Sonobuoy 用于一致性测试,集成 kube-bench 用于安全检查。
AKS 的独特之处是什么?
Azure Kubernetes Fleet Manager 原生支持真正的分阶段发布和验证门。
方案 3:安全 Kubernetes 版本引入
- 挑战: “我需要采用 Kubernetes 1.30,而不会中断现有工作负载或 API。
- 策略: 使用多阶段验证和金丝雀部署。
实现步骤
步骤 1:API 弃用分析
# Install and run API deprecation scanner
kubectl apply -f https://github.com/doitintl/kube-no-trouble/releases/latest/download/knt-full.yaml
# Scan for deprecated APIs
kubectl run knt --image=doitintl/knt:latest --rm -it --restart=Never -- \
-c /kubeconfig -o json > api-deprecation-report.json
# Review and remediate findings
cat api-deprecation-report.json | jq '.[] | select(.deprecated==true)'
若要了解详细信息,请参阅 Kubernetes API 弃用指南 和 kube-no-trouble 文档。
步骤 2:创建金丝雀环境
# Create canary cluster with target version
az aks create \
--resource-group canary-rg \
--name aks-canary-k8s130 \
--kubernetes-version 1.30.0 \
--node-count 2 \
--tier premium \
--enable-addons monitoring
# Deploy subset of workloads
kubectl apply -f ./canary-manifests/
步骤 3:渐进式工作负荷迁移
# Phase 1: Stateless services (20% traffic)
kubectl patch service api-service -p '{"spec":{"selector":{"version":"canary"}}}'
./scripts/monitor-error-rate.sh 15-minutes
# Phase 2: Background jobs (50% traffic)
kubectl scale deployment batch-processor --replicas=3
./scripts/validate-job-completion.sh
# Phase 3: Critical services (100% traffic)
kubectl patch deployment critical-api -p '{"spec":{"template":{"metadata":{"labels":{"cluster":"canary"}}}}}'
步骤 4:功能门验证
# Test new Kubernetes 1.30 features
apiVersion: v1
kind: ConfigMap
metadata:
name: feature-validation
data:
test-script: |
# Test new security features
kubectl auth can-i create pods --as=service-account:default:test-sa
# Validate performance improvements
kubectl top nodes --use-protocol-buffers=true
# Check new API versions
kubectl api-versions | grep "v1.30"
成功指标
- API 兼容性:100%(零重大更改)
- 性能:关键指标回退不超过 5%
- 功能采纳情况:已在 Canary 中验证的新功能
方案 4:最快的安全修补程序部署
- 挑战:“一项严重的 CVE 漏洞已被公布。” 我需要在四小时内将补丁部署到所有集群。
- 策略:使用自动化节点映像修补程序,尽量减少中断。
若要了解详细信息,请参阅 节点映像升级策略、 自动升级通道和安全 修补最佳做法。
实现步骤
步骤 1:紧急响应准备
# Set up automated monitoring for security updates
az aks nodepool update \
--resource-group production-rg \
--cluster-name aks-prod \
--name nodepool1 \
--auto-upgrade-channel SecurityPatch
# Configure maintenance window for emergency patches
az aks maintenance-configuration create \
--resource-group production-rg \
--cluster-name aks-prod \
--config-name emergency-security \
--week-index First,Second,Third,Fourth \
--day-of-week Monday,Tuesday,Wednesday,Thursday,Friday \
--start-hour 0 \
--duration 4
若要了解详细信息,请参阅 计划内维护配置 和 自动升级通道。
步骤 2:自动安全扫描
# security-scan-cronjob.yaml
apiVersion: batch/v1
kind: CronJob
metadata:
name: security-scanner
spec:
schedule: "0 */6 * * *" # Every 6 hours
jobTemplate:
spec:
template:
spec:
containers:
- name: scanner
image: aquasec/trivy:latest
command:
- trivy
- k8s
- --report
- summary
- cluster
步骤 3:快速部署补丁
# Trigger immediate node image upgrade for security patches
az aks nodepool upgrade \
--resource-group production-rg \
--cluster-name aks-prod \
--name nodepool1 \
--node-image-only \
--max-surge 50% \
--drain-timeout 5
# Monitor patch deployment
watch az aks nodepool show \
--resource-group production-rg \
--cluster-name aks-prod \
--name nodepool1 \
--query "upgradeSettings"
步骤 4:合规性验证
# Verify patch installation
kubectl get nodes -o wide
kubectl describe node | grep "Kernel Version"
# Generate compliance report
./scripts/generate-security-report.sh > security-compliance-$(date +%Y%m%d).json
# Notify security team
curl -X POST "$SLACK_WEBHOOK" -d "{\"text\":\"Security patches deployed to production cluster. Compliance report attached.\"}"
成功指标
- 部署时间:从 CVE 公告不到 4 小时
- 覆盖范围:100% 的节点已修补
- 停机时间:每个节点池的停机时间少于 5 分钟
方案 5:用于无缝升级的应用程序体系结构
- 挑战:“我希望我的应用程序能够正常处理群集升级,而不会影响用户。
- 策略:使用可复原的应用程序模式并正常降级。
实现步骤
步骤 1:实施健全的健康检查
# robust-health-checks.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: resilient-api
spec:
replicas: 3
template:
spec:
containers:
- name: api
image: myapp:latest
readinessProbe:
httpGet:
path: /health/ready
port: 8080
initialDelaySeconds: 10
periodSeconds: 5
timeoutSeconds: 3
successThreshold: 1
failureThreshold: 3
livenessProbe:
httpGet:
path: /health/live
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 3
lifecycle:
preStop:
exec:
command: ["/bin/sh", "-c", "sleep 15"]
步骤 2:配置 Pod 中断预算 (PDB)
# optimal-pdb.yaml
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: api-pdb
spec:
selector:
matchLabels:
app: api
maxUnavailable: 1
# Ensures at least 2 pods remain available during upgrades
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: database-pdb
spec:
selector:
matchLabels:
app: database
minAvailable: 2
# Critical: Always keep majority of database pods running
步骤 3:实现断路器模式
// circuit-breaker.js
const CircuitBreaker = require('opossum');
const options = {
timeout: 3000,
errorThresholdPercentage: 50,
resetTimeout: 30000,
fallback: () => 'Service temporarily unavailable'
};
const breaker = new CircuitBreaker(callExternalService, options);
// Monitor circuit breaker state during upgrades
breaker.on('open', () => console.log('Circuit breaker opened'));
breaker.on('halfOpen', () => console.log('Circuit breaker half-open'));
步骤 4:数据库连接复原
# connection-pool-config.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: db-config
data:
database.yml: |
production:
adapter: postgresql
pool: 25
timeout: 5000
retry_attempts: 3
retry_delay: 1000
connection_validation: true
validation_query: "SELECT 1"
test_on_borrow: true
成功指标
- 错误率:在升级期间小于 0.01%
- 响应时间:下降不超过 10%
- 恢复时间:在节点更换后不到 30 秒
场景 6:迁移切换回滚
- 挑战:“我将工作负荷从源群集、VM 资产或本地环境迁移到新的 AKS 群集。 如果切换后出现任何问题,我需要立即回滚到源端。
- 策略:使用蓝绿双群集(源群集 = 蓝色、新的 AKS 群集 = 绿色),或使用节点池在新 AKS 群集内使用蓝/绿。 使源环境保持运行并可由同一外部前门(DNS、流量管理器或负载均衡器)访问。 通过将流量切换到绿色端点来完成最终切换。 如果出现任何问题,将流量切回蓝色环境。
注释
此场景专门涵盖迁移切换回退,具体指源环境位于目标 AKS 群集之外的情况。 有关集群内版本升级回滚,请参阅 场景 1。
为什么这有效
- 切换是在入口层或服务层执行的单次流量切换操作。
- 源系统会保持完整,作为生产环境中的回退保障;在你确认将其停用之前,不会执行任何破坏性迁移步骤。
- 可以预热缓存、验证实际流量下的行为,并在指标超过中止阈值时立即削减。
快速实现
# variables (replace)
RG="myResourceGroup"
CLUSTER="myAksCluster"
GREEN_POOL="greenpool"
NODE_COUNT=3
VM_SIZE="Standard_DS2_v2"
# Step 1: Create a green node pool in the target AKS cluster
az aks nodepool add \
--resource-group $RG \
--cluster-name $CLUSTER \
--name $GREEN_POOL \
--node-count $NODE_COUNT \
--node-vm-size $VM_SIZE \
--labels pool=green
# Step 2: Get credentials
az aks get-credentials --resource-group $RG --name $CLUSTER
# Step 3: Cutover - patch the Service selector to green pods
kubectl patch svc myapp -n production -p '{"spec":{"selector":{"app":"myapp","version":"green"}}}'
# Rollback - patch selector back to blue
kubectl patch svc myapp -n production -p '{"spec":{"selector":{"app":"myapp","version":"blue"}}}'
详细的分步指南
步骤 1:在目标 AKS 群集中创建绿色节点池
添加一个专用节点池,以便在绿色切换期间将 Pod 固定到该节点池,而不影响集群的其余部分。
az aks nodepool add \
--resource-group $RG \
--cluster-name $CLUSTER \
--name $GREEN_POOL \
--node-count $NODE_COUNT \
--node-vm-size $VM_SIZE \
--labels pool=green
步骤 2:获取凭据并确认节点标签
az aks get-credentials --resource-group $RG --name $CLUSTER
# Confirm nodes are in the new pool
kubectl get nodes --show-labels | grep $GREEN_POOL
步骤 3:部署面向绿色节点池的绿色工作负荷
使用以绿色池标签为目标的节点选择器(或节点亲和性)。 AKS 使用 kubernetes.azure.com/agentpool 标记节点。 在部署之前,请确认节点上的标签。
# deployment-green.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp-green
labels:
app: myapp
version: green
spec:
replicas: 3
selector:
matchLabels:
app: myapp
version: green
template:
metadata:
labels:
app: myapp
version: green
spec:
nodeSelector:
"kubernetes.azure.com/agentpool": "greenpool"
containers:
- name: myapp
image: myregistry.azurecr.cn/myapp:green
ports:
- containerPort: 80
kubectl apply -f deployment-green.yaml -n production
kubectl rollout status deploy/myapp-green -n production
步骤 4:借助遥测数据在隔离环境中验证绿色环境
# Quick pod health checks
kubectl get pods -l app=myapp,version=green -n production
kubectl logs -l app=myapp,version=green -n production --tail=100
# Example: check cluster CPU (adjust resource ID for your cluster)
az monitor metrics list \
--resource /subscriptions/<sub>/resourceGroups/$RG/providers/Microsoft.ContainerService/managedClusters/$CLUSTER \
--metric "CpuUsagePercentage" \
--interval PT1M
在继续操作之前,请在Log Analytics工作区或 Application Insights 中验证应用程序跟踪、请求速率和错误日志。
步骤 5:切换 - 通过 Service 选择器切换流量
如果服务是type: LoadBalancer,AKS 将为该服务配置Azure 负载均衡器。 将选择器切换为绿色后,负载均衡器的端点会切换到绿色 Pod,从而使切换过程几乎可瞬间完成。
kubectl patch svc myapp -n production -p '{"spec":{"selector":{"app":"myapp","version":"green"}}}'
# Verify endpoints updated
kubectl get endpoints myapp -n production -o wide
步骤 6:切换后立即监控
监视运行状况探测、请求成功率、延迟百分位、CPU/内存和业务指标。 将运算符保留在定义的观察窗口的循环中。
步骤 7:回滚 - 将选择器切换回蓝色
如果需要回滚,将服务选择器还原到原始(蓝色)Pod,以便立即发生流量逆转。
kubectl patch svc myapp -n production -p '{"spec":{"selector":{"app":"myapp","version":"blue"}}}'
# Verify
kubectl get endpoints myapp -n production -o wide
kubectl rollout status deploy/myapp-blue -n production
双集群迁移(源为独立的集群或虚拟机)
如果源(蓝色)环境是单独的群集或 VM,请从外部操作前门,并在该处切换终结点,而不是修补新群集内的服务。
- Azure 流量管理器或 Front Door:翻转终结点优先级或权重以在源和目标之间路由。
- DNS 切换:保持相同的 DNS 名称,并将 A 记录(短 TTL)更改为目标集群 IP。 请注意 DNS 缓存。
- 外部负载均衡器:为每个群集使用后端池,并切换后端池成员身份。
回滚触发器(go/no-go 指标)
定义会导致立即回滚的明确触发条件。 根据您的 SLO 调整阈值。
| 信号 | 示例阈值 | Action |
|---|---|---|
| 错误率 | 5 分钟错误率 > 高于基线 1–3%,并连续持续 5 分钟 | 回退 |
| 延迟 | p95 > 达到基线的 2 倍或超过 SLO(例如,当 SLO 为 500 毫秒时,p95 > 1 秒并持续 3 分钟) | 回退 |
| 吞吐量 | 每分钟成功请求数较基线下降 >20%,持续 5 分钟 | 回退 |
| 资源压力 | Pod OOMKills 或节点 CPU 饱和 >度 90% 导致请求失败 | 回退 |
| 业务 KPI | 付款失败、结账错误或其他关键业务指标下降 | 回退 |
在 Azure Monitor 或 Application Insights 中配置自动警报,以通知值班工程师,并可选择触发将流量回切的 Runbook。
Troubleshooting
- DNS 传播较慢:在切换前设置较短的 TTL,并确认 DNS 缓存已刷新。
- 源端上的 Pod 一直处于终止状态:检查终结器或耗时过长的关闭钩子。
- 流量未转移:验证流量管理器运行状况探测和终结点配置。
- 回滚失败:在正式停用源环境之前,请保持其已打补丁且可访问。
成功验证清单
切换前:
- [ ] 源 (蓝色) 保持运行且可访问。
- [ ] 绿色环境具有相同或兼容的服务终结点、机密和配置。
- [ ] 已配置并测试运行状况探针以及就绪/存活探针。
- [ ] 已建立针对错误、延迟和资源压力的监控和告警机制。
- [ ] 一键或脚本化回滚操作已准备就绪,并经过测试。
- [ ] 相关干系人和值班人员已收到通知并处于待命状态。
预期结果:始终具备即时回滚能力、零数据丢失,以及经过演练、以指标为驱动的切换方案,并在你选择停用源系统之前始终保持其完好无损。
迁移的后续步骤
- AKS 迁移指南 - 从此处开始进行迁移规划和清单。
- AKS 的蓝绿节点池升级模式 - 节点池蓝/绿和零风险升级。
监视和警报设置
若要了解详细信息,请参阅 AKS 监视概述、 容器见解和 Prometheus 指标。
要监视的基本指标
# upgrade-monitoring.yaml
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: upgrade-monitoring
spec:
groups:
- name: upgrade.rules
rules:
- alert: UpgradeInProgress
expr: kube_node_spec_unschedulable > 0
for: 1m
annotations:
summary: "Node upgrade in progress"
- alert: HighErrorRate
expr: rate(http_requests_total{status=~"5.."}[5m]) > 0.01
for: 2m
annotations:
summary: "High error rate during upgrade"
- alert: PodEvictionFailed
expr: increase(kube_pod_container_status_restarts_total[5m]) > 5
for: 1m
annotations:
summary: "Multiple pod restarts detected"
仪表板配置
{
"dashboard": {
"title": "AKS Upgrade Dashboard",
"panels": [
{
"title": "Upgrade Progress",
"targets":
[
"kube_node_info",
"kube_node_status_condition"
]
},
{
"title": "Application Health",
"targets":
[
"up{job='kubernetes-pods'}",
"http_request_duration_seconds"
]
}
]
}
}
故障排除指南
若要了解详细信息,请参阅 AKS 故障排除指南、 节点和 Pod 故障排除以及 升级错误消息。
常见问题和解决方案
| 問题 | 症状 | 解决方案 |
|---|---|---|
| 停滞的节点清空 | Pod 不会被驱逐。 | 检查 PDB 配置,增加排空超时时间。 |
| 错误率高 | 5xx 响应数量正在增加。 | 确认健康检查,检查资源限制。 |
| 升级速度缓慢 | 需要 >2 小时。 | 增加 maxSurge,优化容器启动。 |
| DNS 解析 | 服务发现失败。 | 验证 CoreDNS Pod,检查服务终结点。 |
紧急回滚规程
# Quick rollback script
#!/bin/bash
echo "Initiating emergency rollback..."
# Switch traffic back to previous cluster
az network traffic-manager endpoint update \
--resource-group traffic-rg \
--profile-name production-tm \
--name current-endpoint \
--target-resource-id "/subscriptions/.../clusters/aks-previous"
# Verify rollback success
curl -f https://api.production.com/health
echo "Rollback completed in $(date)"