40. Helm Kubernetes 包管理器指南
目录
点击展开目录
Helm 概述 - 什么是 Helm - 核心概念 - 架构设计 - 与其他工具对比
安装与配置 - Helm 安装 - 仓库管理 - 配置文件 - 权限设置
Chart 开发 - Chart 结构 - 模板语法 - Values 文件 - 依赖管理
模板引擎 - Go 模板语法 - 内置函数 - 流程控制 - 变量和作用域
Chart 管理 - Chart 创建 - Chart 打包 - Chart 发布 - 版本管理
应用部署 - Release 管理 - 升级和回滚 - 配置覆盖 - 钩子机制
高级特性 - 子 Chart - Library Chart - Chart 测试 - 插件系统
最佳实践 - Chart 设计原则 - 安全实践 - 性能优化 - CI/CD 集成
Helm 概述
什么是 Helm
Helm 是 Kubernetes 的包管理器,被称为"Kubernetes 的 apt/yum"。它简化了 Kubernetes 应用的部署、管理和版本控制。
核心价值:
- 简化部署:通过预定义的 Chart 快速部署复杂应用
- 版本管理:支持应用的版本控制和回滚
- 配置管理:统一管理应用配置和参数
- 依赖管理:处理应用间的依赖关系
- 模板化:通过模板实现配置的复用和定制
主要解决的问题:
- YAML 文件管理复杂:大量 Kubernetes 资源文件难以维护
- 配置重复:相似应用的配置存在大量重复
- 版本控制困难:应用版本和配置版本难以统一管理
- 部署流程复杂:多步骤部署容易出错
核心概念
Helm 核心概念详解:
| 概念 | 说明 | 作用 | 示例 |
|---|---|---|---|
| Chart | Helm 包,包含应用的所有资源定义 | 应用模板 | nginx-chart |
| Release | Chart 的运行实例 | 应用实例 | my-nginx |
| Repository | Chart 仓库,存储和分发 Chart | 包管理 | stable/nginx |
| Values | 配置参数文件 | 配置管理 | values.yaml |
| Template | Kubernetes 资源模板 | 资源定义 | deployment.yaml |
Helm 工作流程:
架构设计
Helm 3 架构(相比 Helm 2 移除了 Tiller):
Helm 3 vs Helm 2 对比:
| 特性 | Helm 2 | Helm 3 | 改进点 |
|---|---|---|---|
| 架构 | 客户端-服务端 | 纯客户端 | 简化架构 |
| Tiller | 需要 Tiller | 无 Tiller | 提高安全性 |
| 权限 | Tiller 权限 | 用户权限 | 细粒度控制 |
| Release 存储 | ConfigMap | Secret | 更安全 |
| 命名空间 | 全局 Tiller | 命名空间隔离 | 更好隔离 |
| CRD 支持 | 有限 | 完整支持 | 更好兼容性 |
与其他工具对比
Kubernetes 包管理工具对比:
| 工具 | 类型 | 复杂度 | 生态 | 适用场景 |
|---|---|---|---|---|
| Helm | 包管理器 | 中等 | 最成熟 | 通用应用部署 |
| Kustomize | 配置管理 | 低 | 官方支持 | 配置定制 |
| Jsonnet | 配置语言 | 高 | 小众 | 复杂配置 |
| Operator | 自定义控制器 | 高 | 发展中 | 有状态应用 |
| Skaffold | 开发工具 | 中等 | 开发流程 |
Helm 优势:
- 生态成熟:大量现成的 Chart 可用
- 社区活跃:CNCF 毕业项目,社区支持好
- 功能完整:覆盖应用生命周期管理
- 易于学习:相对简单的学习曲线
- 企业采用:广泛的企业级应用
安装与配置
Helm 安装
Helm 安装方式支持多种平台和安装方法。
安装方式对比:
| 安装方式 | 平台支持 | 更新便利性 | 适用场景 |
|---|---|---|---|
| 二进制安装 | 全平台 | 手动更新 | 生产环境 |
| 包管理器 | Linux/macOS | 自动更新 | 开发环境 |
| 脚本安装 | Linux/macOS | 半自动 | 快速安装 |
| 容器运行 | 全平台 | 镜像更新 | CI/CD |
各平台安装命令:
# macOS - Homebrew
brew install helm
# Linux - Snap
sudo snap install helm --classic
# Linux - 包管理器
# Ubuntu/Debian
curl https://baltocdn.com/helm/signing.asc | gpg --dearmor | sudo tee /usr/share/keyrings/helm.gpg > /dev/null
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/helm.gpg] https://baltocdn.com/helm/stable/debian/ all main" | sudo tee /etc/apt/sources.list.d/helm-stable-debian.list
sudo apt-get update
sudo apt-get install helm
# CentOS/RHEL/Fedora
sudo dnf install helm
# 脚本安装
curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3
chmod 700 get_helm.sh
./get_helm.sh
# 二进制安装
wget https://get.helm.sh/helm-v3.12.0-linux-amd64.tar.gz
tar -zxvf helm-v3.12.0-linux-amd64.tar.gz
sudo mv linux-amd64/helm /usr/local/bin/helm
# 验证安装
helm version
仓库管理
Helm 仓库是存储和分发 Chart 的中心化服务。
仓库操作命令:
# 添加官方仓库
helm repo add stable https://charts.helm.sh/stable
helm repo add bitnami https://charts.bitnami.com/bitnami
# 添加自定义仓库
helm repo add myrepo https://my-chart-repo.example.com
# 列出仓库
helm repo list
# 更新仓库索引
helm repo update
# 搜索 Chart
helm search repo nginx
helm search repo --versions nginx
# 删除仓库
helm repo remove stable
常用 Chart 仓库:
| 仓库名称 | URL | 说明 | 维护方 |
|---|---|---|---|
| Bitnami | https://charts.bitnami.com/bitnami | 企业级应用 | Bitnami |
| Prometheus Community | https://prometheus-community.github.io/helm-charts | 监控相关 | 社区 |
| Ingress Nginx | https://kubernetes.github.io/ingress-nginx | Ingress 控制器 | Kubernetes |
| Jetstack | https://charts.jetstack.io | cert-manager 等 | Jetstack |
| Elastic | https://helm.elastic.co | ELK Stack | Elastic |
配置文件
Helm 配置通过环境变量和配置文件进行管理。
重要环境变量:
| 环境变量 | 默认值 | 说明 | 示例 |
|---|---|---|---|
| HELM_CONFIG_HOME | ~/.config/helm | 配置目录 | /etc/helm |
| HELM_CACHE_HOME | ~/.cache/helm | 缓存目录 | /tmp/helm |
| HELM_DATA_HOME | ~/.local/share/helm | 数据目录 | /var/lib/helm |
| KUBECONFIG | ~/.kube/config | Kubernetes 配置 | /path/to/kubeconfig |
配置文件示例:
# ~/.config/helm/repositories.yaml
apiVersion: ""
generated: "2023-01-01T00:00:00Z"
repositories:
- caFile: ""
certFile: ""
insecure_skip_tls_verify: false
keyFile: ""
name: stable
password: ""
url: https://charts.helm.sh/stable
username: ""
- name: bitnami
url: https://charts.bitnami.com/bitnami
权限设置
Helm 权限管理基于 Kubernetes RBAC 系统。
权限配置示例:
# helm-rbac.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: helm-user
namespace: default
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: helm-user
rules:
- apiGroups: [""]
resources: ["*"]
verbs: ["*"]
- apiGroups: ["apps"]
resources: ["*"]
verbs: ["*"]
- apiGroups: ["extensions"]
resources: ["*"]
verbs: ["*"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: helm-user
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: helm-user
subjects:
- kind: ServiceAccount
name: helm-user
namespace: default
最小权限原则:
# 最小权限示例
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: myapp
name: helm-deployer
rules:
- apiGroups: [""]
resources: ["pods", "services", "configmaps", "secrets"]
verbs: ["get", "list", "create", "update", "patch", "delete"]
- apiGroups: ["apps"]
resources: ["deployments", "replicasets"]
verbs: ["get", "list", "create", "update", "patch", "delete"]
Chart 开发
Chart 结构
Chart 目录结构遵循标准的组织方式。
标准 Chart 结构:
mychart/
├── Chart.yaml # Chart 元数据
├── values.yaml # 默认配置值
├── charts/ # 依赖的子 Chart
├── templates/ # 模板文件
│ ├── deployment.yaml
│ ├── service.yaml
│ ├── ingress.yaml
│ ├── configmap.yaml
│ ├── _helpers.tpl # 模板助手
│ └── NOTES.txt # 安装说明
├── .helmignore # 忽略文件
└── README.md # 文档说明
Chart.yaml 详解:
# Chart.yaml
apiVersion: v2
name: mychart
description: A Helm chart for my application
type: application
version: 0.1.0
appVersion: "1.0.0"
home: https://example.com
sources:
- https://github.com/example/mychart
maintainers:
- name: John Doe
email: [email protected]
url: https://johndoe.com
keywords:
- web
- nginx
- application
annotations:
category: WebServer
dependencies:
- name: postgresql
version: "11.6.12"
repository: https://charts.bitnami.com/bitnami
condition: postgresql.enabled
Chart.yaml 字段说明:
| 字段 | 必需 | 说明 | 示例 |
|---|---|---|---|
| apiVersion | 是 | Chart API 版本 | v2 |
| name | 是 | Chart 名称 | mychart |
| version | 是 | Chart 版本 | 0.1.0 |
| appVersion | 否 | 应用版本 | 1.0.0 |
| description | 否 | Chart 描述 | My application |
| type | 否 | Chart 类型 | application/library |
| dependencies | 否 | 依赖列表 | 见上例 |
模板语法
Helm 模板基于 Go 模板语法,支持变量替换和逻辑控制。
基础模板语法:
# templates/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ .Values.name }}
labels:
app: {{ .Values.name }}
version: {{ .Chart.AppVersion }}
spec:
replicas: {{ .Values.replicaCount }}
selector:
matchLabels:
app: {{ .Values.name }}
template:
metadata:
labels:
app: {{ .Values.name }}
spec:
containers:
- name: {{ .Values.name }}
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
ports:
- containerPort: {{ .Values.service.port }}
{{- if .Values.env }}
env:
{{- range $key, $value := .Values.env }}
- name: {{ $key }}
value: {{ $value | quote }}
{{- end }}
{{- end }}
内置对象:
| 对象 | 说明 | 示例用法 |
|---|---|---|
| Values | values.yaml 中的值 | {{ .Values.image.tag }} |
| Chart | Chart.yaml 中的信息 | {{ .Chart.Name }} |
| Release | Release 相关信息 | {{ .Release.Name }} |
| Template | 当前模板信息 | {{ .Template.Name }} |
| Files | 访问文件内容 | {{ .Files.Get "config.txt" }} |
| Capabilities | 集群能力信息 | {{ .Capabilities.KubeVersion }} |
Values 文件
Values 文件定义了 Chart 的默认配置和可配置参数。
values.yaml 示例:
# values.yaml
# 应用基本信息
name: myapp
replicaCount: 3
# 镜像配置
image:
repository: nginx
tag: "1.20"
pullPolicy: IfNotPresent
# 服务配置
service:
type: ClusterIP
port: 80
targetPort: 8080
# Ingress 配置
ingress:
enabled: false
className: nginx
annotations: {}
hosts:
- host: myapp.example.com
paths:
- path: /
pathType: Prefix
tls: []
# 资源限制
resources:
limits:
cpu: 500m
memory: 512Mi
requests:
cpu: 250m
memory: 256Mi
# 环境变量
env:
NODE_ENV: production
LOG_LEVEL: info
# 持久化存储
persistence:
enabled: false
storageClass: ""
accessMode: ReadWriteOnce
size: 8Gi
# 安全上下文
securityContext:
runAsNonRoot: true
runAsUser: 1000
fsGroup: 1000
# 节点选择
nodeSelector: {}
tolerations: []
affinity: {}
# 自动扩缩容
autoscaling:
enabled: false
minReplicas: 1
maxReplicas: 100
targetCPUUtilizationPercentage: 80
targetMemoryUtilizationPercentage: 80
Values 文件层次结构:
依赖管理
Chart 依赖允许 Chart 复用其他 Chart 的功能。
依赖配置:
# Chart.yaml
dependencies:
- name: postgresql
version: "11.6.12"
repository: https://charts.bitnami.com/bitnami
condition: postgresql.enabled
tags:
- database
- name: redis
version: "16.8.7"
repository: https://charts.bitnami.com/bitnami
condition: redis.enabled
tags:
- cache
- name: common
version: "1.13.1"
repository: https://charts.bitnami.com/bitnami
依赖管理命令:
# 更新依赖
helm dependency update
# 构建依赖
helm dependency build
# 列出依赖
helm dependency list
# 下载依赖到 charts/ 目录
ls charts/
# postgresql-11.6.12.tgz
# redis-16.8.7.tgz
条件和标签控制:
# values.yaml
postgresql:
enabled: true
auth:
postgresPassword: "mypassword"
redis:
enabled: false
tags:
database: true
cache: false
模板引擎
Go 模板语法
Helm 模板引擎基于 Go 的 text/template 包,提供强大的模板功能。
基础语法元素:
| 语法 | 说明 | 示例 | 输出 |
|---|---|---|---|
| {{ }} | 动作分隔符 | {{ .Values.name }} | myapp |
| {{- }} | 去除左侧空白 | {{- .Values.name }} | myapp |
| {{ -}} | 去除右侧空白 | {{ .Values.name -}} | myapp |
| | | 管道操作符 | {{ .Values.name | upper }} | MYAPP |
| $ | 变量前缀 | {{ $name := .Values.name }} | - |
变量定义和使用:
{{- $fullName := include "mychart.fullname" . -}}
{{- $labels := include "mychart.labels" . -}}
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ $fullName }}
labels:
{{- $labels | nindent 4 }}
spec:
replicas: {{ .Values.replicaCount }}
selector:
matchLabels:
{{- include "mychart.selectorLabels" . | nindent 6 }}
内置函数
Helm 提供了丰富的内置函数用于模板处理。
字符串函数:
| 函数 | 说明 | 示例 | 结果 |
|---|---|---|---|
| upper | 转大写 | {{ "hello" | upper }} | HELLO |
| lower | 转小写 | {{ "HELLO" | lower }} | hello |
| title | 首字母大写 | {{ "hello world" | title }} | Hello World |
| trim | 去除空白 | {{ " hello " | trim }} | hello |
| quote | 添加引号 | {{ "hello" | quote }} | “hello” |
| replace | 字符串替换 | {{ "hello" | replace "l" "x" }} | hexxo |
类型转换函数:
# 数值转换
replicas: {{ .Values.replicaCount | int }}
cpu: {{ .Values.resources.cpu | float64 }}
# 字符串转换
debug: {{ .Values.debug | toString }}
# 布尔转换
enabled: {{ .Values.feature.enabled | bool }}
# 列表转换
ports: {{ .Values.ports | toJson }}
日期和编码函数:
# 日期函数
createdAt: {{ now | date "2006-01-02T15:04:05Z" }}
timestamp: {{ now | unixEpoch }}
# 编码函数
data:
config.json: {{ .Values.config | toJson | b64enc }}
# 哈希函数
checksum: {{ .Values.config | toYaml | sha256sum }}
流程控制
条件语句:
{{- if .Values.ingress.enabled }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: {{ include "mychart.fullname" . }}
{{- if .Values.ingress.annotations }}
annotations:
{{- toYaml .Values.ingress.annotations | nindent 4 }}
{{- end }}
spec:
{{- if .Values.ingress.tls }}
tls:
{{- range .Values.ingress.tls }}
- hosts:
{{- range .hosts }}
- {{ . | quote }}
{{- end }}
secretName: {{ .secretName }}
{{- end }}
{{- end }}
rules:
{{- range .Values.ingress.hosts }}
- host: {{ .host | quote }}
http:
paths:
{{- range .paths }}
- path: {{ .path }}
pathType: {{ .pathType }}
backend:
service:
name: {{ include "mychart.fullname" $ }}
port:
number: {{ $.Values.service.port }}
{{- end }}
{{- end }}
{{- end }}
循环语句:
# range 循环
{{- range $key, $value := .Values.env }}
- name: {{ $key }}
value: {{ $value | quote }}
{{- end }}
# 带索引的循环
{{- range $index, $item := .Values.items }}
- name: item-{{ $index }}
value: {{ $item }}
{{- end }}
# 条件循环
{{- range .Values.services }}
{{- if .enabled }}
---
apiVersion: v1
kind: Service
metadata:
name: {{ .name }}
spec:
ports:
- port: {{ .port }}
{{- end }}
{{- end }}
变量和作用域
作用域管理:
{{- $root := . -}}
{{- range .Values.services }}
apiVersion: v1
kind: Service
metadata:
name: {{ .name }}-{{ $root.Release.Name }}
namespace: {{ $root.Release.Namespace }}
spec:
selector:
app: {{ $root.Values.app.name }}
ports:
- port: {{ .port }}
targetPort: {{ .targetPort | default .port }}
---
{{- end }}
with 语句:
{{- with .Values.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 2 }}
{{- end }}
{{- with .Values.tolerations }}
tolerations:
{{- toYaml . | nindent 2 }}
{{- end }}
{{- with .Values.affinity }}
affinity:
{{- toYaml . | nindent 2 }}
{{- end }}
Chart 管理
Chart 创建
创建新 Chart 使用 helm create 命令。
Chart 创建流程:
# 创建新 Chart
helm create mychart
# 查看生成的结构
tree mychart/
mychart/
├── Chart.yaml
├── values.yaml
├── charts/
└── templates/
├── deployment.yaml
├── service.yaml
├── ingress.yaml
├── serviceaccount.yaml
├── _helpers.tpl
├── hpa.yaml
├── NOTES.txt
└── tests/
└── test-connection.yaml
# 验证 Chart 语法
helm lint mychart/
# 渲染模板(不部署)
helm template mychart ./mychart
# 调试模板
helm template mychart ./mychart --debug
自定义 Chart 模板:
# 使用自定义起始模板
helm create mychart --starter mystarterpack
# 从现有应用生成 Chart
kubectl create deployment nginx --image=nginx --dry-run=client -o yaml > deployment.yaml
# 然后将 YAML 转换为 Helm 模板
Chart 打包
Chart 打包将 Chart 目录打包成 .tgz 文件。
打包命令和选项:
# 基本打包
helm package mychart/
# 指定版本
helm package mychart/ --version 1.0.0
# 指定应用版本
helm package mychart/ --app-version 2.1.0
# 签名打包
helm package mychart/ --sign --key mykey --keyring ~/.gnupg/secring.gpg
# 打包到指定目录
helm package mychart/ --destination ./packages/
# 更新依赖后打包
helm package mychart/ --dependency-update
打包最佳实践:
| 实践 | 说明 | 命令示例 |
|---|---|---|
| 版本管理 | 遵循语义化版本 | --version 1.2.3 |
| 依赖更新 | 打包前更新依赖 | --dependency-update |
| 签名验证 | 对 Chart 进行签名 | --sign --key mykey |
| 元数据检查 | 验证 Chart.yaml | helm lint |
Chart 发布
Chart 发布到仓库供他人使用。
发布到 Chart 仓库:
# 上传到 ChartMuseum
curl --data-binary "@mychart-1.0.0.tgz" http://chartmuseum.example.com/api/charts
# 使用 Helm 插件上传
helm plugin install https://github.com/chartmuseum/helm-push
helm cm-push mychart-1.0.0.tgz myrepo
# 发布到 Harbor
helm registry login harbor.example.com
helm push mychart-1.0.0.tgz oci://harbor.example.com/charts
# 发布到 GitHub Pages
# 1. 创建 gh-pages 分支
# 2. 生成索引文件
helm repo index . --url https://username.github.io/helm-charts/
# 3. 提交到 GitHub
OCI 仓库发布:
# 登录 OCI 仓库
helm registry login registry.example.com
# 推送 Chart
helm push mychart-1.0.0.tgz oci://registry.example.com/charts
# 拉取 Chart
helm pull oci://registry.example.com/charts/mychart --version 1.0.0
# 安装 OCI Chart
helm install myrelease oci://registry.example.com/charts/mychart --version 1.0.0
版本管理
Chart 版本管理遵循语义化版本规范。
版本号规范:
| 版本类型 | 格式 | 示例 | 说明 |
|---|---|---|---|
| 主版本 | X.0.0 | 2.0.0 | 不兼容的 API 变更 |
| 次版本 | X.Y.0 | 1.1.0 | 向后兼容的功能性新增 |
| 修订版本 | X.Y.Z | 1.0.1 | 向后兼容的问题修正 |
| 预发布 | X.Y.Z-alpha | 1.0.0-alpha.1 | 预发布版本 |
版本管理策略:
# Chart.yaml 版本策略
apiVersion: v2
name: mychart
version: 1.2.3 # Chart 版本
appVersion: "2.1.0" # 应用版本
# 版本约束
dependencies:
- name: postgresql
version: "~11.6.0" # >= 11.6.0, < 11.7.0
- name: redis
version: "^16.8.0" # >= 16.8.0, < 17.0.0
版本发布流程:
应用部署
Release 管理
Release 是 Chart 在 Kubernetes 集群中的运行实例。
Release 生命周期管理:
# 安装 Release
helm install myrelease ./mychart
helm install myrelease mychart --repo https://charts.example.com
# 列出 Release
helm list
helm list --all-namespaces
helm list --filter "^my"
# 查看 Release 状态
helm status myrelease
helm get values myrelease
helm get manifest myrelease
# 卸载 Release
helm uninstall myrelease
helm uninstall myrelease --keep-history
Release 信息查看:
| 命令 | 说明 | 输出内容 |
|---|---|---|
| helm status | Release 状态 | 状态、资源、说明 |
| helm get values | 配置值 | 合并后的 values |
| helm get manifest | 生成的清单 | Kubernetes YAML |
| helm get notes | 安装说明 | NOTES.txt 内容 |
| helm get hooks | 钩子信息 | 钩子资源 |
升级和回滚
Release 升级支持滚动更新和配置变更。
升级操作:
# 升级 Release
helm upgrade myrelease ./mychart
helm upgrade myrelease mychart --repo https://charts.example.com
# 升级并安装(不存在则安装)
helm upgrade --install myrelease ./mychart
# 指定新版本升级
helm upgrade myrelease mychart --version 2.0.0
# 强制升级
helm upgrade myrelease ./mychart --force
# 等待升级完成
helm upgrade myrelease ./mychart --wait --timeout 300s
# 原子升级(失败则回滚)
helm upgrade myrelease ./mychart --atomic
回滚操作:
# 查看历史版本
helm history myrelease
# 回滚到上一版本
helm rollback myrelease
# 回滚到指定版本
helm rollback myrelease 2
# 强制回滚
helm rollback myrelease 1 --force
# 等待回滚完成
helm rollback myrelease 2 --wait
升级策略对比:
| 策略 | 说明 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|---|
| 滚动更新 | 逐步替换实例 | 零停机 | 时间较长 | 生产环境 |
| 重建更新 | 先删除后创建 | 速度快 | 有停机 | 开发环境 |
| 蓝绿部署 | 并行环境切换 | 快速回滚 | 资源消耗大 | 关键应用 |
| 金丝雀部署 | 部分流量测试 | 风险可控 | 复杂度高 | 新功能发布 |
配置覆盖
配置覆盖允许在部署时自定义 Chart 参数。
配置覆盖方式:
# 使用 --set 覆盖单个值
helm install myrelease ./mychart --set image.tag=v2.0.0
# 使用 --set 覆盖多个值
helm install myrelease ./mychart \
--set image.tag=v2.0.0 \
--set replicaCount=3 \
--set service.type=LoadBalancer
# 使用 --set-string 强制字符串类型
helm install myrelease ./mychart --set-string nodePort="30080"
# 使用 --set-file 从文件读取值
helm install myrelease ./mychart --set-file config=./config.yaml
# 使用 -f 指定 values 文件
helm install myrelease ./mychart -f production-values.yaml
# 使用多个 values 文件(后面的覆盖前面的)
helm install myrelease ./mychart \
-f base-values.yaml \
-f environment-values.yaml \
-f secret-values.yaml
复杂值设置:
# 设置数组值
helm install myrelease ./mychart \
--set "ingress.hosts[0].host=app.example.com" \
--set "ingress.hosts[0].paths[0].path=/" \
--set "ingress.hosts[0].paths[0].pathType=Prefix"
# 设置对象值
helm install myrelease ./mychart \
--set "resources.limits.cpu=500m" \
--set "resources.limits.memory=512Mi"
# 设置环境变量
helm install myrelease ./mychart \
--set "env.NODE_ENV=production" \
--set "env.LOG_LEVEL=info"
钩子机制
Helm 钩子在 Release 生命周期的特定时点执行额外操作。
钩子类型:
| 钩子类型 | 执行时机 | 用途 | 示例 |
|---|---|---|---|
| pre-install | 安装前 | 环境准备 | 创建命名空间 |
| post-install | 安装后 | 初始化 | 数据库迁移 |
| pre-upgrade | 升级前 | 备份数据 | 数据库备份 |
| post-upgrade | 升级后 | 验证升级 | 健康检查 |
| pre-delete | 删除前 | 清理准备 | 数据导出 |
| post-delete | 删除后 | 清理资源 | 删除 PVC |
| pre-rollback | 回滚前 | 回滚准备 | 停止服务 |
| post-rollback | 回滚后 | 回滚验证 | 重启服务 |
钩子配置示例:
# templates/pre-install-job.yaml
apiVersion: batch/v1
kind: Job
metadata:
name: "{{ include "mychart.fullname" . }}-pre-install"
labels:
{{- include "mychart.labels" . | nindent 4 }}
annotations:
"helm.sh/hook": pre-install
"helm.sh/hook-weight": "-5"
"helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
spec:
template:
metadata:
name: "{{ include "mychart.fullname" . }}-pre-install"
spec:
restartPolicy: Never
containers:
- name: pre-install-job
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
command:
- /bin/sh
- -c
- |
echo "Preparing environment..."
# 执行预安装任务
kubectl create namespace {{ .Release.Namespace }} --dry-run=client -o yaml | kubectl apply -f -
钩子权重和删除策略:
| 注解 | 说明 | 示例值 |
|---|---|---|
| helm.sh/hook-weight | 执行顺序(数值越小越先执行) | “-5”, “0”, “5” |
| helm.sh/hook-delete-policy | 删除策略 | before-hook-creation, hook-succeeded, hook-failed |
钩子最佳实践:
# 数据库迁移钩子
apiVersion: batch/v1
kind: Job
metadata:
name: "{{ include "mychart.fullname" . }}-db-migrate"
annotations:
"helm.sh/hook": post-install,post-upgrade
"helm.sh/hook-weight": "1"
"helm.sh/hook-delete-policy": before-hook-creation
spec:
template:
spec:
restartPolicy: Never
containers:
- name: db-migrate
image: migrate/migrate
command:
- migrate
- -path
- /migrations
- -database
- "postgres://{{ .Values.database.user }}:{{ .Values.database.password }}@{{ .Values.database.host }}/{{ .Values.database.name }}?sslmode=disable"
- up
volumeMounts:
- name: migrations
mountPath: /migrations
volumes:
- name: migrations
configMap:
name: "{{ include "mychart.fullname" . }}-migrations"
高级特性
子 Chart
子 Chart 允许在主 Chart 中包含其他 Chart,实现模块化设计。
子 Chart 结构:
mychart/
├── Chart.yaml
├── values.yaml
├── charts/
│ ├── database/ # 子 Chart
│ │ ├── Chart.yaml
│ │ ├── values.yaml
│ │ └── templates/
│ └── cache/ # 另一个子 Chart
│ ├── Chart.yaml
│ ├── values.yaml
│ └── templates/
└── templates/
子 Chart 配置:
# 父 Chart 的 values.yaml
global:
imageRegistry: "registry.example.com"
storageClass: "fast-ssd"
# 子 Chart 配置
database:
enabled: true
image:
tag: "13.7"
auth:
postgresPassword: "secretpassword"
primary:
persistence:
enabled: true
size: 8Gi
cache:
enabled: true
auth:
enabled: false
master:
persistence:
enabled: false
子 Chart 访问父 Chart 值:
# 子 Chart 模板中访问全局值
apiVersion: v1
kind: ConfigMap
metadata:
name: {{ include "database.fullname" . }}
data:
registry: {{ .Values.global.imageRegistry }}
storage-class: {{ .Values.global.storageClass }}
子 Chart 最佳实践:
| 实践 | 说明 | 示例 |
|---|---|---|
| 全局值 | 使用 global 共享配置 | global.imageRegistry |
| 条件启用 | 通过 enabled 控制子 Chart | database.enabled: false |
| 命名规范 | 避免子 Chart 间命名冲突 | 使用 fullname 模板 |
| 依赖管理 | 明确声明子 Chart 依赖 | Chart.yaml dependencies |
Library Chart
Library Chart 提供可重用的模板和函数,不直接部署资源。
Library Chart 示例:
# Chart.yaml (Library Chart)
apiVersion: v2
name: common-lib
description: Common templates and functions
type: library
version: 1.0.0
定义通用模板:
# templates/_deployment.yaml
{{/*
Common deployment template
*/}}
{{- define "common.deployment" -}}
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "common.fullname" . }}
labels:
{{- include "common.labels" . | nindent 4 }}
spec:
replicas: {{ .Values.replicaCount | default 1 }}
selector:
matchLabels:
{{- include "common.selectorLabels" . | nindent 6 }}
template:
metadata:
labels:
{{- include "common.selectorLabels" . | nindent 8 }}
spec:
containers:
- name: {{ .Chart.Name }}
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
ports:
- containerPort: {{ .Values.service.port }}
{{- if .Values.resources }}
resources:
{{- toYaml .Values.resources | nindent 10 }}
{{- end }}
{{- end }}
使用 Library Chart:
# Chart.yaml (应用 Chart)
dependencies:
- name: common-lib
version: "1.0.0"
repository: "file://../common-lib"
# templates/deployment.yaml
{{- include "common.deployment" . }}
Chart 测试
Chart 测试验证部署的应用是否正常工作。
测试文件结构:
mychart/
└── templates/
└── tests/
├── test-connection.yaml
├── test-api.yaml
└── test-database.yaml
测试配置示例:
# templates/tests/test-connection.yaml
apiVersion: v1
kind: Pod
metadata:
name: "{{ include "mychart.fullname" . }}-test-connection"
labels:
{{- include "mychart.labels" . | nindent 4 }}
annotations:
"helm.sh/hook": test
"helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
spec:
restartPolicy: Never
containers:
- name: wget
image: busybox
command: ['wget']
args: ['{{ include "mychart.fullname" . }}:{{ .Values.service.port }}']
---
# templates/tests/test-api.yaml
apiVersion: v1
kind: Pod
metadata:
name: "{{ include "mychart.fullname" . }}-test-api"
annotations:
"helm.sh/hook": test
spec:
restartPolicy: Never
containers:
- name: api-test
image: curlimages/curl
command:
- /bin/sh
- -c
- |
set -e
echo "Testing API endpoints..."
curl -f http://{{ include "mychart.fullname" . }}:{{ .Values.service.port }}/health
curl -f http://{{ include "mychart.fullname" . }}:{{ .Values.service.port }}/api/v1/status
echo "All tests passed!"
运行测试:
# 运行所有测试
helm test myrelease
# 运行测试并显示日志
helm test myrelease --logs
# 清理测试 Pod
helm test myrelease --cleanup
# 运行特定测试
kubectl get pods -l "app.kubernetes.io/name=mychart,helm.sh/hook=test"
插件系统
Helm 插件扩展 Helm 的功能。
常用插件:
| 插件名称 | 功能 | 安装命令 |
|---|---|---|
| helm-diff | 比较 Release 差异 | helm plugin install https://github.com/databus23/helm-diff |
| helm-secrets | 管理敏感信息 | helm plugin install https://github.com/jkroepke/helm-secrets |
| helm-push | 推送到 ChartMuseum | helm plugin install https://github.com/chartmuseum/helm-push |
| helm-unittest | Chart 单元测试 | helm plugin install https://github.com/quintush/helm-unittest |
插件使用示例:
# 安装 helm-diff 插件
helm plugin install https://github.com/databus23/helm-diff
# 比较升级差异
helm diff upgrade myrelease ./mychart
# 使用 helm-secrets 管理密钥
helm secrets install myrelease ./mychart -f secrets.yaml
# 推送 Chart 到仓库
helm cm-push mychart/ myrepo
自定义插件开发:
# plugin.yaml
name: "myplugin"
version: "1.0.0"
usage: "My custom Helm plugin"
description: "A custom plugin for Helm"
command: "$HELM_PLUGIN_DIR/myplugin.sh"
hooks:
install: "$HELM_PLUGIN_DIR/install.sh"
update: "$HELM_PLUGIN_DIR/update.sh"
最佳实践
Chart 设计原则
Chart 设计应遵循一致性、可维护性和可扩展性原则。
设计原则对比:
| 原则 | 说明 | 实践方法 | 反例 |
|---|---|---|---|
| 单一职责 | 每个 Chart 专注一个应用 | 拆分复杂应用 | 一个 Chart 包含多个不相关服务 |
| 配置外部化 | 所有配置通过 Values 管理 | 使用 values.yaml | 硬编码配置值 |
| 向后兼容 | 新版本兼容旧配置 | 保持 API 稳定 | 随意更改配置结构 |
| 文档完整 | 提供完整的使用文档 | README + NOTES.txt | 缺少使用说明 |
命名规范:
# 资源命名模板
{{- define "mychart.fullname" -}}
{{- if .Values.fullnameOverride }}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- $name := default .Chart.Name .Values.nameOverride }}
{{- if contains $name .Release.Name }}
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- end }}
{{- end }}
# 标签模板
{{- define "mychart.labels" -}}
helm.sh/chart: {{ include "mychart.chart" . }}
{{ include "mychart.selectorLabels" . }}
{{- if .Chart.AppVersion }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}
配置验证:
# values.schema.json
{
"$schema": "https://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"replicaCount": {
"type": "integer",
"minimum": 1,
"maximum": 10
},
"image": {
"type": "object",
"properties": {
"repository": {
"type": "string"
},
"tag": {
"type": "string"
}
},
"required": ["repository", "tag"]
}
},
"required": ["replicaCount", "image"]
}
安全实践
Helm 安全实践涵盖 Chart 开发、部署和运行时安全。
安全检查清单:
| 安全项 | 检查内容 | 实现方式 | 重要性 |
|---|---|---|---|
| 镜像安全 | 使用可信镜像源 | 指定镜像 digest | 高 |
| 权限最小化 | 最小 RBAC 权限 | 自定义 ServiceAccount | 高 |
| 敏感信息 | 避免硬编码密钥 | 使用 Secret | 高 |
| 网络策略 | 限制网络访问 | NetworkPolicy | 中 |
| 资源限制 | 设置资源约束 | resources limits | 中 |
安全配置示例:
# 安全的 Deployment 配置
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "mychart.fullname" . }}
spec:
template:
spec:
serviceAccountName: {{ include "mychart.serviceAccountName" . }}
securityContext:
runAsNonRoot: true
runAsUser: 1000
fsGroup: 1000
containers:
- name: {{ .Chart.Name }}
image: "{{ .Values.image.repository }}@{{ .Values.image.digest }}"
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL
resources:
limits:
cpu: {{ .Values.resources.limits.cpu }}
memory: {{ .Values.resources.limits.memory }}
requests:
cpu: {{ .Values.resources.requests.cpu }}
memory: {{ .Values.resources.requests.memory }}
Chart 签名验证:
# 生成 GPG 密钥
gpg --gen-key
# 签名 Chart
helm package --sign --key mykey --keyring ~/.gnupg/secring.gpg mychart/
# 验证签名
helm verify mychart-1.0.0.tgz
# 安装时验证
helm install myrelease mychart-1.0.0.tgz --verify
性能优化
Helm 性能优化提高部署效率和运行性能。
优化策略:
| 优化项 | 方法 | 效果 | 实现难度 |
|---|---|---|---|
| 模板优化 | 减少复杂计算 | 提高渲染速度 | 低 |
| 依赖管理 | 合理使用依赖 | 减少下载时间 | 中 |
| 资源配置 | 优化资源设置 | 提高运行效率 | 中 |
| 镜像优化 | 使用轻量镜像 | 减少启动时间 | 高 |
模板性能优化:
# 避免重复计算
{{- $fullName := include "mychart.fullname" . -}}
{{- $labels := include "mychart.labels" . -}}
# 使用缓存的值
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ $fullName }}
labels:
{{- $labels | nindent 4 }}
spec:
selector:
matchLabels:
app.kubernetes.io/name: {{ include "mychart.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
资源配置优化:
# values.yaml - 生产环境配置
resources:
limits:
cpu: 1000m
memory: 1Gi
requests:
cpu: 500m
memory: 512Mi
# HPA 配置
autoscaling:
enabled: true
minReplicas: 2
maxReplicas: 10
targetCPUUtilizationPercentage: 70
targetMemoryUtilizationPercentage: 80
CI/CD 集成
Helm 与 CI/CD 集成实现自动化部署流水线。
GitLab CI 集成示例:
# .gitlab-ci.yml
stages:
- build
- test
- deploy
variables:
HELM_VERSION: "3.12.0"
CHART_PATH: "./helm/mychart"
before_script:
- curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3
- chmod 700 get_helm.sh
- ./get_helm.sh --version v${HELM_VERSION}
lint-chart:
stage: test
script:
- helm lint ${CHART_PATH}
- helm template test ${CHART_PATH} --debug
deploy-staging:
stage: deploy
script:
- helm upgrade --install myapp-staging ${CHART_PATH}
--namespace staging
--create-namespace
--values ${CHART_PATH}/values-staging.yaml
--set image.tag=${CI_COMMIT_SHA}
--wait
environment:
name: staging
only:
- develop
deploy-production:
stage: deploy
script:
- helm upgrade --install myapp-prod ${CHART_PATH}
--namespace production
--create-namespace
--values ${CHART_PATH}/values-production.yaml
--set image.tag=${CI_COMMIT_TAG}
--wait
environment:
name: production
only:
- tags
when: manual
GitHub Actions 集成:
# .github/workflows/helm-deploy.yml
name: Helm Deploy
on:
push:
branches: [main]
tags: ['v*']
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Helm
uses: azure/setup-helm@v3
with:
version: '3.12.0'
- name: Setup Kubernetes
uses: azure/k8s-set-context@v3
with:
method: kubeconfig
kubeconfig: ${{ secrets.KUBE_CONFIG }}
- name: Lint Chart
run: |
helm lint ./helm/mychart
- name: Deploy to Staging
if: github.ref == 'refs/heads/main'
run: |
helm upgrade --install myapp-staging ./helm/mychart \
--namespace staging \
--create-namespace \
--values ./helm/mychart/values-staging.yaml \
--set image.tag=${{ github.sha }} \
--wait
- name: Deploy to Production
if: startsWith(github.ref, 'refs/tags/v')
run: |
helm upgrade --install myapp-prod ./helm/mychart \
--namespace production \
--create-namespace \
--values ./helm/mychart/values-production.yaml \
--set image.tag=${{ github.ref_name }} \
--wait
故障排查
常见问题
Helm 常见问题及其解决方案。
问题分类和解决方案:
| 问题类型 | 常见症状 | 可能原因 | 解决方案 |
|---|---|---|---|
| 模板错误 | 渲染失败 | 语法错误、变量未定义 | helm template --debug |
| 依赖问题 | 安装失败 | 依赖版本冲突 | helm dependency update |
| 权限问题 | 部署被拒绝 | RBAC 权限不足 | 检查 ServiceAccount |
| 资源冲突 | 资源已存在 | 重复安装 | helm upgrade --install |
| 网络问题 | 仓库访问失败 | 网络连接问题 | 检查仓库 URL |
调试技巧
Helm 调试使用多种工具和方法。
调试命令:
# 模板调试
helm template myrelease ./mychart --debug
helm template myrelease ./mychart --debug --set debug=true
# 安装调试
helm install myrelease ./mychart --debug --dry-run
helm install myrelease ./mychart --debug --wait --timeout 600s
# 升级调试
helm upgrade myrelease ./mychart --debug --dry-run
helm diff upgrade myrelease ./mychart # 需要 helm-diff 插件
# 查看生成的资源
helm get manifest myrelease
helm get values myrelease
helm get hooks myrelease
# 检查 Release 历史
helm history myrelease
helm rollback myrelease 1 --dry-run
调试技巧:
# 在模板中添加调试信息
{{- if .Values.debug }}
# Debug: Chart Name = {{ .Chart.Name }}
# Debug: Release Name = {{ .Release.Name }}
# Debug: Values = {{ .Values | toYaml | nindent 2 }}
{{- end }}
# 使用 fail 函数进行验证
{{- if not .Values.image.repository }}
{{- fail "image.repository is required" }}
{{- end }}
# 条件性资源创建
{{- if .Values.debug }}
apiVersion: v1
kind: ConfigMap
metadata:
name: debug-info
data:
values.yaml: |
{{- .Values | toYaml | nindent 4 }}
{{- end }}
日志分析
日志分析帮助定位问题根因。
日志收集:
# Helm 操作日志
export HELM_DEBUG=true
helm install myrelease ./mychart
# Kubernetes 事件
kubectl get events --sort-by=.metadata.creationTimestamp
# Pod 日志
kubectl logs -l app.kubernetes.io/instance=myrelease
kubectl logs -l app.kubernetes.io/instance=myrelease --previous
# 描述资源状态
kubectl describe deployment myrelease
kubectl describe pod -l app.kubernetes.io/instance=myrelease
日志分析脚本:
#!/bin/bash
# helm-debug.sh - Helm 故障排查脚本
RELEASE_NAME=$1
NAMESPACE=${2:-default}
if [ -z "$RELEASE_NAME" ]; then
echo "Usage: $0 <release-name> [namespace]"
exit 1
fi
echo "=== Helm Release 信息 ==="
helm status $RELEASE_NAME -n $NAMESPACE
echo -e "\n=== Release 历史 ==="
helm history $RELEASE_NAME -n $NAMESPACE
echo -e "\n=== 生成的资源清单 ==="
helm get manifest $RELEASE_NAME -n $NAMESPACE
echo -e "\n=== 当前配置值 ==="
helm get values $RELEASE_NAME -n $NAMESPACE
echo -e "\n=== Kubernetes 事件 ==="
kubectl get events -n $NAMESPACE --sort-by=.metadata.creationTimestamp
echo -e "\n=== Pod 状态 ==="
kubectl get pods -n $NAMESPACE -l app.kubernetes.io/instance=$RELEASE_NAME
echo -e "\n=== Pod 日志 ==="
kubectl logs -n $NAMESPACE -l app.kubernetes.io/instance=$RELEASE_NAME --tail=50
性能诊断
性能诊断识别和解决性能瓶颈。
性能指标监控:
# Helm 操作耗时
time helm install myrelease ./mychart
# 资源使用情况
kubectl top pods -l app.kubernetes.io/instance=myrelease
kubectl top nodes
# 集群资源状态
kubectl describe nodes
kubectl get pods --all-namespaces -o wide
性能优化建议:
| 性能问题 | 诊断方法 | 优化建议 |
|---|---|---|
| 模板渲染慢 | time helm template | 简化模板逻辑 |
| 安装时间长 | 检查镜像拉取时间 | 使用本地镜像仓库 |
| 升级缓慢 | 分析滚动更新策略 | 调整更新参数 |
| 资源不足 | kubectl top | 增加资源配额 |
生产实践
多环境管理
多环境管理确保不同环境的配置隔离和一致性。
环境配置策略:
helm/
├── mychart/
│ ├── Chart.yaml
│ ├── values.yaml # 默认配置
│ └── templates/
├── environments/
│ ├── values-development.yaml # 开发环境
│ ├── values-staging.yaml # 测试环境
│ ├── values-production.yaml # 生产环境
│ └── values-dr.yaml # 灾备环境
└── scripts/
├── deploy-dev.sh
├── deploy-staging.sh
└── deploy-prod.sh
环境配置示例:
# values-development.yaml
replicaCount: 1
image:
tag: "latest"
resources:
limits:
cpu: 200m
memory: 256Mi
requests:
cpu: 100m
memory: 128Mi
ingress:
enabled: true
hosts:
- host: myapp-dev.example.com
autoscaling:
enabled: false
# values-production.yaml
replicaCount: 3
image:
tag: "v1.2.3"
resources:
limits:
cpu: 1000m
memory: 1Gi
requests:
cpu: 500m
memory: 512Mi
ingress:
enabled: true
hosts:
- host: myapp.example.com
tls:
- secretName: myapp-tls
hosts:
- myapp.example.com
autoscaling:
enabled: true
minReplicas: 3
maxReplicas: 10
部署脚本:
#!/bin/bash
# deploy-prod.sh
set -e
CHART_PATH="./mychart"
RELEASE_NAME="myapp"
NAMESPACE="production"
VALUES_FILE="./environments/values-production.yaml"
echo "部署到生产环境..."
# 验证 Chart
helm lint $CHART_PATH
# 检查差异
helm diff upgrade $RELEASE_NAME $CHART_PATH \
--namespace $NAMESPACE \
--values $VALUES_FILE
# 确认部署
read -p "确认部署到生产环境? (y/N): " confirm
if [[ $confirm == [yY] ]]; then
helm upgrade --install $RELEASE_NAME $CHART_PATH \
--namespace $NAMESPACE \
--create-namespace \
--values $VALUES_FILE \
--wait \
--timeout 600s
echo "部署完成!"
helm status $RELEASE_NAME -n $NAMESPACE
else
echo "部署已取消"
fi
GitOps 集成
GitOps 集成实现声明式的应用部署和管理。
ArgoCD 集成:
# argocd-application.yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: myapp
namespace: argocd
spec:
project: default
source:
repoURL: https://github.com/example/myapp-helm
targetRevision: HEAD
path: helm/mychart
helm:
valueFiles:
- values-production.yaml
parameters:
- name: image.tag
value: v1.2.3
destination:
server: https://kubernetes.default.svc
namespace: production
syncPolicy:
automated:
prune: true
selfHeal: true
syncOptions:
- CreateNamespace=true
Flux 集成:
# flux-helmrelease.yaml
apiVersion: helm.toolkit.fluxcd.io/v2beta1
kind: HelmRelease
metadata:
name: myapp
namespace: production
spec:
interval: 5m
chart:
spec:
chart: mychart
version: '1.2.3'
sourceRef:
kind: HelmRepository
name: myrepo
namespace: flux-system
values:
replicaCount: 3
image:
tag: v1.2.3
upgrade:
remediation:
retries: 3
监控告警
Helm Release 监控确保应用的健康状态。
监控指标:
# prometheus-rules.yaml
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: helm-release-monitoring
spec:
groups:
- name: helm.rules
rules:
- alert: HelmReleaseFailed
expr: |
kube_pod_container_status_restarts_total{
pod=~".*-helm-.*"
} > 5
for: 5m
labels:
severity: warning
annotations:
summary: "Helm release {{ $labels.pod }} has failed"
description: "Pod {{ $labels.pod }} has restarted {{ $value }} times"
- alert: HelmReleaseOutdated
expr: |
time() - kube_pod_created{
pod=~"myapp-.*"
} > 86400 * 30 # 30 days
labels:
severity: info
annotations:
summary: "Helm release may be outdated"
description: "Pod {{ $labels.pod }} is older than 30 days"
Grafana 仪表板:
{
"dashboard": {
"title": "Helm Releases",
"panels": [
{
"title": "Release Status",
"type": "stat",
"targets": [
{
"expr": "count by (release) (kube_pod_info{created_by_kind=\"ReplicaSet\"})"
}
]
},
{
"title": "Pod Restarts",
"type": "graph",
"targets": [
{
"expr": "rate(kube_pod_container_status_restarts_total[5m])"
}
]
}
]
}
}
运维自动化
运维自动化减少手动操作,提高效率和可靠性。
自动化脚本示例:
#!/bin/bash
# helm-ops.sh - Helm 运维自动化脚本
# 配置
NAMESPACE="production"
BACKUP_DIR="/backup/helm"
DATE=$(date +%Y%m%d-%H%M%S)
# 备份所有 Release
backup_releases() {
echo "备份 Helm Releases..."
mkdir -p $BACKUP_DIR/$DATE
for release in $(helm list -n $NAMESPACE -q); do
echo "备份 Release: $release"
helm get values $release -n $NAMESPACE > $BACKUP_DIR/$DATE/$release-values.yaml
helm get manifest $release -n $NAMESPACE > $BACKUP_DIR/$DATE/$release-manifest.yaml
done
}
# 检查 Release 健康状态
check_health() {
echo "检查 Release 健康状态..."
for release in $(helm list -n $NAMESPACE -q); do
status=$(helm status $release -n $NAMESPACE -o json | jq -r '.info.status')
if [[ "$status" != "deployed" ]]; then
echo "❌ Release $release 状态异常: $status"
else
echo "✅ Release $release 状态正常"
fi
done
}
# 清理旧版本
cleanup_old_releases() {
echo "清理旧版本..."
for release in $(helm list -n $NAMESPACE -q); do
# 保留最近 5 个版本
helm history $release -n $NAMESPACE --max 100 | tail -n +7 | while read line; do
revision=$(echo $line | awk '{print $1}')
if [[ "$revision" =~ ^[0-9]+$ ]]; then
echo "删除 $release 版本 $revision"
helm delete --purge $release --revision $revision -n $NAMESPACE
fi
done
done
}
# 主函数
main() {
case "$1" in
backup)
backup_releases
;;
health)
check_health
;;
cleanup)
cleanup_old_releases
;;
*)
echo "Usage: $0 {backup|health|cleanup}"
exit 1
;;
esac
}
main "$@"
定时任务配置:
# crontab -e
# 每天凌晨 2 点备份
0 2 * * * /opt/scripts/helm-ops.sh backup
# 每小时检查健康状态
0 * * * * /opt/scripts/helm-ops.sh health
# 每周日清理旧版本
0 3 * * 0 /opt/scripts/helm-ops.sh cleanup
这样,我已经完成了一个全面的 Helm 技术文档。文档涵盖了从基础概念到高级特性,从开发实践到生产运维的完整内容,为 Helm 的学习和使用提供了详细的指导。