Helm Chart包管理实战:Kubernetes应用模板化部署与版本回滚方案

Helm是Kubernetes的包管理工具,通过Chart将应用部署所需的所有资源对象打包为可复用模板。一个Chart包含Deployment、Service、ConfigMap、Secret等资源定义,配合values.yaml实现多环境参数差异化配置。Helm的版本管理能力支持一键回滚到历史版本,相比直接apply YAML文件,大幅降低了Kubernetes应用的管理复杂度。

Helm Chart目录结构与模板渲染

# Chart目录结构
my-app/
├── Chart.yaml          # Chart元数据
├── values.yaml          # 默认配置值
├── values-prod.yaml     # 生产环境覆盖配置
├── templates/
│   ├── deployment.yaml
│   ├── service.yaml
│   ├── configmap.yaml
│   ├── ingress.yaml
│   ├── hpa.yaml
│   └── _helpers.tpl      # 模板辅助函数
└── charts/               # 依赖的子Chart

# Chart.yaml
apiVersion: v2
name: my-app
description: Web application Helm chart
type: application
version: 1.2.3
appVersion: "3.1.0"

# 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:
      {{- include "my-app.selectorLabels" . | nindent 6 }}
  template:
    metadata:
      labels:
        {{- include "my-app.selectorLabels" . | nindent 8 }}
    spec:
      containers:
        - name: {{ .Chart.Name }}
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          ports:
            - containerPort: 8080
              protocol: TCP
          resources:
            {{- toYaml .Values.resources | nindent 12 }}
          {{- if .Values.probe.enabled }}
          readinessProbe:
            httpGet:
              path: /health
              port: 8080
            initialDelaySeconds: 10
            periodSeconds: 5
          {{- end }}

values.yaml多环境配置与覆盖策略

# values.yaml - 默认配置
replicaCount: 2

image:
  repository: registry.example.com/my-app
  tag: "3.1.0"
  pullPolicy: IfNotPresent

service:
  type: ClusterIP
  port: 80

resources:
  requests:
    cpu: 250m
    memory: 256Mi
  limits:
    cpu: 500m
    memory: 512Mi

# values-prod.yaml - 生产环境覆盖
replicaCount: 5

image:
  tag: "3.1.0"
  pullPolicy: Always

resources:
  requests:
    cpu: 1000m
    memory: 1Gi
  limits:
    cpu: 2000m
    memory: 2Gi

ingress:
  enabled: true
  hosts:
    - host: app.example.com
      paths:
        - path: /
          pathType: Prefix

hpa:
  enabled: true
  minReplicas: 5
  maxReplicas: 20
  cpuUtilization: 70

# 部署时指定环境配置文件
# helm install my-app ./my-app -f values.yaml -f values-prod.yaml -n production

模板辅助函数与复用逻辑

# templates/_helpers.tpl
{{/* 生成完整资源名称 */}}
{{- define "my-app.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 "my-app.labels" -}}
helm.sh/chart: {{ include "my-app.chart" . }}
{{ include "my-app.selectorLabels" . }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}

{{/* 选择器标签 */}}
{{- define "my-app.selectorLabels" -}}
app.kubernetes.io/name: {{ include "my-app.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}

# templates/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "my-app.fullname" . }}-config
data:
  application.yaml: |
    server:
      port: 8080
    database:
      host: {{ .Values.database.host | quote }}
      port: {{ .Values.database.port }}
    {{- if .Values.featureFlags }}
    features:
    {{- range $key, $val := .Values.featureFlags }}
      {{ $key }}: {{ $val }}
    {{- end }}
    {{- end }}

Helm版本管理与一键回滚操作

# 安装Chart
helm install my-app ./my-app \
  -f values.yaml \
  -f values-prod.yaml \
  -n production

# 查看发布历史
helm history my-app -n production
# REVISION  STATUS     CHART         APP VERSION  DESCRIPTION
# 1         deployed   my-app-1.0.0  3.0.0       Install complete
# 2         deployed   my-app-1.1.0  3.1.0       Upgrade complete

# 升级
helm upgrade my-app ./my-app \
  -f values.yaml \
  -f values-prod.yaml \
  --set image.tag=3.1.1 \
  --set replicaCount=8 \
  -n production

# 回滚到指定版本
helm rollback my-app 2 -n production
# Rollback was a success!

# 回滚时指定超时
helm rollback my-app 1 -n production --timeout 5m --wait

# 查看某个Revision的配置值
helm get values my-app -n production --revision 2

# 查看渲染后的完整YAML(不实际部署)
helm template my-app ./my-app \
  -f values.yaml \
  -f values-prod.yaml \
  -n production > rendered.yaml

# dry-run验证升级效果
helm upgrade my-app ./my-app \
  -f values-prod.yaml \
  --set image.tag=3.2.0 \
  --dry-run -n production

Helm Chart测试与Lint校验

# 语法校验
helm lint ./my-app
# ==> Linting ./my-app
# [INFO] Chart.yaml: icon is recommended
# 1 chart(s) linted, 0 chart(s) failed

# 模板渲染校验
helm template my-app ./my-app -f values-prod.yaml | kubectl apply --dry-run=client -f -

# 添加测试模板
# templates/tests/test-connection.yaml
apiVersion: v1
kind: Pod
metadata:
  name: "{{ include "my-app.fullname" . }}-test"
  annotations:
    "helm.sh/hook": test
spec:
  restartPolicy: Never
  containers:
    - name: wget
      image: busybox
      command: ['wget']
      args:
        - '--spider'
        - '--timeout=10'
        - 'http://{{ include "my-app.fullname" . }}:{{ .Values.service.port }}/health'

# 执行测试
helm test my-app -n production

# Chart打包发布
helm package ./my-app
# 生成 my-app-1.2.3.tgz
helm repo add myrepo https://charts.example.com
helm push my-app-1.2.3.tgz myrepo

Helm Chart将Kubernetes应用配置从碎片化的YAML文件整合为可版本化管理的模板包。values.yaml分离配置与模板,同一Chart可部署到dev/staging/prod多个环境。回滚机制在发布故障时快速恢复,revision历史完整记录每次变更。生产环境建议配合CI/CD流水线自动执行lint、template、test校验后再触发upgrade,降低人为操作风险。

原创文章,作者:小编,如若转载,请注明出处:https://www.yunthe.com/helmchart-bao-guan-li-shi-zhan-kubernetes-ying-yong-mu-ban/

(0)
小编小编
上一篇 6小时前
下一篇 6小时前

相关推荐