Helm Chart 编写与管理最佳实践
Raj Kumar | 2026-09-01T08:57:16 | DevOps, Cloud
深入 Helm 3 的模板语法、values 分层、依赖管理、Chart 测试及企业级 Chart 仓库搭建方案。
# Helm Chart 编写与管理最佳实践 ## Chart 结构 ``` my-app/ Chart.yaml # Chart 元数据 values.yaml # 默认配置 values-prod.yaml # 生产环境覆盖 templates/ deployment.yaml service.yaml ingress.yaml configmap.yaml _helpers.tpl # 模板辅助函数 NOTES.txt # 安装后提示 charts/ # 子 Chart 依赖 tests/ test-connection.yaml ``` ## 模板语法进阶 ```yaml # templates/_helpers.tpl {{- define "my-app.labels" -}} app.kubernetes.io/name: {{ include "my-app.name" . }} app.kubernetes.io/instance: {{ .Release.Name }} app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} app.kubernetes.io/managed-by: {{ .Release.Service }} {{- end }} # templates/deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: {{ include "my-app.fullname" . }} labels: {{- include "my-app.labels" . | nindent 4 }} spec: replicas: {{ .Values.replicaCount }} selector: matchLabels: app: {{ include "my-app.name" . }} template: spec: containers: - name: {{ .Chart.Name }} image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}" ports: - containerPort: {{ .Values.service.targetPort }} {{- if .Values.resources }} resources: {{- toYaml .Values.resources | nindent 12 }} {{- end }} envFrom: - configMapRef: name: {{ include "my-app.fullname" . }}-config ``` ## Values 分层覆盖 ```bash # 开发环境 helm install my-app ./my-app -f values.yaml # 生产环境叠加覆盖 helm install my-app ./my-app -f values.yaml -f values-prod.yaml \ --set image.tag=v2.1.0 # 查看最终渲染结果 helm template my-app ./my-app -f values-prod.yaml ``` ## Chart 测试 ```yaml # tests/test-connection.yaml apiVersion: v1 kind: Pod metadata: name: "{{ include "my-app.fullname" . }}-test" annotations: "helm.sh/hook": test spec: containers: - name: curl-test image: curlimages/curl:latest command: ['curl'] args: ['{{ include "my-app.fullname" . }}:{{ .Values.service.port }}/health'] restartPolicy: Never ``` Helm Chart 是 Kubernetes 应用分发的事实标准,建议配合 ChartMuseum 或 OCI Registry 搭建企业内部 Chart 仓库。