You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Helm Chart中使用多容器?寻求最佳实践方案

关于Helm多容器Deployment的最佳实践处理方式

手动复制容器配置代码肯定不是最佳实践——重复代码会导致维护成本飙升,比如要改探针规则或资源限制时,得同步修改多处,很容易出错。下面是两种更标准的处理方式:

方式一:使用Helm模板片段(复用性强)

在Helm Chart的templates目录下创建_helpers.tpl文件,把通用容器配置抽离成可复用的模板片段:

{{- define "common.container" -}}
- name: {{ .name }}
  securityContext:
    {{- toYaml .securityContext | default toYaml .Values.global.securityContext | nindent 12 }}
  image: "{{ .image.repository }}:{{ .image.tag | default .Chart.AppVersion }}"
  imagePullPolicy: {{ .image.pullPolicy }}
  ports:
    - name: http
      containerPort: {{ .containerPort | default 80 }}
      protocol: TCP
  livenessProbe:
    httpGet:
      path: {{ .livenessProbe.path | default "/" }}
      port: http
  readinessProbe:
    httpGet:
      path: {{ .readinessProbe.path | default "/" }}
      port: http
  resources:
    {{- toYaml .resources | default toYaml .Values.global.resources | nindent 12 }}
{{- end -}}

然后在Deployment.yaml中直接调用这个模板,传入nginx和flask的专属配置:

containers:
  {{- include "common.container" (merge (dict "name" "nginx") .Values.nginx) | nindent 4 }}
  {{- include "common.container" (merge (dict "name" "flask") .Values.flask) | nindent 4 }}

如果不同容器有特殊配置(比如不同的端口),可以在values.yaml的对应容器节点下添加字段,模板里用default兜底通用值即可

方式二:将容器配置抽象为列表(灵活性高)

调整values.yaml的结构,把多容器定义成一个列表:

containers:
  - name: nginx
    image:
      repository: _ADDRESS_
      tag: stable
      pullPolicy: IfNotPresent
    containerPort: 80
    # 可添加该容器专属的探针、资源配置等
  - name: flask
    image:
      repository: _ADDRESS_
      tag: stable
      pullPolicy: IfNotPresent
    containerPort: 5000

接着在Deployment.yaml中通过range循环渲染所有容器:

containers:
{{- range .Values.containers }}
- name: {{ .name }}
  securityContext:
    {{- toYaml .securityContext | default toYaml $.Values.global.securityContext | nindent 12 }}
  image: "{{ .image.repository }}:{{ .image.tag | default $.Chart.AppVersion }}"
  imagePullPolicy: {{ .image.pullPolicy }}
  ports:
    - name: http
      containerPort: {{ .containerPort | default 80 }}
      protocol: TCP
  livenessProbe:
    httpGet:
      path: {{ .livenessProbe.path | default "/" }}
      port: http
  readinessProbe:
    httpGet:
      path: {{ .readinessProbe.path | default "/" }}
      port: http
  resources:
    {{- toYaml .resources | default toYaml $.Values.global.resources | nindent 12 }}
{{- end }}

这种方式适合需要动态增减容器的场景,后续加新容器只需要在values.yaml里追加配置,不用修改Deployment模板。

内容的提问来源于stack exchange,提问作者DougM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 15:27:23