# Helm 升级和清理指南 ## 概述 本指南说明如何使用 `--cleanup-on-fail` 和自动清理机制来确保Helm升级时的稳定性。 --- ## 方案说明 ### 1. 旧ReplicaSets的问题 当使用 `helm upgrade` 时,Kubernetes会保留之前的ReplicaSets(包含历史版本的Pod信息)。如果新镜像无法启动,旧的RS会保留但不再运行任何Pod,造成资源浪费。 ### 2. 解决方案 #### ✅ 方案A: 使用 `--cleanup-on-fail`(推荐) 这个参数让Helm在升级失败时自动清理新创建的资源: ```bash helm upgrade shop-recycle ./ --cleanup-on-fail -f environments/prod-values.yaml ``` #### ✅ 方案B: 设置 `revisionHistoryLimit`(自动清理) 在 `base/templates/deployment.yaml` 中已配置 `revisionHistoryLimit: 3`,这意味着: - 只保留最近3个ReplicaSets版本 - 更旧的RS会自动删除 #### ✅ 方案C: 定期手动清理 使用提供的清理脚本: ```bash # 删除所有没有running pod的RS bash scripts/cleanup-old-replicasets.sh ``` --- ## 使用部署脚本 ### 快速部署(内置cleanup-on-fail) ```bash # 开发环境 ./scripts/deploy-with-cleanup.sh dev # 预发布环境 ./scripts/deploy-with-cleanup.sh staging # 生产环境 ./scripts/deploy-with-cleanup.sh prod ``` ### 脚本功能 ✅ 自动检测Release是否存在(选择install或upgrade) ✅ 内置 `--cleanup-on-fail` 参数 ✅ 失败时自动清理资源 ✅ 升级成功后清理旧的ReplicaSets ✅ 等待Pod就绪后才返回 --- ## 检查旧ReplicaSets ```bash # 查看所有ReplicaSets kubectl get rs -l project=shop-recycle # 查看没有running pod的RS kubectl get rs --field-selector=status.replicas=0 -l project=shop-recycle # 手动删除特定RS kubectl delete rs # 删除所有没有running pod的RS kubectl delete rs --field-selector=status.replicas=0 -l project=shop-recycle ``` --- ## 监控部署状态 ```bash # 查看Helm Release状态 helm status shop-recycle # 查看部署历史 helm history shop-recycle # 实时查看Pod日志 kubectl logs -f -l project=shop-recycle # 查看特定服务日志 kubectl logs -f -l app=shop-recycle-payment ``` --- ## 故障排查 ### 问题:升级失败但资源未清理 **解决方案:** ```bash # 手动清理 helm upgrade shop-recycle ./ --cleanup-on-fail --force # 或者回滚到上一个版本 helm rollback shop-recycle ``` ### 问题:太多旧ReplicaSets占用空间 **解决方案:** ```bash # 减少历史版本保留数(编辑deployment.yaml的revisionHistoryLimit) # 或手动清理 kubectl delete rs --field-selector=status.replicas=0 ``` ### 问题:Pod一直无法启动 **检查日志:** ```bash # 查看pod事件 kubectl describe pod # 查看pod日志 kubectl logs # 检查镜像是否可用 kubectl describe pod | grep Image ``` --- ## 最佳实践 ### CI/CD集成示例 **GitLab CI:** ```yaml deploy_prod: stage: deploy script: - helm upgrade shop-recycle ./ --cleanup-on-fail -f environments/prod-values.yaml --timeout 5m --wait only: - master ``` **GitHub Actions:** ```yaml - name: Helm Deploy run: | helm upgrade shop-recycle ./ --cleanup-on-fail -f environments/prod-values.yaml --timeout 5m --wait ``` --- ## 配置总结 | 配置项 | 文件 | 说明 | |--------|------|------| | `revisionHistoryLimit: 3` | `charts/base/templates/deployment.yaml` | 只保留最近3个RS版本 | | `--cleanup-on-fail` | 命令行参数 | 升级失败时自动清理 | | 清理脚本 | `scripts/cleanup-old-replicasets.sh` | 手动清理没有running的RS | | 部署脚本 | `scripts/deploy-with-cleanup.sh` | 一键部署(内置cleanup) | --- **最后更新**: 2026-01-21