【云原生与DevOps】04-Helm Chart开发实战:打包你的第一个应用

📅 2026/6/30 1:03:38
【云原生与DevOps】04-Helm Chart开发实战:打包你的第一个应用
专栏云原生 DevOps难度进阶标签HelmKubernetesChart模板应用打包前言手写一堆YAML维护很痛苦Helm 就是 Kubernetes 的包管理器。本文从零开发一个完整 Helm Chart掌握后可以直接用在生产。一、Helm 基础概念ChartHelm 的包包含一个应用的所有 Kubernetes 资源模板ReleaseChart 的一次部署实例Repository存储 Chart 的仓库Values部署时的配置参数覆盖默认值二、创建 Chart# 创建Chart骨架helm create myapp# 目录结构myapp/ ├── Chart.yaml# Chart元信息├── values.yaml# 默认配置值├── charts/# 依赖的子Chart└── templates/# 资源模板├── deployment.yaml ├── service.yaml ├── ingress.yaml ├── _helpers.tpl# 模板辅助函数├── hpa.yaml └── NOTES.txt# 部署后展示的说明三、编写 values.yaml# values.yamlreplicaCount:2image:repository:registry.example.com/myapptag:1.0.0pullPolicy:IfNotPresentservice:type:ClusterIPport:80targetPort:8080ingress:enabled:truehost:myapp.example.comtlsEnabled:falseresources:limits:cpu:1000mmemory:512Mirequests:cpu:250mmemory:128Miautoscaling:enabled:falseminReplicas:2maxReplicas:10targetCPUUtilizationPercentage:70env:DB_HOST:db.example.comLOG_LEVEL:info四、编写 templates/deployment.yamlapiVersion:apps/v1kind:Deploymentmetadata:name:{{include myapp.fullname .}}labels:{{-include myapp.labels .|nindent 4}}spec:{{-if not .Values.autoscaling.enabled}}replicas:{{.Values.replicaCount}}{{-end}}selector:matchLabels:{{-include myapp.selectorLabels .|nindent 6}}template:metadata:labels:{{-include myapp.selectorLabels .|nindent 8}}spec:containers:-name:{{.Chart.Name}}image:{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}imagePullPolicy:{{.Values.image.pullPolicy}}ports:-containerPort:{{.Values.service.targetPort}}env:{{-range $key,$val: .Values.env}}-name:{{$key}}value:{{$val|quote}}{{-end}}resources:{{-toYaml .Values.resources|nindent 12}}readinessProbe:httpGet:path:/healthport:{{.Values.service.targetPort}}initialDelaySeconds:10periodSeconds:5五、部署与管理# 检查模板渲染结果helm template myrelease ./myapp-fprod-values.yaml# 安装首次helminstallmyrelease ./myapp\--namespaceproduction\-fprod-values.yaml# 升级helm upgrade myrelease ./myapp\--namespaceproduction\-fprod-values.yaml\--setimage.tag1.1.0# 回滚helm rollback myrelease1# 回滚到第1个版本# 查看历史helmhistorymyrelease# 卸载helm uninstall myrelease-nproduction六、发布到 Helm 仓库# 打包Charthelm package ./myapp# 发布到 OCI 仓库推荐helm push myapp-1.0.0.tgz oci://registry.example.com/helm-charts# 安装时直接从仓库拉取helminstallmyrelease oci://registry.example.com/helm-charts/myapp--version1.0.0结语Helm 的核心价值是把部署参数化同一套 Chart 可以部署到 dev/staging/prod 不同环境只需要不同的 values 文件。