K8s Helm Charts包管理器开发实战指南 从零构建到部署的全流程解析

引言:理解Helm在Kubernetes生态中的核心价值
在现代云原生技术栈中,Kubernetes已经成为容器编排的标准,但直接管理Kubernetes资源对象(如Deployment、Service、ConfigMap等)往往面临诸多挑战。Helm作为Kubernetes的包管理器,通过引入”Chart”的概念,将复杂的Kubernetes应用打包、配置和部署过程标准化,极大地简化了应用的生命周期管理。
为什么需要Helm?
想象一下,你需要部署一个包含前端Web服务、后端API、Redis缓存、PostgreSQL数据库以及Prometheus监控的完整应用。如果手动编写所有Kubernetes YAML文件,你将面临:
配置复杂性
:每个组件都有大量的配置参数
版本管理困难
:不同环境(开发、测试、生产)需要不同的配置
部署一致性
:确保每次部署的参数和资源定义完全一致
依赖管理
:组件之间的依赖关系需要手动处理
Helm通过以下方式解决这些问题:
打包应用
:将所有Kubernetes资源文件打包成一个Chart
参数化配置
:使用Go模板语法支持动态配置
依赖管理
:自动处理Chart之间的依赖关系
版本控制
:支持Chart版本的发布、回滚和升级
第一部分:Helm基础概念与环境准备
1.1 Helm核心概念解析
Chart
Chart是Helm中的应用打包单元,本质上是一个文件集合,包含:
Chart.yaml
:Chart的元数据描述文件
values.yaml
:默认配置参数文件
templates/
目录:Kubernetes资源模板文件
charts/
目录:依赖的子Chart
README.md
:使用说明文档
Release
Release是Chart在Kubernetes集群中运行的实例。同一个Chart可以部署多个Release,每个Release可以有不同的配置。
Repository
Repository是存储和分发Chart的服务器,类似于代码仓库。
1.2 环境准备与安装
安装Helm客户端
Linux系统:
# 下载最新版本
curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash

# 验证安装
helm version
# 输出示例:version.BuildInfo{Version:”v3.12.0″, GitCommit:”c5f05a4″, GitTreeState:”clean”, GoVersion:”go1.19.5″}
macOS系统:
# 使用Homebrew
brew install helm

# 或者手动下载
curl -LO https://get.helm.sh/helm-v3.12.0-darwin-amd64.tar.gz
tar -zxvf helm-v3.12.0-darwin-amd64.tar.gz
sudo mv darwin-amd64/helm /usr/local/bin/helm
Windows系统:
# 使用Chocolatey
choco install kubernetes-helm

# 或者使用winget
winget install Helm.Helm
配置Kubernetes集群访问
确保你的kubeconfig文件正确配置:
# 检查kubectl是否能正常连接集群
kubectl cluster-info

# 查看当前上下文
kubectl config current-context
添加常用Helm仓库
# 添加官方Helm仓库
helm repo add bitnami https://charts.bitnami.com/bitnami
helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts

# 更新仓库索引
helm repo update

# 查看已添加的仓库
helm repo list
# NAME URL
# bitnami https://charts.bitnami.com/bitnami
# ingress-nginx https://kubernetes.github.io/ingress-nginx
# prometheus-community https://prometheus-community.github.io/helm-charts
第二部分:从零开始创建第一个Helm Chart
2.1 创建Chart项目结构
让我们创建一个简单的Web应用Chart作为示例。假设我们要部署一个基于Node.js的简单API服务。
# 创建新的Chart
helm create my-webapp

# 查看生成的目录结构
tree my-webapp
生成的目录结构如下:
my-webapp/
├── Chart.yaml # Chart元数据
├── values.yaml # 默认配置值
├── charts/ # 依赖的子Chart
├── templates/ # Kubernetes模板文件
│ ├── _helpers.tpl # 模板辅助函数
│ ├── deployment.yaml # Deployment资源模板
│ ├── service.yaml # Service资源模板
│ ├── ingress.yaml # Ingress资源模板(可选)
│ └── serviceaccount.yaml # ServiceAccount模板(可选)
└── README.md # 说明文档
2.2 配置Chart.yaml
编辑
my-webapp/Chart.yaml
文件:
apiVersion: v2
name: my-webapp
description: A Helm chart for Kubernetes deployment of a Node.js web application

# 图标(可选)
icon: https://nodejs.org/static/images/logo.svg

# 版本号,遵循语义化版本规范
version: 1.0.0

# 应用版本,通常对应你的应用版本
appVersion: “1.0.0”

# 维护者信息
maintainers:
– name: yourname
email: yourname@example.com

# Chart类型
type: application

# 依赖的其他Chart(如果有)
dependencies:
# 示例:依赖Redis
# – name: redis
# version: “16.x.x”
# repository: “https://charts.bitnami.com/bitnami”
# condition: redis.enabled
2.3 设计values.yaml参数
values.yaml
是Chart的核心配置文件,定义了所有可配置的参数。编辑
my-webapp/values.yaml
:
# 默认副本数
replicaCount: 1

# 镜像配置
image:
repository: nginx
pullPolicy: IfNotPresent
# Overrides the image tag whose default is the chart appVersion.
tag: “”

# 服务配置
service:
type: ClusterIP
port: 80
targetPort: 8080

# Ingress配置
ingress:
enabled: false
className: “”
annotations: {}
# kubernetes.io/ingress.class: nginx
# cert-manager.io/cluster-issuer: “letsencrypt-prod”
hosts:
– host: chart-example.local
paths:
– path: /
pathType: ImplementationSpecific
tls: []
# – secretName: chart-example-tls
# hosts:
# – chart-example.local

# 资源限制
resources: {}
# We usually recommend not to specify default resources and to leave this as a conscious
# choice for the user. This also increases chances charts run on environments with little
# resources, such as Minikube. If you do want to specify resources, uncomment the following
# lines, adjust them as necessary, and remove the curly braces after ‘resources:’.
# limits:
# cpu: 100m
# memory: 128Mi
# requests:
# cpu: 100m
# memory: 128Mi

# 自动扩缩容配置
autoscaling:
enabled: false
minReplicas: 1
maxReplicas: 100
targetCPUUtilizationPercentage: 80
# targetMemoryUtilizationPercentage: 80

# 服务账户配置
serviceAccount:
# Specifies whether a service account should be created
create: true
# Annotations to add to the service account
annotations: {}
# The name of the service account to use.
# If not set and create is true, a name is generated using the fullname template
name: “”

# Pod安全上下文
podSecurityContext: {}
# fsGroup: 2000

# 安全上下文(容器级别)
securityContext: {}
# capabilities:
# drop:
# – ALL
# readOnlyRootFilesystem: true
# runAsNonRoot: true
# runAsUser: 1000

# 环境变量
env:
– name: NODE_ENV
value: “production”
– name: PORT
value: “8080”

# 配置文件(通过ConfigMap挂载)
config:
enabled: true
data:
config.json: |
{
“database”: {
“host”: “postgres”,
“port”: 5432
},
“cache”: {
“ttl”: 3600
}
}

# 健康检查
livenessProbe:
httpGet:
path: /health
port: http
initialDelaySeconds: 30
periodSeconds: 10

readinessProbe:
httpGet:
path: /health
port: http
initialDelaySeconds: 5
periodSeconds: 5
2.4 编写Kubernetes资源模板
2.4.1 创建Deployment模板
编辑
my-webapp/templates/deployment.yaml
:
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include “my-webapp.fullname” . }}
labels:
{{- include “my-webapp.labels” . | nindent 4 }}
spec:
{{- if not .Values.autoscaling.enabled }}
replicas: {{ .Values.replicaCount }}
{{- end }}
selector:
matchLabels:
{{- include “my-webapp.selectorLabels” . | nindent 6 }}
template:
metadata:
{{- with .Values.podAnnotations }}
annotations:
{{- toYaml . | nindent 8 }}
{{- end }}
labels:
{{- include “my-webapp.selectorLabels” . | nindent 8 }}
spec:
{{- with .Values.imagePullSecrets }}
imagePullSecrets:
{{- toYaml . | nindent 8 }}
{{- end }}
serviceAccountName: {{ include “my-webapp.serviceAccountName” . }}
securityContext:
{{- toYaml .Values.podSecurityContext | nindent 8 }}
containers:
– name: {{ .Chart.Name }}
securityContext:
{{- toYaml .Values.securityContext | nindent 12 }}
image: “{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}”
imagePullPolicy: {{ .Values.image.pullPolicy }}
ports:
– name: http
containerPort: {{ .Values.service.targetPort }}
protocol: TCP
livenessProbe:
{{- toYaml .Values.livenessProbe | nindent 12 }}
readinessProbe:
{{- toYaml .Values.readinessProbe | nindent 12 }}
resources:
{{- toYaml .Values.resources | nindent 12 }}
{{- if .Values.env }}
env:
{{- range .Values.env }}
– name: {{ .name }}
value: {{ .value | quote }}
{{- end }}
{{- end }}
{{- if .Values.config.enabled }}
volumeMounts:
– name: config-volume
mountPath: /app/config
readOnly: true
{{- end }}
{{- if .Values.config.enabled }}
volumes:
– name: config-volume
configMap:
name: {{ include “my-webapp.fullname” . }}-config
{{- end }}
{{- with .Values.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.affinity }}
affinity:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.tolerations }}
tolerations:
{{- toYaml . | nindent 8 }}
{{- end }}
2.4.2 创建Service模板
编辑
my-webapp/templates/service.yaml
:
apiVersion: v1
kind: Service
metadata:
name: {{ include “my-webapp.fullname” . }}
labels:
{{- include “my-webapp.labels” . | nindent 4 }}
spec:
type: {{ .Values.service.type }}
ports:
– port: {{ .Values.service.port }}
targetPort: {{ .Values.service.targetPort }}
protocol: TCP
name: http
selector:
{{- include “my-webapp.selectorLabels” . | nindent 4 }}
2.4.3 创建ConfigMap模板(用于配置文件)
编辑
my-webapp/templates/configmap.yaml
:
{{- if .Values.config.enabled -}}
apiVersion: v1
kind: ConfigMap
metadata:
name: {{ include “my-webapp.fullname” . }}-config
labels:
{{- include “my-webapp.labels” . | nindent 4 }}
data:
{{- range $key, $value := .Values.config.data }}
{{ $key }}: |
{{ $value | nindent 4 }}
{{- end }}
{{- end -}}
2.4.4 创建Ingress模板(可选)
编辑
my-webapp/templates/ingress.yaml
:
{{- if .Values.ingress.enabled -}}
{{- $fullName := include “my-webapp.fullname” . -}}
{{- $svcPort := .Values.service.port -}}
{{- if and .Values.ingress.className (not (semverCompare “>=1.18-0” .Capabilities.KubeVersion.GitVersion)) }}
{{- if not (hasKey .Values.ingress.annotations “kubernetes.io/ingress.class”) }}
{{- $_ := set .Values.ingress.annotations “kubernetes.io/ingress.class” .Values.ingress.className }}
{{- end }}
{{- end }}
{{- if semverCompare “>=1.19-0” .Capabilities.KubeVersion.GitVersion -}}
apiVersion: networking.k8s.io/v1
{{- else if semverCompare “>=1.14-0” .Capabilities.KubeVersion.GitVersion -}}
apiVersion: networking.k8s.io/v1beta1
{{- else -}}
apiVersion: extensions/v1beta1
{{- end }}
kind: Ingress
metadata:
name: {{ $fullName }}
labels:
{{- include “my-webapp.labels” . | nindent 4 }}
{{- with .Values.ingress.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
{{- if and .Values.ingress.className (semverCompare “>=1.18-0” .Capabilities.KubeVersion.GitVersion) }}
ingressClassName: {{ .Values.ingress.className }}
{{- end }}
{{- 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 }}
{{- if and .pathType (semverCompare “>=1.18-0” $.Capabilities.KubeVersion.GitVersion) }}
pathType: {{ .pathType }}
{{- end }}
backend:
{{- if semverCompare “>=1.19-0” $.Capabilities.KubeVersion.GitVersion }}
service:
name: {{ $fullName }}
port:
number: {{ $svcPort }}
{{- else }}
serviceName: {{ $fullName }}
servicePort: {{ $svcPort }}
{{- end }}
{{- end }}
{{- end }}
{{- end }}
2.4.5 创建ServiceAccount模板(可选)
编辑
my-webapp/templates/serviceaccount.yaml
:
{{- if .Values.serviceAccount.create -}}
apiVersion: v1
kind: ServiceAccount
metadata:
name: {{ include “my-webapp.serviceAccountName” . }}
labels:
{{- include “my-webapp.labels” . | nindent 4 }}
{{- with .Values.serviceAccount.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
{{- end }}
2.5 配置辅助模板文件
编辑
my-webapp/templates/_helpers.tpl
,添加常用的模板辅助函数:
{{/*
Expand the name of the chart.
*/}}
{{- define “my-webapp.name” -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix “-” }}
{{- end }}

{{/*
Create a default fully qualified app name.
*/}}
{{- define “my-webapp.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 }}

{{/*
Create chart name and version as used by the chart label.
*/}}
{{- define “my-webapp.chart” -}}
{{- printf “%s-%s” .Chart.Name .Chart.Version | replace “+” “_” | trunc 63 | trimSuffix “-” }}
{{- end }}

{{/*
Common labels
*/}}
{{- define “my-webapp.labels” -}}
helm.sh/chart: {{ include “my-webapp.chart” . }}
{{ include “my-webapp.selectorLabels” . }}
{{- if .Chart.AppVersion }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}

{{/*
Selector labels
*/}}
{{- define “my-webapp.selectorLabels” -}}
app.kubernetes.io/name: {{ include “my-webapp.name” . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}

{{/*
Create the name of the service account to use
*/}}
{{- define “my-webapp.serviceAccountName” -}}
{{- if .Values.serviceAccount.create }}
{{- default (include “my-webapp.fullname” .) .Values.serviceAccount.name }}
{{- else }}
{{- default “default” .Values.serviceAccount.name }}
{{- end }}
{{- end }}
2.6 验证Chart语法
在部署之前,先验证Chart的语法是否正确:
# 进入Chart目录
cd my-webapp

# 检查模板语法
helm template . –debug

# 如果有错误,会显示详细的错误信息
# 如果成功,会输出渲染后的Kubernetes YAML
第三部分:Chart开发进阶技巧
3.1 使用条件判断和循环
条件判断示例
在
deployment.yaml
中,我们可以根据配置决定是否挂载配置文件:
# 在containers部分
{{- if .Values.config.enabled }}
volumeMounts:
– name: config-volume
mountPath: /app/config
readOnly: true
{{- end }}
循环示例
处理多个环境变量:
env:
{{- range .Values.env }}
– name: {{ .name }}
value: {{ .value | quote }}
{{- end }}
处理多个端口:
ports:
{{- range .Values.ports }}
– name: {{ .name }}
containerPort: {{ .containerPort }}
protocol: {{ .protocol }}
{{- end }}
3.2 子Chart和依赖管理
创建依赖关系
假设我们的应用依赖Redis和PostgreSQL,可以在
Chart.yaml
中声明:
dependencies:
– name: redis
version: “16.x.x”
repository: “https://charts.bitnami.com/bitnami”
condition: redis.enabled
– name: postgresql
version: “11.x.x”
repository: “https://charts.bitnami.com/bitnami”
condition: postgresql.enabled
然后在
values.yaml
中配置子Chart的参数:
redis:
enabled: true
auth:
enabled: true
password: “my-secure-password”

postgresql:
enabled: true
auth:
username: myapp
password: myapp-password
database: myapp
下载依赖:
helm dependency update
3.3 模板函数和管道
Helm提供了丰富的内置函数,常用的有:
字符串处理
# 大小写转换
name: {{ .Values.name | upper | quote }}

# 截断
name: {{ .Values.name | trunc 63 }}

# 默认值
name: {{ .Values.name | default “myapp” }}
数值计算
# 计算副本数
replicas: {{ .Values.replicaCount | int }}

# 算术运算
port: {{ add .Values.service.port 1 }}
条件判断
# 如果值存在
{{- if .Values.ingress.enabled }}
# ingress配置
{{- end }}

# 如果值不存在
{{- if not .Values.autoscaling.enabled }}
replicas: {{ .Values.replicaCount }}
{{- end }}
字典操作
# 合并字典
{{- $labels := merge .Values.podLabels .Values.globalLabels }}
3.4 使用命名模板
在
_helpers.tpl
中定义可重用的模板:
{{/*
Define a common label set
*/}}
{{- define “my-webapp.commonLabels” -}}
app: {{ include “my-webapp.name” . }}
version: {{ .Chart.AppVersion }}
environment: {{ .Values.global.environment }}
{{- end }}

# 在其他模板中使用
metadata:
labels:
{{- include “my-webapp.commonLabels” . | nindent 4 }}
3.5 验证和测试
使用schema验证
创建
values.schema.json
来验证输入参数:
{
“$schema”: “http://json-schema.org/draft-07/schema#”,
“type”: “object”,
“properties”: {
“replicaCount”: {
“type”: “integer”,
“minimum”: 1,
“maximum”: 100
},
“image”: {
“type”: “object”,
“properties”: {
“repository”: {
“type”: “string”
},
“tag”: {
“type”: “string”
},
“pullPolicy”: {
“type”: “string”,
“enum”: [“Always”, “IfNotPresent”, “Never”]
}
},
“required”: [“repository”]
},
“service”: {
“type”: “object”,
“properties”: {
“type”: {
“type”: “string”,
“enum”: [“ClusterIP”, “NodePort”, “LoadBalancer”]
},
“port”: {
“type”: “integer”,
“minimum”: 1,
“maximum”: 65535
}
}
}
},
“required”: [“image”]
}
单元测试
使用
helm unittest
插件进行测试:
# 安装helm unittest插件
helm plugin install https://github.com/helm-unittest/helm-unittest

# 创建测试文件 my-webapp/tests/deployment_test.yaml
测试文件示例:
suite: test deployment
templates:
– deployment.yaml
tests:
– it: should create a deployment
asserts:
– hasKind:
of: Deployment
– hasDocument:
count: 1
– it: should have correct labels
asserts:
– equal:
path: metadata.labels.app
value: my-webapp
– it: should use custom replica count
set:
replicaCount: 3
asserts:
– equal:
path: spec.replicas
value: 3
运行测试:
helm unittest my-webapp
第四部分:Chart的打包、发布与版本管理
4.1 本地测试和调试
使用helm template进行本地渲染
# 基本渲染
helm template my-webapp ./my-webapp

# 使用自定义values文件
helm template my-webapp ./my-webapp -f values-production.yaml

# 设置单个参数
helm template my-webapp ./my-webapp –set replicaCount=3

# 设置多个参数
helm template my-webapp ./my-webapp –set replicaCount=3,image.tag=2.0.0

# 查看渲染结果但不安装
helm template my-webapp ./my-webapp –debug
使用helm install –dry-run
# 模拟安装(不会真正创建资源)
helm install my-webapp ./my-webapp –dry-run –debug

# 模拟升级
helm upgrade my-webapp ./my-webapp –dry-run –debug
4.2 Chart版本管理
语义化版本规范
遵循SemVer规范:
主版本号(MAJOR)
:不兼容的API变更
次版本号(MINOR)
:向后兼容的功能新增
修订号(PATCH)
:向后兼容的问题修正
示例版本演进:
1.0.0 -> 1.0.1 (修复bug)
1.0.1 -> 1.1.0 (新增功能)
1.1.0 -> 2.0.0 (破坏性变更)
更新Chart版本
在
Chart.yaml
中更新版本:
version: 1.1.0 # 更新版本号
appVersion: “1.1.0” # 更新应用版本
4.3 打包Chart
# 打包当前目录的Chart
helm package my-webapp

# 指定输出目录
helm package my-webapp –destination ./charts

# 使用版本号覆盖
helm package my-webapp –version 1.2.0
打包后会生成
.tgz
文件,如:
my-webapp-1.0.0.tgz
4.4 创建Chart仓库
本地仓库
# 创建仓库目录
mkdir my-chart-repo
cd my-chart-repo

# 将打包的Chart复制到仓库目录
cp ../my-webapp-1.0.0.tgz .

# 生成仓库索引
helm repo index .

# 查看生成的index.yaml
cat index.yaml
index.yaml
示例:
apiVersion: v1
entries:
my-webapp:
– name: my-webapp
version: 1.0.0
appVersion: “1.0.0”
description: A Helm chart for Kubernetes deployment of a Node.js web application
digest: sha256:1234567890abcdef…
created: “2023-01-01T12:00:00Z”
urls:
– https://myrepo.example.com/charts/my-webapp-1.0.0.tgz
使用本地仓库
# 添加本地仓库
helm repo add myrepo http://localhost:8080

# 或者使用文件系统路径(开发用)
helm repo add myrepo file:///path/to/my-chart-repo

# 更新仓库
helm repo update

# 查看仓库中的Chart
helm search repo myrepo
4.5 使用GitHub Pages托管Chart仓库
步骤1:创建GitHub仓库
# 创建仓库,假设名为 helm-charts
# 启用GitHub Pages
步骤2:设置GitHub Actions自动构建
创建
.github/workflows/release.yml
:
name: Release Charts

on:
push:
branches:
– main
paths:
– ‘charts/**’

jobs:
release:
runs-on: ubuntu-latest
steps:
– name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0

– name: Configure Git
run: |
git config user.name “$GITHUB_ACTOR”
git config user.email “$GITHUB_ACTOR@users.noreply.github.com”

– name: Install Helm
uses: azure/setup-helm@v3
with:
version: ‘v3.12.0’

– name: Run chart-releaser
uses: helm/chart-releaser-action@v1.5.0
env:
CR_TOKEN: “${{ secrets.GITHUB_TOKEN }}”
步骤3:使用chart-releaser工具
# 安装chart-releaser
# 创建GitHub Release并上传Chart
cr upload –owner –repo –token

# 更新仓库索引
cr index –owner –repo –token
4.6 发布到公共仓库
发布到Artifact Hub
Artifact Hub是CNCF的Chart仓库聚合服务。
# 注册账号并添加仓库
# 在Artifact Hub控制台添加你的GitHub仓库URL
发布到Bitnami等公共仓库
通常需要贡献代码到对应仓库的GitHub项目,遵循其贡献指南。
第五部分:部署与生命周期管理
5.1 安装Chart
基本安装
# 从仓库安装
helm install my-webapp bitnami/nginx

# 从本地Chart安装
helm install my-webapp ./my-webapp

# 从打包文件安装
helm install my-webapp ./my-webapp-1.0.0.tgz

# 从URL安装
helm install my-webapp https://myrepo.example.com/charts/my-webapp-1.0.0.tgz
使用自定义配置
# 使用自定义values文件
helm install my-webapp ./my-webapp -f values-production.yaml

# 命令行设置参数
helm install my-webapp ./my-webapp –set replicaCount=3,image.tag=2.0.0

# 设置多个参数(使用逗号分隔)
helm install my-webapp ./my-webapp –set replicaCount=3,image.tag=2.0.0,service.type=LoadBalancer

# 使用文件设置复杂结构
helm install my-webapp ./my-webapp –set-file config=config.json
等待部署完成
# 等待所有Pod就绪
helm install my-webapp ./my-webapp –wait –timeout 5m

# 查看部署状态
helm status my-webapp
5.2 升级和回滚
升级Release
# 升级到新版本Chart
helm upgrade my-webapp ./my-webapp

# 升级并设置新参数
helm upgrade my-webapp ./my-webapp –set replicaCount=5,image.tag=2.1.0

# 使用新的values文件
helm upgrade my-webapp ./my-webapp -f values-new.yaml

# 等待升级完成
helm upgrade my-webapp ./my-webapp –wait –timeout 10m

# 强制升级(跳过验证)
helm upgrade my-webapp ./my-webapp –force
回滚操作
# 查看历史版本
helm history my-webapp

# 输出示例:
# REVISION UPDATED STATUS CHART APP VERSION DESCRIPTION
# 1 Mon Jan 1 12:00:00 2023 superseded my-webapp-1.0.0 1.0.0 Install complete
# 2 Mon Jan 2 12:00:00 2023 superseded my-webapp-1.1.0 1.1.0 Upgrade complete
# 3 Mon Jan 3 12:00:00 2023 deployed my-webapp-1.2.0 1.2.0 Upgrade complete

# 回滚到上一个版本
helm rollback my-webapp

# 回滚到指定版本
helm rollback my-webapp 2

# 回滚并等待
helm rollback my-webapp 2 –wait
5.3 管理Release
查看已安装的Release
# 列出所有Release
helm list

# 列出所有命名空间的Release
helm list –all-namespaces

# 只显示特定命名空间
helm list -n production

# 查看Release详情
helm get all my-webapp

# 查看manifest(生成的YAML)
helm get manifest my-webapp

# 查看values(使用的配置)
helm get values my-webapp

# 查看notes(安装说明)
helm get notes my-webapp
删除Release
# 删除Release
helm uninstall my-webapp

# 删除并保留历史(用于后续回滚)
helm uninstall my-webapp –keep-history

# 删除指定命名空间的Release
helm uninstall my-webapp -n production

# 强制删除(跳过等待)
helm uninstall my-webapp –no-hooks
5.4 使用Helmfile进行批量管理
对于管理多个Release的复杂场景,可以使用Helmfile:
安装Helmfile
# macOS
brew install helmfile

# Linux
wget https://github.com/helmfile/helmfile/releases/download/v0.155.0/helmfile_0.155.0_linux_amd64.tar.gz
tar -xzf helmfile_0.155.0_linux_amd64.tar.gz
sudo mv helmfile /usr/local/bin/
创建Helmfile配置
创建
helmfile.yaml
:
# helmfile.yaml
repositories:
– name: bitnami
url: https://charts.bitnami.com/bitnami
– name: ingress-nginx
url: https://kubernetes.github.io/ingress-nginx

releases:
– name: my-webapp-prod
namespace: production
chart: ./my-webapp
values:
– values-production.yaml
set:
– replicaCount=3
– image.tag=2.0.0

– name: my-webapp-staging
namespace: staging
chart: ./my-webapp
values:
– values-staging.yaml

– name: nginx-ingress
namespace: ingress-nginx
chart: ingress-nginx/ingress-nginx
version: “4.x.x”
values:
– controller:
service:
type: LoadBalancer
使用Helmfile
# 查看将要执行的变更
helmfile diff

# 应用配置
helmfile apply

# 同步(安装/升级)
helmfile sync

# 删除所有配置
helmfile destroy
第六部分:高级主题与最佳实践
6.1 CI/CD集成
GitHub Actions完整工作流
创建
.github/workflows/helm-ci.yml
:
name: Helm CI/CD

on:
push:
branches:
– main
paths:
– ‘charts/**’
– ‘.github/workflows/helm-ci.yml’
pull_request:
branches:
– main

jobs:
lint:
runs-on: ubuntu-latest
steps:
– name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0

– name: Set up Helm
uses: azure/setup-helm@v3
with:
version: ‘v3.12.0’

– name: Lint chart
run: |
helm lint ./my-webapp
helm lint ./my-webapp –strict

– name: Template chart
run: |
helm template ./my-webapp –debug

test:
runs-on: ubuntu-latest
needs: lint
steps:
– name: Checkout
uses: actions/checkout@v3

– name: Set up Helm
uses: azure/setup-helm@v3
with:
version: ‘v3.12.0’

– name: Install helm unittest
run: |
helm plugin install https://github.com/helm-unittest/helm-unittest
helm unittest ./my-webapp

– name: Create kind cluster
uses: helm/kind-action@v1.5.0
with:
cluster_name: helm-test

– name: Install chart
run: |
helm install my-webapp-test ./my-webapp –wait –timeout 5m

– name: Test chart
run: |
kubectl get pods -n default
kubectl get svc -n default
# Add more tests as needed

release:
runs-on: ubuntu-latest
needs: [lint, test]
if: github.ref == ‘refs/heads/main’
steps:
– name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0

– name: Configure Git
run: |
git config user.name “$GITHUB_ACTOR”
git config user.email “$GITHUB_ACTOR@users.noreply.github.com”

– name: Set up Helm
uses: azure/setup-helm@v3
with:
version: ‘v3.12.0’

– name: Run chart-releaser
uses: helm/chart-releaser-action@v1.5.0
env:
CR_TOKEN: “${{ secrets.GITHUB_TOKEN }}”
CR_SKIP_EXISTING: true
6.2 安全最佳实践
1. 使用非root用户运行容器
在
values.yaml
中:
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000
fsGroup: 2000
2. 资源限制
resources:
limits:
cpu: 500m
memory: 512Mi
requests:
cpu: 100m
memory: 128Mi
3. 网络策略
创建
templates/networkpolicy.yaml
:
{{- if .Values.networkPolicy.enabled }}
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: {{ include “my-webapp.fullname” . }}
spec:
podSelector:
matchLabels:
{{- include “my-webapp.selectorLabels” . | nindent 6 }}
policyTypes:
– Ingress
– Egress
ingress:
– from:
– namespaceSelector:
matchLabels:
name: ingress-nginx
ports:
– protocol: TCP
port: {{ .Values.service.targetPort }}
egress:
– to:
– namespaceSelector:
matchLabels:
name: database
ports:
– protocol: TCP
port: 5432
{{- end }}
4. 使用Secret管理敏感信息
# templates/secret.yaml
apiVersion: v1
kind: Secret
metadata:
name: {{ include “my-webapp.fullname” . }}-secret
type: Opaque
data:
database-password: {{ .Values.database.password | b64enc | quote }}
api-key: {{ .Values.api.key | b64enc | quote }}
6.3 性能优化
1. 使用HPA(水平Pod自动扩缩容)
# templates/hpa.yaml
{{- if .Values.autoscaling.enabled }}
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: {{ include “my-webapp.fullname” . }}
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: {{ include “my-webapp.fullname” . }}
minReplicas: {{ .Values.autoscaling.minReplicas }}
maxReplicas: {{ .Values.autoscaling.maxReplicas }}
metrics:
{{- if .Values.autoscaling.targetCPUUtilizationPercentage }}
– type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: {{ .Values.autoscaling.targetCPUUtilizationPercentage }}
{{- end }}
{{- if .Values.autoscaling.targetMemoryUtilizationPercentage }}
– type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: {{ .Values.autoscaling.targetMemoryUtilizationPercentage }}
{{- end }}
{{- end }}
2. 使用PDB(PodDisruptionBudget)
# templates/pdb.yaml
{{- if .Values.podDisruptionBudget.enabled }}
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: {{ include “my-webapp.fullname” . }}
spec:
{{- if .Values.podDisruptionBudget.minAvailable }}
minAvailable: {{ .Values.podDisruptionBudget.minAvailable }}
{{- else if .Values.podDisruptionBudget.maxUnavailable }}
maxUnavailable: {{ .Values.podDisruptionBudget.maxUnavailable }}
{{- end }}
selector:
matchLabels:
{{- include “my-webapp.selectorLabels” . | nindent 6 }}
{{- end }}
6.4 多环境管理策略
方法1:使用不同values文件
my-webapp/
├── values-dev.yaml
├── values-staging.yaml
└── values-prod.yaml
方法2:使用Helmfile环境
# helmfile.yaml
environments:
dev:
values:
– values-dev.yaml
staging:
values:
– values-staging.yaml
prod:
values:
– values-prod.yaml

releases:
– name: my-webapp
chart: ./my-webapp
values:
– values.yaml
{{- if eq .Environment.Name “prod” }}
set:
– replicaCount=3
{{- end }}
方法3:使用Kustomize + Helm
# 先用Helm生成基础YAML
helm template my-webapp ./my-webapp > base.yaml

# 然后用Kustomize进行环境特定的patch
kustomize build overlays/production/
6.5 监控和日志
集成Prometheus监控
在Chart中添加ServiceMonitor:
# templates/servicemonitor.yaml
{{- if .Values.metrics.enabled }}
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: {{ include “my-webapp.fullname” . }}
labels:
{{- include “my-webapp.labels” . | nindent 4 }}
spec:
selector:
matchLabels:
{{- include “my-webapp.selectorLabels” . | nindent 6 }}
endpoints:
– port: http
path: /metrics
interval: 30s
{{- end }}
集成日志收集
在
deployment.yaml
中添加日志边车:
containers:
– name: {{ .Chart.Name }}
# 主容器配置
– name: log-collector
image: fluent/fluent-bit:latest
volumeMounts:
– name: varlog
mountPath: /var/log
volumes:
– name: varlog
emptyDir: {}
第七部分:实战案例 – 完整的微服务应用Chart
7.1 项目结构
microservice-app/
├── Chart.yaml
├── values.yaml
├── values-dev.yaml
├── values-prod.yaml
├── charts/
│ ├── redis-16.0.0.tgz
│ └── postgresql-11.0.0.tgz
├── templates/
│ ├── _helpers.tpl
│ ├── deployment.yaml
│ ├── service.yaml
│ ├── ingress.yaml
│ ├── configmap.yaml
│ ├── secret.yaml
│ ├── hpa.yaml
│ ├── pdb.yaml
│ ├── networkpolicy.yaml
│ └── servicemonitor.yaml
└── README.md
7.2 完整的Chart.yaml
apiVersion: v2
name: microservice-app
description: A comprehensive Helm chart for a microservice application
type: application
version: 1.0.0
appVersion: “1.0.0”
icon: https://example.com/icon.png

dependencies:
– name: redis
version: “16.x.x”
repository: “https://charts.bitnami.com/bitnami”
condition: redis.enabled
– name: postgresql
version: “11.x.x”
repository: “https://charts.bitnami.com/bitnami”
condition: postgresql.enabled

maintainers:
– name: DevOps Team
email: devops@example.com
7.3 完整的values.yaml
# 全局配置
global:
environment: production
domain: example.com

# 应用配置
app:
name: microservice-app
port: 8080
replicaCount: 2

# 镜像配置
image:
repository: myregistry/microservice-app
tag: “1.0.0”
pullPolicy: IfNotPresent
pullSecrets: []

# 服务配置
service:
type: ClusterIP
port: 80
targetPort: 8080
annotations: {}

# Ingress配置
ingress:
enabled: true
className: “nginx”
annotations:
cert-manager.io/cluster-issuer: “letsencrypt-prod”
hosts:
– host: api.example.com
paths:
– path: /
pathType: Prefix
tls:
– secretName: api-tls
hosts:
– api.example.com

# 资源配置
resources:
limits:
cpu: 500m
memory: 512Mi
requests:
cpu: 100m
memory: 128Mi

# 自动扩缩容
autoscaling:
enabled: true
minReplicas: 2
maxReplicas: 10
targetCPUUtilizationPercentage: 80
targetMemoryUtilizationPercentage: 80

# 健康检查
livenessProbe:
httpGet:
path: /health
port: http
initialDelaySeconds: 30
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 3

readinessProbe:
httpGet:
path: /ready
port: http
initialDelaySeconds: 5
periodSeconds: 5
timeoutSeconds: 3
failureThreshold: 3

# 环境变量
env:
– name: NODE_ENV
value: “production”
– name: PORT
value: “8080”
– name: LOG_LEVEL
value: “info”

# 配置文件
config:
enabled: true
data:
config.json: |
{
“database”: {
“host”: “{{ .Release.Name }}-postgresql”,
“port”: 5432,
“name”: “microservice”
},
“cache”: {
“host”: “{{ .Release.Name }}-redis”,
“port”: 6379
},
“logging”: {
“level”: “info”,
“format”: “json”
}
}

# 敏感信息(通过Secret)
secrets:
database:
username: microservice
password: “” # 在安装时设置
api:
key: “” # 在安装时设置

# 安全配置
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000
fsGroup: 2000
capabilities:
drop:
– ALL
readOnlyRootFilesystem: true

# 网络策略
networkPolicy:
enabled: true
ingress:
– from:
– namespaceSelector:
matchLabels:
name: ingress-nginx
ports:
– protocol: TCP
port: 8080
egress:
– to:
– namespaceSelector:
matchLabels:
name: database
ports:
– protocol: TCP
port: 5432
– to:
– namespaceSelector:
matchLabels:
name: cache
ports:
– protocol: TCP
port: 6379

# 监控配置
metrics:
enabled: true
serviceMonitor:
interval: 30s
path: /metrics

# PodDisruptionBudget
podDisruptionBudget:
enabled: true
minAvailable: 1

# 子Chart配置
redis:
enabled: true
auth:
enabled: true
password: “redis-password-123”
master:
persistence:
enabled: true
size: 1Gi

postgresql:
enabled: true
auth:
username: microservice
password: “postgres-password-123”
database: microservice
primary:
persistence:
enabled: true
size: 5Gi
7.4 完整的deployment.yaml模板
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include “microservice-app.fullname” . }}
labels:
{{- include “microservice-app.labels” . | nindent 4 }}
spec:
{{- if not .Values.autoscaling.enabled }}
replicas: {{ .Values.app.replicaCount }}
{{- end }}
selector:
matchLabels:
{{- include “microservice-app.selectorLabels” . | nindent 6 }}
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
template:
metadata:
{{- with .Values.podAnnotations }}
annotations:
{{- toYaml . | nindent 8 }}
{{- end }}
labels:
{{- include “microservice-app.selectorLabels” . | nindent 8 }}
spec:
{{- with .Values.image.pullSecrets }}
imagePullSecrets:
{{- toYaml . | nindent 8 }}
{{- end }}
serviceAccountName: {{ include “microservice-app.serviceAccountName” . }}
securityContext:
{{- toYaml .Values.securityContext | nindent 8 }}
containers:
– name: {{ .Chart.Name }}
securityContext:
{{- toYaml .Values.securityContext | nindent 12 }}
image: “{{ .Values.image.repository }}:{{ .Values.image.tag }}”
imagePullPolicy: {{ .Values.image.pullPolicy }}
ports:
– name: http
containerPort: {{ .Values.app.port }}
protocol: TCP
livenessProbe:
{{- toYaml .Values.livenessProbe | nindent 12 }}
readinessProbe:
{{- toYaml .Values.readinessProbe | nindent 12 }}
resources:
{{- toYaml .Values.resources | nindent 12 }}
{{- if .Values.env }}
env:
{{- range .Values.env }}
– name: {{ .name }}
value: {{ .value | quote }}
{{- end }}
{{- end }}
{{- if or .Values.config.enabled .Values.secrets.database.password }}
envFrom:
{{- if .Values.config.enabled }}
– configMapRef:
name: {{ include “microservice-app.fullname” . }}-config
{{- end }}
{{- if .Values.secrets.database.password }}
– secretRef:
name: {{ include “microservice-app.fullname” . }}-secret
{{- end }}
{{- end }}
{{- if .Values.config.enabled }}
volumeMounts:
– name: config-volume
mountPath: /app/config
readOnly: true
{{- end }}
{{- if .Values.securityContext.readOnlyRootFilesystem }}
volumeMounts:
– name: tmp
mountPath: /tmp
{{- end }}
{{- if .Values.config.enabled }}
volumes:
– name: config-volume
configMap:
name: {{ include “microservice-app.fullname” . }}-config
{{- end }}
{{- if .Values.securityContext.readOnlyRootFilesystem }}
– name: tmp
emptyDir: {}
{{- end }}
{{- with .Values.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.affinity }}
affinity:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.tolerations }}
tolerations:
{{- toYaml . | nindent 8 }}
{{- end }}
7.5 部署命令示例
# 1. 更新依赖
helm dependency update

# 2. 验证Chart
helm lint .
helm template . –debug

# 3. 开发环境部署
helm install microservice-app-dev . \
-f values-dev.yaml \
–set secrets.database.password=”dev-password” \
–set secrets.api.key=”dev-api-key” \
–namespace dev \
–create-namespace \
–wait

# 4. 生产环境部署
helm install microservice-app-prod . \
-f values-prod.yaml \
–set secrets.database.password=”$(openssl rand -base64 32)” \
–set secrets.api.key=”$(openssl rand -base64 32)” \
–namespace production \
–create-namespace \
–wait \
–timeout 10m

# 5. 升级生产环境
helm upgrade microservice-app-prod . \
-f values-prod.yaml \
–set image.tag=1.1.0 \
–namespace production \
–wait

# 6. 回滚
helm rollback microservice-app-prod 1 –namespace production
第八部分:故障排除与调试技巧
8.1 常见问题及解决方案
问题1:模板渲染错误
症状
:
helm install
或
helm template
报错
解决方案
:
# 使用–debug查看详细错误
helm template my-app . –debug

# 检查YAML语法
yamllint templates/

# 检查模板语法
helm lint .
问题2:资源创建失败
症状
:Pod处于Pending或CrashLoopBackOff状态
排查步骤
:
# 查看Pod状态
kubectl get pods -n

# 查看Pod详情
kubectl describe pod -n

# 查看Pod日志
kubectl logs -n
kubectl logs -n –previous # 查看前一个崩溃的容器日志

# 检查事件
kubectl get events -n –sort-by=’.lastTimestamp’
问题3:配置不生效
症状
:修改了values但应用没有变化
解决方案
:
# 查看实际使用的values
helm get values

# 检查模板是否正确渲染
helm get manifest

# 比较差异
helm diff upgrade . -f values-new.yaml
8.2 调试工具和技巧
使用helm diff插件
# 安装插件
helm plugin install https://github.com/databus23/helm-diff

# 查看升级差异
helm diff upgrade my-app . -f values-new.yaml

# 查看安装差异(dry-run)
helm diff install my-app . -f values.yaml
使用helm-secrets插件(管理敏感数据)
# 安装插件
helm plugin install https://github.com/jkroepke/helm-secrets

# 加密敏感文件
helm secrets encrypt values-secrets.yaml

# 使用加密文件部署
helm install my-app . -f values.yaml -f values-secrets.yaml.enc
使用helm-schema生成schema
# 安装插件
helm plugin install https://github.com/karuppiah7890/helm-schema

# 生成schema
helm schema generate
8.3 日志和监控
启用Helm调试日志
# 设置环境变量
export HELM_DEBUG=1
helm install my-app . –debug

# 或者使用–debug标志
helm install my-app . –debug
使用kubectl进行实时监控
# 实时查看Pod状态
kubectl get pods -w -n

# 实时查看事件
kubectl get events -w -n

# 实时查看日志
kubectl logs -f -n
第九部分:总结与进阶学习路径
9.1 核心要点回顾
Chart结构
:理解Chart.yaml、values.yaml、templates/目录的作用
模板语法
:掌握Go模板、条件判断、循环、函数使用
依赖管理
:使用子Chart管理复杂应用依赖
版本控制
:遵循SemVer规范进行版本管理
生命周期管理
:熟练使用install、upgrade、rollback等命令
安全最佳实践
:资源限制、安全上下文、网络策略
多环境管理
:使用不同values文件或Helmfile管理多环境
9.2 进阶学习路径
阶段1:深入理解Helm内部机制
学习Helm的架构和工作原理
研究Helm的源码(Go语言编写)
理解Tiller(Helm v2)与Helm v3的区别
阶段2:高级模板技巧
学习更多内置函数
自定义模板函数
复杂条件逻辑处理
阶段3:生态系统集成
与ArgoCD、Flux等GitOps工具集成
使用Helmfile管理大规模部署
与Prometheus、Grafana监控集成
阶段4:企业级实践
Chart仓库管理(Harbor、Nexus)
CI/CD流水线集成
安全扫描和合规检查
多集群部署策略
9.3 推荐资源
官方文档
Helm官方文档
Helm Charts GitHub
社区资源
Artifact Hub
Helm Community Slack
书籍推荐
“Helm: Up and Running” by Matt Farina, Matt Butcher, and Josh Dolitsky
实践项目
尝试将现有的Kubernetes应用迁移到Helm
为开源项目贡献Helm Chart
创建自己的Chart仓库
9.4 持续学习建议
保持更新
:Helm版本迭代较快,关注新特性
实践驱动
:在实际项目中应用Helm
社区参与
:参与Helm社区讨论和贡献
最佳实践
:持续学习和应用最佳实践
通过本指南的学习,你应该能够独立开发、部署和管理复杂的Helm Chart,并在生产环境中安全可靠地使用Helm。记住,Helm是强大的工具,但需要谨慎使用,特别是在生产环境中。始终在测试环境中充分验证你的Chart,使用版本控制,并建立完善的回滚机制。