使用这些经过验证的模式安全地升级生产 Azure Kubernetes 服务(AKS)群集。 每个策略都针对特定的业务约束和风险容忍度进行优化。
本文介绍的内容
本文针对生产 AKS 群集提供经过测试的升级模式,并重点介绍:
- 用于零停机升级的蓝绿部署。
- 跨多个环境进行分阶段车队升级。
- 使用验证入口的安全 Kubernetes 版本采用。
- 用于快速常见漏洞和暴露(CVE)响应的紧急安全修补。
- 用于无缝升级的应用程序复原模式。
这些模式最适合生产环境、站点可靠性工程师和平台团队,这些团队需要最短的停机时间和最大安全性。
有关详细信息,请参阅以下相关文章:
- 若要获取具有有状态工作负荷的 AKS 群集的升级模式,请参阅 有状态工作负荷升级模式。
- 若要检查并应用 AKS 群集的基本升级,请参阅 升级 Azure Kubernetes 服务群集。
- 若要使用方案中心帮助你选择正确的 AKS 升级方法,请参阅 AKS 升级方案:选择路径。
有关快速入门,请选择相关说明的链接:
选择策略
优先级 | 最佳模式 | 停机时间 | 完成时间 |
---|---|---|---|
零停机时间 | 蓝绿部署 | <2 分钟 | 45-60 分钟 |
多环境安全性 | 分阶段机群升级 | 计划窗口 | 2-4 小时 |
新版本安全性 | 具有验证的 Canary | 低风险 | 3-6 小时 |
安全修补程序 | 自动修补 | <4 小时 | 30-90 分钟 |
面向未来的应用 | 可复原体系结构 | 零影响 | 持续 |
基于角色的快速入门
角色 | 从此处开始 |
---|---|
站点可靠性工程师/平台 | 方案 1、 方案 2 |
数据库管理员/数据工程师 | 有状态工作负荷模式 |
应用开发 | 方案 5 |
安全性 | 场景 4 |
方案 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
常见陷阱和常见问题解答
展开快速故障排除和提示
- 域名系统(DNS)传播速度缓慢: 在升级之前使用低生存时间值,并验证 DNS 缓存刷新。
-
Pod 停滞终止:使用 检查终结器、长时间关闭挂钩或 Pod 中断预算(PDB)。
maxUnavailable: 0
- 流量未转移: 验证 Azure 负载均衡器/Azure 流量管理器配置和运行状况探测。
- 回滚失败: 始终使蓝色群集保持就绪状态,直到绿色群集得到完全验证。
-
问:是否可以使用开源软件工具进行验证?
- 一个: 是的。 对 API 检查使用 kube-no-trouble ,使用 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
预期结果: 不到 2 分钟的总停机时间、零数据丢失和完全回滚功能。
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
常见陷阱和常见问题解答
展开快速故障排除和提示
- 阶段由于配额而失败: 预检查队列中所有群集的区域配额。
- 验证脚本失败: 确保测试脚本是幂等的,并且具有明确的传递/失败输出。
- 手动审批延迟: 将自动化用于非生产。 只需手动进行生产。
-
问:是否可以使用开源软件工具进行验证?
- 一个: 是的。 集成 Sonobuoy ,实现一致性,将 kube-bench 集成,实现安全性。
-
问:AKS 有什么独特之处?
- 一个: Azure Kubernetes Fleet Manager 原生启用真正的分阶段推出和验证入口。
方案 3:安全 Kubernetes 版本引入
挑战: “我需要采用 Kubernetes 1.30,而不会中断现有工作负载或 API。
策略: 将多短语验证与 Canary 部署配合使用。
实现步骤
步骤 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:创建 Canary 环境
# 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。 我需要在 4 小时内在所有群集中部署的修补程序。
策略: 使用自动化节点映像修补,尽量减少中断。
若要了解详细信息,请参阅 节点映像升级策略、 自动升级通道和安全 修补最佳做法。
实现步骤
步骤 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
> 💡 **Learn more:** [Planned maintenance configuration](./planned-maintenance.md) | [Auto-upgrade channels](./auto-upgrade-cluster.md#configure-auto-upgrade-channel)
步骤 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.\"}"
成功指标
- 部署时间:<4 小时,从常见漏洞和暴露公告
- 覆盖范围: 修补了 100 个节点的 100 个%
- 停机时间:<每个节点池 5 分钟
方案 5:用于无缝升级的应用程序体系结构
挑战: “我希望我的应用程序能够正常地处理群集升级,而不会影响用户。
策略: 使用可复原的应用程序模式并正常降级。
💡 了解详细信息:Pod 中断预算
实现步骤
步骤 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 中断预算
# 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 秒
监视和警报设置
若要了解详细信息,请参阅 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)"
相关资源
专用方案
支持工具
最佳做法
下一个任务
- 设置监视: 在首次升级之前配置 升级通知 。
- 安全地练习: 使用 群集快照在过渡中测试方案。
- 逐步自动执行: 从非生产 版的自动升级通道 开始。
- 处理有状态数据: 如果运行数据库 ,请查看有状态工作负荷模式 。