Helm与应用包管理
1. 概念
Helm 是 K8s 的包管理器。把一套 yaml 模板化加版本化,叫 Chart。部署一次叫 Release。
解决的问题:
- 20 个 yaml 管不过来
- 多环境(dev/staging/prod)只是参数不同
- 版本管理 + 回滚
- 公共组件复用(nginx-ingress、prometheus 都是社区 chart)
2. 安装
brew install helm
helm version
3. 使用社区 Chart
helm repo add bitnami https://charts.bitnami.com/bitnami
helm repo update
helm search repo nginx
helm install my-app bitnami/nginx --namespace web --create-namespace
helm list -n web
helm upgrade my-app bitnami/nginx -n web
helm rollback my-app 1 -n web
helm uninstall my-app -n web
4. 自建 Chart
helm create my-frontend
目录结构:
my-frontend/
├── Chart.yaml
├── values.yaml
├── templates/
│ ├── _helpers.tpl
│ ├── deployment.yaml
│ ├── service.yaml
│ └── ingress.yaml
4.1 values.yaml 示例
replicaCount: 3
image:
repository: ghcr.io/myorg/my-frontend
tag: "v1.2.3"
pullPolicy: IfNotPresent
service:
type: ClusterIP
port: 80
resources:
requests:
cpu: 50m
memory: 64Mi
4.2 模板语法
Helm 模板用 Go template 双大括号语法(本文用占位符 [VAR] 表示,避免文档冲突):
[VAR]在真实模板中写为双大括号包裹的.Values.replicaCount等表达式- 调用辅助函数:双大括号包裹
include "name" . - 内置对象:
.Chart.Name、.Release.Namespace - 条件 / 循环:
if、range、with - 格式化:管道
|接toYaml、nindent、quote
完整可用模板请直接执行 helm create 查看脚手架,或参考社区 chart(如 bitnami)。
5. 多环境
# values-prod.yaml 与 values-staging.yaml 分别覆盖参数
helm upgrade --install my-frontend ./my-frontend \
-f values-prod.yaml -n frontend-prod --atomic
6. 常用命令
helm template my-frontend ./my-frontend -f values-prod.yaml
helm install --dry-run --debug my-frontend ./my-frontend
helm diff upgrade my-frontend ./my-frontend
helm package ./my-frontend
helm push my-frontend-1.0.0.tgz oci://ghcr.io/myorg/charts
7. 生产建议
| 建议 | 原因 |
|---|---|
| 锁 chart version | 避免社区升级 break |
| values 分文件 | 基线 + 环境覆盖 |
| CI 跑 helm template 校验 | apply 前发现错 |
| 配 helm-diff 插件 | preview 变更 |
| Chart 放 git | 版本管理 + review |
| 用 upgrade --install | 幂等,CI 友好 |
| 加 --atomic | 失败自动回滚 |
8. 故障排查
helm history my-frontend -n frontend
helm get manifest my-frontend -n frontend
helm get values my-frontend -n frontend
helm rollback my-frontend 3 -n frontend
9. 常见反模式
- 不锁 chart 版本:社区升级 break 配置
- 所有参数都模板化:过度工程
- 模板嵌套太深:难以 review
- secrets 写 values.yaml 提交 git:用 sealed-secrets / external-secrets
- 一个 chart 装所有服务:拆,每服务一个
- 不跑 dry-run:apply 才发现语法错
- 不用 --atomic:部分 apply 失败留下半成品
10. 延伸阅读
- Helm 官方文档:https://helm.sh/docs/
- Artifact Hub:https://artifacthub.io/
- helm-diff 插件:https://github.com/databus23/helm-diff
- bitnami/charts:生产级 chart 范例