Bạn có 20 service, mỗi service 3 môi trường. Viết YAML thuần nghĩa là 60 bộ manifest gần giống nhau — và sửa một thói quen chung phải sửa 60 chỗ. Helm giải quyết việc đó bằng template cộng values: một chart dùng chung, mỗi service và mỗi môi trường chỉ khác file values.
Chín mục: vì sao Helm (1) → cấu trúc chart (2) → template và hàm (3) → values theo môi trường (4) → _helpers và library chart (5) → hooks (6) → một chart cho nhiều service (7) → lệnh và debug (8) → checklist (9).
| Vấn đề với YAML thuần | Helm giải quyết thế nào |
|---|---|
| 20 service × 3 môi trường = 60 bộ manifest gần giống nhau | Một chart dùng chung, 60 file values nhỏ. Sửa thói quen chung thì sửa một chỗ. |
| Sửa ConfigMap không làm pod restart | checksum/config sinh tự động từ hash của ConfigMap. |
| Không biết đang chạy phiên bản nào, rollback bằng tay | helm history và helm rollback — có bản ghi từng lần release. |
| Migration DB phải chạy tay trước khi deploy | hooks với pre-upgrade chạy Job và chờ xong mới tiếp. |
| Thiếu một giá trị cấu hình thì phát hiện lúc chạy | values.schema.json và required — fail ngay lúc render. |
| Cài Prometheus, cert-manager, ingress controller bằng tay | Chart công khai, cài một lệnh, phiên bản khai báo được trong Git. |
| Helm | Kustomize | |
|---|---|---|
| Cách hoạt động | Template Go rồi render thành YAML | Lấy YAML gốc rồi áp patch lên (overlay) |
| Điểm mạnh | Logic phức tạp, vòng lặp, điều kiện; đóng gói và phân phối được; có hooks và versioning | Không có template nên YAML luôn là YAML hợp lệ, dễ đọc; không cần học cú pháp mới |
| Điểm yếu | Template Go khó đọc khi phức tạp; lỗi thụt lề khó debug | Không có vòng lặp, không có hàm; chia sẻ giữa nhiều repo kém; không có hooks |
| Phù hợp khi | Nhiều service cấu trúc giống nhau; cần phân phối chart; cần hooks | Ít biến thể, muốn giữ YAML đơn giản và minh bạch |
| Ngộ nhận | Thực tế |
|---|---|
| "Helm quản lý trạng thái cluster" | Helm chỉ render YAML rồi gọi API server. Trạng thái mong muốn vẫn do controller Kubernetes thực
thi. Nếu ai đó sửa bằng kubectl, Helm không biết và không sửa lại — đó là việc
của ArgoCD. |
| "Helm là công cụ deploy liên tục" | helm upgrade là một lệnh thủ công. GitOps cần một controller liên tục so Git với
cluster. Xem chặng 07. |
"helm rollback là đủ để quay lui" |
Nó quay lui manifest, nhưng không quay lui schema database hay dữ liệu đã bị migration thay đổi. Rollback an toàn cần migration tương thích ngược. |
| "Chart công khai thì dùng là an toàn" | Chart bên thứ ba chạy template tuỳ ý và có thể tạo ClusterRole rộng. Luôn
helm template để đọc trước khi cài vào production. |
replicas bằng kubectl scale trên release do Helm quản lý. Helm làm gì?order-service/
├── Chart.yaml # metadata: tên, phiên bản, dependency
├── Chart.lock # phiên bản dependency đã khoá (COMMIT file này)
├── values.yaml # giá trị mặc định — tài liệu sống của chart
├── values.schema.json # schema kiểm tra values, fail sớm nếu sai
├── .helmignore # file không đóng gói vào chart
├── README.md # tài liệu tham số
├── charts/ # subchart (dependency đã tải về)
├── crds/ # CustomResourceDefinition, cài TRƯỚC mọi thứ khác
└── templates/
├── _helpers.tpl # hàm dùng lại: tên, label, selector
├── NOTES.txt # thông báo in ra sau khi install thành công
├── deployment.yaml
├── service.yaml
├── ingress.yaml
├── configmap.yaml
├── externalsecret.yaml
├── serviceaccount.yaml
├── hpa.yaml
├── scaledobject.yaml
├── pdb.yaml
├── networkpolicy.yaml
├── servicemonitor.yaml
├── job-migration.yaml # hook pre-upgrade
└── tests/
└── test-connection.yaml # chạy bằng helm test
Chart.yamlapiVersion: v2
name: order-service
description: Order processing service
type: application
# version: phiên bản CHART (template). Tăng khi sửa template.
version: 1.4.2
# appVersion: phiên bản ỨNG DỤNG. Thường là image tag.
appVersion: "a3f8c21"
kubeVersion: ">=1.28.0-0"
keywords: [order, api]
home: https://github.com/myorg/order-service
maintainers:
- name: Platform Team
email: platform@example.com
dependencies:
- name: common
version: "1.2.0"
repository: "oci://123456789012.dkr.ecr.ap-southeast-1.amazonaws.com/charts"
- name: redis
version: "20.x.x"
repository: "https://charts.bitnami.com/bitnami"
condition: redis.enabled # chỉ cài khi values bật
tags: [cache]
version và appVersion: sửa template (thêm một probe) thì
tăng version. Deploy code mới thì đổi appVersion và
image.tag. Hai thứ này độc lập — một chart version có thể deploy nhiều app version, và
ngược lại.
values.yaml — vừa là cấu hình, vừa là tài liệu# -- Số replica khi không bật autoscaling
replicaCount: 3
image:
repository: 123456789012.dkr.ecr.ap-southeast-1.amazonaws.com/order-service
pullPolicy: IfNotPresent
# -- Tag ảnh. ĐỂ TRỐNG để dùng Chart.appVersion. CI sẽ ghi git SHA vào đây.
tag: ""
imagePullSecrets: []
nameOverride: ""
fullnameOverride: ""
serviceAccount:
create: true
# -- Annotation cho ServiceAccount. Dùng để gắn IAM role qua IRSA.
annotations: {}
# eks.amazonaws.com/role-arn: arn:aws:iam::123456789012:role/prod-order-service
name: ""
podAnnotations: {}
podLabels: {}
podSecurityContext:
runAsNonRoot: true
runAsUser: 10001
runAsGroup: 10001
fsGroup: 10001
seccompProfile:
type: RuntimeDefault
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
service:
type: ClusterIP
port: 8080
ingress:
enabled: false
className: alb
annotations: {}
hosts: []
tls: []
resources:
requests:
cpu: 200m
memory: 2560Mi
limits:
cpu: 2000m
memory: 3584Mi
# -- Cấu hình probe. Đường dẫn khác nhau giữa các runtime.
probes:
startup:
enabled: true
path: /actuator/health/readiness
periodSeconds: 2
failureThreshold: 60
liveness:
enabled: true
path: /actuator/health/liveness
periodSeconds: 10
timeoutSeconds: 3
failureThreshold: 3
readiness:
enabled: true
path: /actuator/health/readiness
periodSeconds: 5
timeoutSeconds: 3
failureThreshold: 2
lifecycle:
# -- Đệm để ALB kịp gỡ pod khỏi backend trước khi app từ chối request
preStopSleepSeconds: 5
terminationGracePeriodSeconds: 45
autoscaling:
enabled: true
minReplicas: 3
maxReplicas: 20
# -- Dùng KEDA thay HPA để scale theo tín hiệu nghiệp vụ
keda:
enabled: false
triggers: []
targetCPUUtilizationPercentage: 70
# -- KHÔNG đặt targetMemory cho app Java/.NET: working set là hàm của cấu hình
# runtime, không phải của tải, nên trigger này không bao giờ thoả mãn được.
podDisruptionBudget:
enabled: true
# -- PHẢI nhỏ hơn replicaCount, nếu không sẽ chặn drain node và cluster upgrade
minAvailable: 2
topologySpread:
enabled: true
# -- Biến môi trường thường, vào ConfigMap
env:
LOG_LEVEL: INFO
SPRING_PROFILES_ACTIVE: prod
# -- Secret lấy từ AWS Secrets Manager qua External Secrets Operator
externalSecrets:
enabled: true
secretStoreRef: aws-secrets-manager
refreshInterval: 1h
remoteRefs: []
# -- Cấu hình JVM. Ghi đè toàn bộ cho từng môi trường.
javaOpts: >-
-XX:+UseContainerSupport
-XX:MaxRAMPercentage=70.0
-XX:+ExitOnOutOfMemoryError
-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=/dump
migration:
enabled: false
# -- Lệnh chạy migration. Chạy như Helm hook pre-upgrade.
command: []
serviceMonitor:
enabled: true
path: /actuator/prometheus
interval: 30s
networkPolicy:
enabled: true
allowedIngressApps: []
allowedEgressPorts: [5432, 6379, 443]
nodeSelector: {}
tolerations: []
affinity: {}
# -- không phải tuỳ ý: helm-docs đọc chúng để sinh
README.md tự động với bảng tham số. Chạy helm-docs trong CI để tài liệu
không bao giờ lệch với values.yaml.
values.schema.json — chặn lỗi trước khi render{
"$schema": "https://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["image", "resources"],
"properties": {
"replicaCount": { "type": "integer", "minimum": 1 },
"image": {
"type": "object",
"required": ["repository"],
"properties": {
"repository": { "type": "string", "minLength": 1 },
"tag": { "type": "string" },
"pullPolicy": { "enum": ["Always", "IfNotPresent", "Never"] }
}
},
"resources": {
"type": "object",
"required": ["requests", "limits"],
"properties": {
"requests": {
"type": "object",
"required": ["cpu", "memory"],
"properties": {
"cpu": { "type": ["string","number"] },
"memory": { "type": "string", "pattern": "^[0-9]+(Mi|Gi)$" }
}
},
"limits": {
"type": "object",
"required": ["cpu", "memory"],
"properties": {
"cpu": { "type": ["string","number"] },
"memory": { "type": "string", "pattern": "^[0-9]+(Mi|Gi)$" }
}
}
}
},
"autoscaling": {
"type": "object",
"properties": {
"enabled": { "type": "boolean" },
"minReplicas": { "type": "integer", "minimum": 1 },
"maxReplicas": { "type": "integer", "minimum": 1 }
}
}
}
}
Helm kiểm schema này ở mỗi lần template, install,
upgrade và lint. Sai kiểu dữ liệu hoặc thiếu field bắt buộc thì fail ngay
với thông báo rõ ràng, thay vì tạo ra manifest sai rồi lỗi trên cluster.
Helm dùng template Go cộng thư viện Sprig. Mục này là phần cú pháp bạn sẽ dùng 95% thời gian, kèm những bẫy thụt lề hay gây lỗi.
| Đối tượng | Chứa gì |
|---|---|
.Values | Nội dung values.yaml đã gộp với -f và --set. |
.Release | .Name, .Namespace, .Revision,
.IsInstall, .IsUpgrade, .Service. |
.Chart | Nội dung Chart.yaml: .Name,
.Version, .AppVersion. |
.Capabilities | Thông tin cluster: .KubeVersion,
.APIVersions.Has "autoscaling/v2". |
# --- Giá trị và mặc định ---
{{ .Values.image.repository }}
{{ .Values.image.tag | default .Chart.AppVersion }}
{{ .Values.replicaCount | default 1 }}
{{ required "image.repository là bắt buộc" .Values.image.repository }}
# --- Dấu gạch: KIỂM SOÁT KHOẢNG TRẮNG ---
{{- /* gạch bên trái: xoá whitespace và newline TRƯỚC */ -}}
{{- .Values.x }} # xoá trước
{{ .Values.x -}} # xoá sau
{{- .Values.x -}} # xoá cả hai
# --- Điều kiện ---
{{- if .Values.ingress.enabled }}
...
{{- else if .Values.service.external }}
...
{{- end }}
{{- if and .Values.autoscaling.enabled (not .Values.autoscaling.keda.enabled) }}
{{- if or .Values.a .Values.b }}
{{- if eq .Values.service.type "LoadBalancer" }}
{{- if gt (int .Values.replicaCount) 1 }}
# --- Vòng lặp ---
{{- range $key, $value := .Values.env }}
- name: {{ $key }}
value: {{ $value | quote }}
{{- end }}
{{- range .Values.ingress.hosts }}
- host: {{ .host | quote }} # trong range, "." là phần tử hiện tại
{{- end }}
# Cần truy cập .Values bên trong range → lưu scope gốc vào biến
{{- $root := . }}
{{- range .Values.items }}
image: {{ $root.Values.image.repository }}:{{ .tag }}
{{- end }}
# --- Chèn khối YAML ---
resources:
{{- toYaml .Values.resources | nindent 2 }}
# toYaml → chuyển map/list thành YAML
# nindent → thêm newline rồi thụt N dấu cách (dùng cái này)
# indent → chỉ thụt, KHÔNG thêm newline
# SAI — toYaml không tự thụt lề, YAML kết quả không hợp lệ
resources:
{{ toYaml .Values.resources }}
# SAI — indent không thêm newline nên dòng đầu dính vào "resources:"
resources: {{ toYaml .Values.resources | indent 2 }}
# ĐÚNG — nindent thêm newline rồi thụt 2 dấu cách
resources:
{{- toYaml .Values.resources | nindent 2 }}
Quy tắc: hầu như luôn dùng nindent, và luôn kiểm bằng
helm template trước khi commit.
# --- Chuỗi ---
{{ .Values.name | upper | quote }}
{{ .Values.name | trunc 63 | trimSuffix "-" }} # giới hạn 63 ký tự của label K8s
{{ printf "%s-%s" .Release.Name .Chart.Name }}
{{ .Values.host | replace "." "-" }}
{{ contains "prod" .Release.Namespace }}
{{ .Values.path | trimPrefix "/" }}
# --- Số và đơn vị ---
{{ int .Values.port }}
{{ .Values.resources.limits.memory | trimSuffix "Mi" | int }}
{{ div (mul (int .Values.memMi) 70) 100 }} # 70% của memMi
# --- Mã hoá ---
{{ .Values.password | b64enc }}
{{ .Values.config | toYaml | sha256sum | trunc 16 }}
{{ .Values.data | toJson }}
# --- Map và list ---
{{ keys .Values.env | sortAlpha }}
{{ .Values.list | join "," }}
{{ .Values.list | first }} / {{ .Values.list | last }}
{{ len .Values.list }}
{{ dig "a" "b" "default" .Values }} # truy cập lồng an toàn
# --- Gộp map (quan trọng cho values theo môi trường) ---
{{ $merged := merge .Values.override .Values.base }} # override THẮNG base
{{ $deep := mergeOverwrite (deepCopy .Values.base) .Values.override }}
# --- Đọc file trong chart ---
{{ .Files.Get "config/application.yaml" | nindent 4 }}
{{ (.Files.Glob "config/*.yaml").AsConfig | nindent 2 }}
# --- Kiểm tra API có sẵn trên cluster ---
{{- if .Capabilities.APIVersions.Has "keda.sh/v1alpha1" }}
...
{{- end }}
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "app.fullname" . }}
labels:
{{- include "app.labels" . | nindent 4 }}
spec:
{{- if not (or .Values.autoscaling.enabled .Values.autoscaling.keda.enabled) }}
replicas: {{ .Values.replicaCount }}
{{- end }}
revisionHistoryLimit: {{ .Values.revisionHistoryLimit | default 5 }}
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: {{ .Values.strategy.maxSurge | default 1 }}
maxUnavailable: {{ .Values.strategy.maxUnavailable | default 0 }}
selector:
matchLabels:
{{- include "app.selectorLabels" . | nindent 6 }}
template:
metadata:
annotations:
# Làm pod template đổi khi config đổi → kích hoạt rolling update
checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}
{{- with .Values.podAnnotations }}
{{- toYaml . | nindent 8 }}
{{- end }}
labels:
{{- include "app.selectorLabels" . | nindent 8 }}
{{- with .Values.podLabels }}
{{- toYaml . | nindent 8 }}
{{- end }}
spec:
serviceAccountName: {{ include "app.serviceAccountName" . }}
automountServiceAccountToken: {{ .Values.automountServiceAccountToken | default false }}
terminationGracePeriodSeconds: {{ .Values.terminationGracePeriodSeconds }}
securityContext:
{{- toYaml .Values.podSecurityContext | nindent 8 }}
{{- with .Values.imagePullSecrets }}
imagePullSecrets:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- if .Values.topologySpread.enabled }}
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
{{- include "app.selectorLabels" . | nindent 14 }}
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels:
{{- include "app.selectorLabels" . | nindent 14 }}
{{- end }}
containers:
- name: {{ .Chart.Name }}
image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
ports:
- name: http
containerPort: {{ .Values.service.port }}
protocol: TCP
envFrom:
- configMapRef:
name: {{ include "app.fullname" . }}
{{- if .Values.externalSecrets.enabled }}
- secretRef:
name: {{ include "app.fullname" . }}
{{- end }}
env:
- name: POD_NAME
valueFrom: { fieldRef: { fieldPath: metadata.name } }
- name: POD_NAMESPACE
valueFrom: { fieldRef: { fieldPath: metadata.namespace } }
# Cho app tự đọc limit của chính nó — giải quyết bẫy cgroup của Python
- name: CPU_LIMIT
valueFrom:
resourceFieldRef:
containerName: {{ .Chart.Name }}
resource: limits.cpu
{{- with .Values.javaOpts }}
- name: JAVA_TOOL_OPTIONS
value: {{ . | quote }}
{{- end }}
resources:
{{- toYaml .Values.resources | nindent 12 }}
{{- if .Values.probes.startup.enabled }}
startupProbe:
httpGet:
path: {{ .Values.probes.startup.path }}
port: http
periodSeconds: {{ .Values.probes.startup.periodSeconds }}
failureThreshold: {{ .Values.probes.startup.failureThreshold }}
{{- end }}
{{- if .Values.probes.liveness.enabled }}
livenessProbe:
httpGet:
path: {{ .Values.probes.liveness.path }}
port: http
periodSeconds: {{ .Values.probes.liveness.periodSeconds }}
timeoutSeconds: {{ .Values.probes.liveness.timeoutSeconds }}
failureThreshold: {{ .Values.probes.liveness.failureThreshold }}
{{- end }}
{{- if .Values.probes.readiness.enabled }}
readinessProbe:
httpGet:
path: {{ .Values.probes.readiness.path }}
port: http
periodSeconds: {{ .Values.probes.readiness.periodSeconds }}
timeoutSeconds: {{ .Values.probes.readiness.timeoutSeconds }}
failureThreshold: {{ .Values.probes.readiness.failureThreshold }}
{{- end }}
{{- if .Values.lifecycle.preStopSleepSeconds }}
lifecycle:
preStop:
exec:
command: ["sh", "-c", "sleep {{ .Values.lifecycle.preStopSleepSeconds }}"]
{{- end }}
securityContext:
{{- toYaml .Values.securityContext | nindent 12 }}
volumeMounts:
- { name: tmp, mountPath: /tmp }
- { name: dump, mountPath: /dump }
{{- with .Values.extraVolumeMounts }}
{{- toYaml . | nindent 12 }}
{{- end }}
volumes:
- name: tmp
emptyDir: {}
- name: dump
emptyDir:
sizeLimit: {{ .Values.dumpVolumeSize | default "4Gi" }}
{{- with .Values.extraVolumes }}
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.tolerations }}
tolerations:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.affinity }}
affinity:
{{- toYaml . | nindent 8 }}
{{- end }}
with làm hai việc cùng lúc: kiểm tra giá trị có tồn tại và không rỗng, đồng thời
đổi scope . thành giá trị đó. Nó gọn hơn if cho trường hợp "chỉ render khi có
giá trị":
# Dài
{{- if .Values.nodeSelector }}
nodeSelector:
{{- toYaml .Values.nodeSelector | nindent 2 }}
{{- end }}
# Gọn, tương đương
{{- with .Values.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 2 }}
{{- end }}
Nhớ: bên trong with, muốn dùng .Values thì phải lưu scope gốc trước
({{- $root := . }}) hoặc dùng $.
indent 4 và nindent 4?Đây là lý do chính người ta dùng Helm. Một chart, nhiều file values — và chỉ những thứ thực sự khác nhau được khai lại.
deploy/
├── chart/ # chart dùng chung (hoặc tham chiếu chart ở repo khác)
│ ├── Chart.yaml
│ ├── values.yaml # MẶC ĐỊNH: giá trị an toàn nhất, thường là của dev
│ └── templates/
└── envs/
├── dev/values.yaml
├── staging/values.yaml
└── prod/
├── values.yaml # cấu hình chung của prod
├── values-apse1.yaml # riêng cho region ap-southeast-1
└── values-use1.yaml # riêng cho region us-east-1
# Thứ tự ưu tiên: file sau GHI ĐÈ file trước, --set thắng tất cả
helm upgrade --install order-service ./chart \
-f ./chart/values.yaml \
-f ./envs/prod/values.yaml \
-f ./envs/prod/values-apse1.yaml \
--set image.tag=a3f8c21 \
-n prod
replicaCount: 1
resources:
requests: { cpu: 100m, memory: 512Mi }
limits: { cpu: 1000m, memory: 1Gi }
javaOpts: >-
-XX:+UseContainerSupport
-XX:MaxRAMPercentage=70.0
-XX:+ExitOnOutOfMemoryError
autoscaling:
enabled: false
podDisruptionBudget:
enabled: false # 1 replica thì PDB vô nghĩa
topologySpread:
enabled: false # cluster dev thường 1 AZ
networkPolicy:
enabled: false # giảm ma sát khi phát triển
env:
LOG_LEVEL: DEBUG
SPRING_PROFILES_ACTIVE: dev
ingress:
enabled: true
className: alb
annotations:
alb.ingress.kubernetes.io/scheme: internal
alb.ingress.kubernetes.io/group.name: dev-shared
hosts:
- host: order-dev.internal.example.com
paths: [{ path: /, pathType: Prefix }]
replicaCount: 3
image:
pullPolicy: IfNotPresent # tag bất biến nên không cần Always
# Tính theo công thức: limits.memory = (Xmx + ngoài heap) × 1,15
# Xmx = 70% × 3584Mi ≈ 2508Mi, ngoài heap ≈ 655Mi
resources:
requests: { cpu: 200m, memory: 2816Mi }
limits: { cpu: 2000m, memory: 3584Mi }
javaOpts: >-
-XX:+UseContainerSupport
-XX:MaxRAMPercentage=70.0
-XX:MaxMetaspaceSize=384m
-XX:ReservedCodeCacheSize=256m
-XX:MaxDirectMemorySize=128m
-XX:+UseG1GC
-XX:MaxGCPauseMillis=200
-XX:+ExitOnOutOfMemoryError
-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=/dump
-XX:NativeMemoryTracking=summary
autoscaling:
enabled: true
minReplicas: 3
maxReplicas: 20
# requests.cpu 200m suy ngược từ: P95 120m ÷ 70% × 1,15 ≈ 197m
targetCPUUtilizationPercentage: 70
# KHÔNG đặt memory trigger — xem chặng 04 mục 6
podDisruptionBudget:
enabled: true
minAvailable: 2 # < replicaCount 3
topologySpread:
enabled: true
terminationGracePeriodSeconds: 45
lifecycle:
preStopSleepSeconds: 5
serviceAccount:
create: true
annotations:
eks.amazonaws.com/role-arn: arn:aws:iam::123456789012:role/prod-order-service
env:
LOG_LEVEL: INFO
SPRING_PROFILES_ACTIVE: prod
OTEL_TRACES_SAMPLER_ARG: "0.1"
externalSecrets:
enabled: true
secretStoreRef: aws-secrets-manager
refreshInterval: 1h
remoteRefs:
- secretKey: SPRING_DATASOURCE_PASSWORD
remoteRef:
key: prod/order-service/db
property: password
- secretKey: SPRING_DATASOURCE_USERNAME
remoteRef:
key: prod/order-service/db
property: username
ingress:
enabled: true
className: alb
annotations:
alb.ingress.kubernetes.io/scheme: internet-facing
alb.ingress.kubernetes.io/target-type: ip
alb.ingress.kubernetes.io/group.name: prod-shared
alb.ingress.kubernetes.io/certificate-arn: arn:aws:acm:ap-southeast-1:123456789012:certificate/abc
alb.ingress.kubernetes.io/ssl-redirect: "443"
alb.ingress.kubernetes.io/healthcheck-path: /actuator/health/readiness
# deregistration_delay >= preStop + thời gian xử lý request
alb.ingress.kubernetes.io/target-group-attributes: deregistration_delay.timeout_seconds=30
alb.ingress.kubernetes.io/load-balancer-attributes: idle_timeout.timeout_seconds=60
hosts:
- host: api.example.com
paths: [{ path: /orders, pathType: Prefix }]
networkPolicy:
enabled: true
allowedIngressApps: [api-gateway]
allowedEgressPorts: [5432, 6379, 443]
migration:
enabled: true
command: ["java", "-jar", "/app/app.jar", "--spring.flyway.migrate-only=true"]
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: karpenter.sh/capacity-type
operator: In
values: ["on-demand"] # service quan trọng: không dùng spot
# values.yaml
tolerations:
- key: a
operator: Exists
# envs/prod/values.yaml
tolerations:
- key: b
operator: Exists
# Kết quả: CHỈ còn key b. Phần tử "a" MẤT HOÀN TOÀN.
Map thì gộp theo từng key (deep merge), nhưng list bị ghi đè nguyên khối. Hệ quả thực tế: nếu
bạn muốn "thêm" một toleration ở prod, bạn phải khai lại cả danh sách. Cách thiết kế tránh
được: tách thành tolerations (cơ bản) và extraTolerations (thêm), rồi
concat trong template.
# values.yaml
env:
LOG_LEVEL: INFO
extraEnv: []
# template
env:
{{- range $k, $v := .Values.env }}
- name: {{ $k }}
value: {{ $v | quote }}
{{- end }}
{{- with .Values.extraEnv }}
{{- toYaml . | nindent 2 }}
{{- end }}
Môi trường nào cần thêm biến thì dùng extraEnv, không phải khai lại toàn bộ
env. Áp dụng mẫu này cho mọi list: extraVolumes,
extraVolumeMounts, extraTolerations.
# Xem values đã gộp (không render template) — kiểm xem file nào ghi đè cái gì
helm template order-service ./chart \
-f ./envs/prod/values.yaml \
--show-only templates/deployment.yaml
# Xem toàn bộ values sau khi gộp
helm show values ./chart > defaults.yaml
helm get values order-service -n prod # values đã dùng cho release đang chạy
helm get values order-service -n prod --all # kể cả giá trị mặc định
# So manifest giữa hai bộ values — rất hữu ích khi review PR
diff <(helm template app ./chart -f envs/staging/values.yaml) \
<(helm template app ./chart -f envs/prod/values.yaml)
values.yaml có tolerations gồm 2 phần tử, values-prod.yaml khai 1 phần tử khác. Kết quả?_helpers.tpl và library chartFile bắt đầu bằng dấu gạch dưới không được render thành manifest. Chúng chứa các hàm dùng lại — nơi đặt logic đặt tên và gắn label.
_helpers.tpl chuẩn{{/*
Tên ngắn của chart. Giới hạn 63 ký tự vì đó là trần của label Kubernetes.
*/}}
{{- define "app.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
{{- end }}
{{/*
Tên đầy đủ, dùng cho tên của hầu hết đối tượng.
Nếu release name đã chứa tên chart thì không nối lặp lại.
*/}}
{{- define "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 }}
{{/*
Label đầy đủ — gắn vào metadata.labels của mọi đối tượng.
*/}}
{{- define "app.labels" -}}
helm.sh/chart: {{ printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
{{ include "app.selectorLabels" . }}
{{- if .Chart.AppVersion }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
app.kubernetes.io/part-of: {{ .Values.partOf | default .Chart.Name }}
{{- end }}
{{/*
Selector label — BẤT BIẾN sau khi tạo Deployment.
TUYỆT ĐỐI không thêm version vào đây: selector của Deployment là immutable,
thay đổi sẽ làm helm upgrade thất bại và phải xoá Deployment để sửa.
*/}}
{{- define "app.selectorLabels" -}}
app.kubernetes.io/name: {{ include "app.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
{{- define "app.serviceAccountName" -}}
{{- if .Values.serviceAccount.create }}
{{- default (include "app.fullname" .) .Values.serviceAccount.name }}
{{- else }}
{{- default "default" .Values.serviceAccount.name }}
{{- end }}
{{- end }}
{{/*
Tính Xmx từ limits.memory. Dùng khi muốn đặt -Xmx tường minh
thay vì để MaxRAMPercentage tự tính.
*/}}
{{- define "app.computedXmx" -}}
{{- $limitMi := .Values.resources.limits.memory | trimSuffix "Mi" | int -}}
{{- $offHeap := .Values.jvm.offHeapReserveMi | default 700 | int -}}
{{- $xmx := sub $limitMi $offHeap -}}
{{- if lt $xmx 256 -}}
{{- fail (printf "limits.memory %dMi quá nhỏ: sau khi trừ %dMi ngoài heap chỉ còn %dMi cho heap" $limitMi $offHeap $xmx) -}}
{{- end -}}
{{- printf "%dm" $xmx -}}
{{- end }}
{{/*
Kiểm tra tính nhất quán của cấu hình. Gọi hàm này ở đầu deployment.yaml
để fail sớm thay vì deploy ra cấu hình sai.
*/}}
{{- define "app.validate" -}}
{{- if and .Values.podDisruptionBudget.enabled (not .Values.autoscaling.enabled) }}
{{- if ge (int .Values.podDisruptionBudget.minAvailable) (int .Values.replicaCount) }}
{{- fail (printf "podDisruptionBudget.minAvailable (%v) phải NHỎ HƠN replicaCount (%v), nếu không sẽ chặn hoàn toàn việc drain node" .Values.podDisruptionBudget.minAvailable .Values.replicaCount) }}
{{- end }}
{{- end }}
{{- if and .Values.autoscaling.enabled .Values.autoscaling.keda.enabled }}
{{- fail "Không bật đồng thời autoscaling.enabled (HPA) và autoscaling.keda.enabled — hai cái sẽ tranh nhau điều khiển replicas" }}
{{- end }}
{{- $graceP := int .Values.terminationGracePeriodSeconds }}
{{- $preStop := int (.Values.lifecycle.preStopSleepSeconds | default 0) }}
{{- if le $graceP $preStop }}
{{- fail (printf "terminationGracePeriodSeconds (%d) phải lớn hơn preStopSleepSeconds (%d) cộng thời gian app cần để shutdown" $graceP $preStop) }}
{{- end }}
{{- end }}
app.selectorLabels:
Error: UPGRADE FAILED: cannot patch "order-service" with kind Deployment:
Deployment.apps "order-service" is invalid: spec.selector: Invalid value:
field is immutable
Khi gặp lỗi này, cách duy nhất là xoá Deployment rồi tạo lại — tức là có downtime. Đây là lý do
selectorLabels chỉ chứa name và instance, còn
version nằm ở app.labels (chỉ dùng cho metadata, không dùng cho selector).
fail là công cụ bị dùng ít hơn mức nó đáng. Nó chặn cấu hình sai ngay lúc
render, trước khi có gì tới được cluster. Những thứ đáng kiểm bằng fail:
minAvailable ≥ replicaCount → chặn drain nodeterminationGracePeriodSeconds ≤ preStop → app luôn bị SIGKILLlimits.memory quá nhỏ so với nhu cầu heapimage.tag là latestLibrary chart (type: library) chỉ chứa template, không render gì. Các chart
khác khai nó làm dependency rồi gọi các hàm bên trong. Đây là cách giữ 20 service dùng chung một chuẩn.
apiVersion: v2
name: common
description: Template dùng chung cho mọi service
type: library # KHÔNG phải application
version: 1.2.0
{{- define "common.deployment" -}}
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "app.fullname" . }}
labels:
{{- include "app.labels" . | nindent 4 }}
spec:
{{- if not .Values.autoscaling.enabled }}
replicas: {{ .Values.replicaCount }}
{{- end }}
selector:
matchLabels:
{{- include "app.selectorLabels" . | nindent 6 }}
template:
metadata:
labels:
{{- include "app.selectorLabels" . | nindent 8 }}
spec:
terminationGracePeriodSeconds: {{ .Values.terminationGracePeriodSeconds }}
securityContext:
{{- toYaml .Values.podSecurityContext | nindent 8 }}
containers:
- name: {{ .Chart.Name }}
image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
resources:
{{- toYaml .Values.resources | nindent 12 }}
{{- /* Cho phép chart con chèn thêm phần riêng của nó */}}
{{- if .Values.containerExtra }}
{{- toYaml .Values.containerExtra | nindent 10 }}
{{- end }}
{{- end }}
{{- include "common.validate" . }}
{{ include "common.deployment" . }}
# Đóng gói và đẩy library chart lên ECR (ECR hỗ trợ OCI registry cho Helm)
aws ecr create-repository --repository-name charts/common
helm package ./common
aws ecr get-login-password --region ap-southeast-1 \
| helm registry login --username AWS --password-stdin \
123456789012.dkr.ecr.ap-southeast-1.amazonaws.com
helm push common-1.2.0.tgz \
oci://123456789012.dkr.ecr.ap-southeast-1.amazonaws.com/charts
# Trong chart con: khai dependency rồi tải về
helm dependency update ./order-service
# Lệnh trên sinh Chart.lock và tải vào charts/ — COMMIT Chart.lock vào Git
# để mọi người và CI dùng đúng cùng một phiên bản.
version: "1.2.0") thay vì dùng dải ("1.x.x") cho môi trường production.
app.kubernetes.io/version vào selectorLabels?Hook là đối tượng Kubernetes có annotation đặc biệt, được Helm áp dụng vào đúng thời điểm trong vòng đời release. Dùng chủ yếu cho migration database.
helm install:
pre-install → [tạo manifest] → post-install
helm upgrade:
pre-upgrade → [cập nhật manifest] → post-upgrade
helm rollback:
pre-rollback → [quay lui manifest] → post-rollback
helm uninstall:
pre-delete → [xoá manifest] → post-delete
helm test:
test
{{- if .Values.migration.enabled }}
apiVersion: batch/v1
kind: Job
metadata:
# Tên có revision để mỗi lần upgrade là một Job mới, giữ được log của lần trước
name: {{ include "app.fullname" . }}-migration-{{ .Release.Revision }}
labels:
{{- include "app.labels" . | nindent 4 }}
annotations:
"helm.sh/hook": pre-install,pre-upgrade
"helm.sh/hook-weight": "-5" # số nhỏ chạy trước
# Giữ Job thất bại để đọc log; Job thành công thì xoá
"helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
spec:
backoffLimit: 2
activeDeadlineSeconds: 600 # cắt sau 10 phút để không treo deploy mãi
ttlSecondsAfterFinished: 3600
template:
metadata:
labels:
{{- include "app.selectorLabels" . | nindent 8 }}
job: migration
spec:
restartPolicy: Never
serviceAccountName: {{ include "app.serviceAccountName" . }}
securityContext:
{{- toYaml .Values.podSecurityContext | nindent 8 }}
containers:
- name: migration
# DÙNG CÙNG IMAGE với app — đảm bảo schema khớp với code
image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
command: {{ toYaml .Values.migration.command | nindent 12 }}
envFrom:
- configMapRef: { name: {{ include "app.fullname" . }} }
- secretRef: { name: {{ include "app.fullname" . }} }
resources:
{{- toYaml (.Values.migration.resources | default .Values.resources) | nindent 12 }}
securityContext:
{{- toYaml .Values.securityContext | nindent 12 }}
volumeMounts:
- { name: tmp, mountPath: /tmp }
volumes:
- name: tmp
emptyDir: {}
{{- end }}
hook-delete-policy — chọn đúng rất quan trọng| Policy | Hành vi |
|---|---|
before-hook-creation |
Xoá hook cũ cùng tên trước khi tạo mới. Cần có, nếu không lần upgrade thứ hai sẽ lỗi "Job đã tồn tại" (Job có field bất biến). |
hook-succeeded |
Xoá Job sau khi thành công. Giữ cluster sạch. |
hook-failed |
Xoá cả khi thất bại. Thường KHÔNG nên dùng — bạn sẽ mất log của lần migration lỗi, đúng lúc cần nó nhất. |
before-hook-creation,hook-succeeded. Job thành công thì tự dọn, Job
thất bại thì giữ lại để bạn đọc kubectl logs job/...-migration-7 và biết vì sao.
SAI — đổi tên cột trong một lần deploy:
ALTER TABLE orders RENAME COLUMN amount TO total_amount;
→ pod phiên bản cũ vẫn SELECT amount → lỗi ngay lập tức
→ và nếu rollback, pod cũ lên lại vẫn lỗi vì schema đã đổi
ĐÚNG — tách thành ba lần deploy:
Deploy 1: ALTER TABLE orders ADD COLUMN total_amount numeric;
code mới ghi CẢ HAI cột, đọc amount
Deploy 2: backfill total_amount từ amount
code mới đọc total_amount, vẫn ghi cả hai
Deploy 3: ALTER TABLE orders DROP COLUMN amount;
code chỉ dùng total_amount
Chậm hơn, nhưng mỗi bước rollback được an toàn. Đây là cái giá của zero-downtime deploy.
# 1. post-install: tạo dữ liệu seed cho môi trường mới
"helm.sh/hook": post-install
"helm.sh/hook-weight": "5"
# 2. pre-delete: dọn tài nguyên ngoài cluster trước khi xoá release
"helm.sh/hook": pre-delete
# Ví dụ: hủy đăng ký khỏi service registry, xoá DNS record
# 3. test: kiểm tra sau khi deploy, chạy bằng `helm test`
"helm.sh/hook": test
"helm.sh/hook-delete-policy": hook-succeeded
apiVersion: v1
kind: Pod
metadata:
name: "{{ include "app.fullname" . }}-test"
annotations:
"helm.sh/hook": test
"helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
spec:
restartPolicy: Never
containers:
- name: test
image: curlimages/curl:latest
command:
- sh
- -c
- |
set -e
echo "Kiểm readiness endpoint..."
curl -fsS --max-time 10 \
http://{{ include "app.fullname" . }}:{{ .Values.service.port }}{{ .Values.probes.readiness.path }}
echo ""
echo "Kiểm metrics endpoint..."
curl -fsS --max-time 10 \
http://{{ include "app.fullname" . }}:{{ .Values.service.port }}{{ .Values.serviceMonitor.path }} \
| head -5
echo "OK"
helm test order-service -n prod --logs
| Hạn chế | Ý nghĩa |
|---|---|
| Hook không nằm trong release | helm rollback không hoàn tác việc hook đã làm. Migration đã chạy thì đã chạy. |
| Hook thất bại để lại trạng thái lỡ dở | Release ở trạng thái failed hoặc pending-upgrade. Có thể cần
helm rollback hoặc sửa tay trước khi deploy lại được. |
| ArgoCD không chạy Helm hook | ArgoCD render chart bằng helm template rồi tự áp dụng, nên annotation của Helm bị
bỏ qua. Phải dùng ArgoCD sync hooks thay thế — xem bên dưới. |
metadata:
annotations:
# Dành cho Helm (khi deploy bằng helm upgrade)
"helm.sh/hook": pre-install,pre-upgrade
"helm.sh/hook-weight": "-5"
"helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
# Dành cho ArgoCD (khi deploy bằng GitOps)
argocd.argoproj.io/hook: PreSync
argocd.argoproj.io/hook-delete-policy: BeforeHookCreation
argocd.argoproj.io/sync-wave: "-5"
Khai cả hai bộ annotation thì chart dùng được ở cả hai cách deploy. Chi tiết về sync wave và ArgoCD hook ở chặng 07.
helm.sh/hook: pre-upgrade, deploy bằng ArgoCD. Job chạy khi nào?Đây là mô hình thực tế khi bạn có nhiều service cùng khuôn: Java, Python, .NET đều là "một Deployment, một Service, có thể có Ingress". Thay vì 20 chart, bạn có một chart generic và 20 bộ values.
| Mô hình | Cách làm | Phù hợp khi |
|---|---|---|
| Chart riêng mỗi service | Mỗi repo service có chart/ của nó |
Service rất khác nhau. Nhưng dẫn tới sao chép template và 20 bản khác nhau của cùng một lỗi. |
| Library chart | Chart riêng nhưng gọi template từ common |
Cần nhất quán mà vẫn cho phép từng service thêm đối tượng riêng. Linh hoạt nhất. |
| Generic chart đơn giản nhất |
Một chart duy nhất, mỗi service một file values | Service cùng khuôn. Ít việc phải bảo trì nhất. Nên bắt đầu từ đây. |
platform-charts/ # một repo riêng cho chart
├── charts/
│ └── generic-service/ # MỘT chart cho mọi service
│ ├── Chart.yaml
│ ├── values.yaml # mặc định an toàn
│ ├── values.schema.json
│ └── templates/
│ ├── _helpers.tpl
│ ├── deployment.yaml
│ ├── service.yaml
│ ├── ingress.yaml
│ ├── configmap.yaml
│ ├── externalsecret.yaml
│ ├── serviceaccount.yaml
│ ├── hpa.yaml
│ ├── scaledobject.yaml
│ ├── pdb.yaml
│ ├── networkpolicy.yaml
│ ├── servicemonitor.yaml
│ └── job-migration.yaml
└── README.md
gitops-config/ # repo cấu hình (ArgoCD theo dõi repo này)
├── apps/
│ ├── order-service/
│ │ ├── base.yaml # cấu hình chung của service này
│ │ ├── dev.yaml
│ │ ├── staging.yaml
│ │ └── prod.yaml
│ ├── payment-service/
│ │ └── ...
│ └── report-worker-python/
│ └── ...
└── argocd/
└── applicationset.yaml
Điểm khác biệt chính giữa Java, Python và .NET nằm ở: đường dẫn probe, port, biến môi trường runtime, và thời gian khởi động. Đưa tất cả vào values.
# -- Loại runtime: java | python | dotnet | generic
# Dùng để chọn mặc định hợp lý cho probe và biến môi trường.
runtime: generic
service:
port: 8080
probes:
startup:
enabled: true
path: /healthz
periodSeconds: 2
failureThreshold: 30
liveness:
enabled: true
path: /healthz
periodSeconds: 10
timeoutSeconds: 3
failureThreshold: 3
readiness:
enabled: true
path: /readyz
periodSeconds: 5
timeoutSeconds: 3
failureThreshold: 2
# -- Biến môi trường riêng theo runtime, template tự chèn
runtimeEnv:
java:
JAVA_TOOL_OPTIONS: >-
-XX:+UseContainerSupport
-XX:MaxRAMPercentage=70.0
-XX:+ExitOnOutOfMemoryError
-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=/dump
python:
PYTHONUNBUFFERED: "1"
PYTHONDONTWRITEBYTECODE: "1"
PYTHONFAULTHANDLER: "1"
PROMETHEUS_MULTIPROC_DIR: /tmp/prometheus
dotnet:
ASPNETCORE_HTTP_PORTS: "8080"
DOTNET_gcServer: "1"
DOTNET_GCHeapHardLimitPercent: "4B"
DOTNET_TieredPGO: "1"
{{/*
Mặc định theo runtime. Values của service vẫn ghi đè được.
*/}}
{{- define "app.runtimeDefaults" -}}
{{- $r := .Values.runtime | default "generic" -}}
{{- if eq $r "java" -}}
probePathLiveness: /actuator/health/liveness
probePathReadiness: /actuator/health/readiness
metricsPath: /actuator/prometheus
startupFailureThreshold: 60
{{- else if eq $r "python" -}}
probePathLiveness: /healthz
probePathReadiness: /readyz
metricsPath: /metrics
startupFailureThreshold: 15
{{- else if eq $r "dotnet" -}}
probePathLiveness: /healthz
probePathReadiness: /readyz
metricsPath: /metrics
startupFailureThreshold: 30
{{- else -}}
probePathLiveness: /healthz
probePathReadiness: /readyz
metricsPath: /metrics
startupFailureThreshold: 30
{{- end -}}
{{- end }}
{{/*
Gộp biến môi trường: chung + theo runtime + thêm của service
*/}}
{{- define "app.env" -}}
{{- $runtimeEnv := dict -}}
{{- if .Values.runtime -}}
{{- $runtimeEnv = (get .Values.runtimeEnv .Values.runtime) | default dict -}}
{{- end -}}
{{- range $k, $v := $runtimeEnv }}
- name: {{ $k }}
value: {{ $v | quote }}
{{- end }}
{{- range $k, $v := .Values.env }}
- name: {{ $k }}
value: {{ $v | quote }}
{{- end }}
{{- with .Values.extraEnv }}
{{- toYaml . }}
{{- end }}
{{- end }}
runtime: java
image:
repository: .../order-service
service:
port: 8080
resources:
requests:
cpu: 200m
memory: 2816Mi
limits:
cpu: 2000m
memory: 3584Mi
probes:
startup:
path: /actuator/health/readiness
failureThreshold: 60
liveness:
path: /actuator/health/liveness
readiness:
path: /actuator/health/readiness
serviceMonitor:
path: /actuator/prometheus
autoscaling:
enabled: true
targetCPUUtilizationPercentage: 70
runtime: python
image:
repository: .../report-worker
service:
port: 8000
resources:
requests:
cpu: 500m
memory: 512Mi
limits:
cpu: 2000m
memory: 1Gi
env:
# TƯỜNG MINH: Python không
# đọc được cgroup
GUNICORN_WORKERS: "4"
GUNICORN_THREADS: "2"
extraVolumes:
- name: prom
emptyDir: {}
extraVolumeMounts:
- name: prom
mountPath: /tmp/prometheus
autoscaling:
keda:
enabled: true
triggers:
- type: aws-sqs-queue
metadata:
queueLength: "20"
runtime: dotnet
image:
repository: .../invoice-api
service:
port: 8080
resources:
requests:
cpu: 200m
memory: 512Mi
limits:
cpu: 2000m
memory: 1Gi
env:
ASPNETCORE_ENVIRONMENT: Production
# Pod nhỏ: workstation GC
# tốn ít RAM hơn server GC
DOTNET_gcServer: "0"
probes:
startup:
failureThreshold: 30
autoscaling:
enabled: true
targetCPUUtilizationPercentage: 70
Với generic chart, bạn không muốn viết tay 20 Application của ArgoCD. ApplicationSet sinh chúng từ cấu trúc thư mục.
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
name: prod-services
namespace: argocd
spec:
generators:
# Quét thư mục: mỗi apps/<service>/ thành một Application
- git:
repoURL: https://github.com/myorg/gitops-config.git
revision: main
directories:
- path: apps/*
template:
metadata:
name: '{{`{{path.basename}}`}}-prod'
spec:
project: prod
sources:
# Nguồn 1: generic chart từ repo chart
- repoURL: https://github.com/myorg/platform-charts.git
targetRevision: v1.4.0
path: charts/generic-service
helm:
valueFiles:
- $values/apps/{{`{{path.basename}}`}}/base.yaml
- $values/apps/{{`{{path.basename}}`}}/prod.yaml
# Nguồn 2: repo values, gắn alias $values
- repoURL: https://github.com/myorg/gitops-config.git
targetRevision: main
ref: values
destination:
server: https://kubernetes.default.svc
namespace: prod
syncPolicy:
automated:
prune: true
selfHeal: true
syncOptions:
- CreateNamespace=false
{{`{{...}}`}} là cách escape trong Helm: nó in ra {{...}} để
ArgoCD xử lý, thay vì để Helm thay thế ngay. Cần thiết khi chính file ApplicationSet cũng được quản lý
bằng Helm. Chi tiết ở chặng 07.
preStop sleep) nghĩa là sửa một file template, bump chart version, rồi 20 service
nhận được ở lần sync tiếp theo. So với việc mở 20 pull request.
# Render thành YAML mà KHÔNG gửi lên cluster. Lệnh dùng nhiều nhất.
helm template order-service ./chart -f envs/prod/values.yaml
# Chỉ xem một file
helm template order-service ./chart -f envs/prod/values.yaml \
--show-only templates/deployment.yaml
# Kiểm cú pháp và schema
helm lint ./chart -f envs/prod/values.yaml --strict
# Render CÓ kiểm tra với API server thật (phát hiện CRD thiếu, API đã bị loại bỏ)
helm template order-service ./chart -f envs/prod/values.yaml --validate
# Thử nghiệm upgrade: xem Helm sẽ làm gì mà không làm thật
helm upgrade --install order-service ./chart -f envs/prod/values.yaml \
-n prod --dry-run=server
# So diff với trạng thái đang chạy — CẦN plugin helm-diff
helm plugin install https://github.com/databus23/helm-diff
helm diff upgrade order-service ./chart -f envs/prod/values.yaml -n prod
helm diff upgrade là lệnh đáng cài plugin nhất. Nó cho thấy chính xác field
nào sẽ đổi trước khi bạn chạm vào production. Đưa nó vào pipeline CI để diff hiện ngay trong pull
request — người review thấy được hệ quả thật của thay đổi values, không phải đoán từ template.
# Install hoặc upgrade — dùng dạng này trong CI, idempotent
helm upgrade --install order-service ./chart \
-f envs/prod/values.yaml \
--set image.tag=a3f8c21 \
-n prod \
--create-namespace \
--atomic \
--timeout 10m \
--wait
# --atomic : thất bại thì TỰ ĐỘNG rollback về trạng thái trước. Luôn dùng trong CI.
# --wait : chờ pod Ready mới coi là thành công (--atomic đã bao hàm --wait)
# --timeout: hết thời gian thì coi là thất bại (và rollback nếu có --atomic)
# Lịch sử và quay lui
helm history order-service -n prod
helm rollback order-service -n prod # về revision trước
helm rollback order-service 3 -n prod # về revision cụ thể
# Xem những gì đang chạy
helm list -n prod
helm list -A --all # kể cả release thất bại
helm get manifest order-service -n prod # YAML thật đang áp dụng
helm get values order-service -n prod --all # values đã dùng
helm get notes order-service -n prod
# Xoá
helm uninstall order-service -n prod
helm uninstall order-service -n prod --keep-history # giữ lịch sử để rollback được
pending-upgrade hoặc pending-install: xảy ra khi tiến trình
Helm bị giết giữa lúc upgrade (CI timeout, agent bị xoá). Release bị khoá, mọi lệnh sau báo
another operation is in progress.
# 1. Xác nhận trạng thái
helm list -n prod --all
helm history order-service -n prod
# 2. Cách sạch nhất: rollback về revision thành công cuối
helm rollback order-service <revision-thành-công> -n prod
# 3. Nếu rollback cũng không được: xoá secret lưu trạng thái của revision kẹt
kubectl get secret -n prod -l owner=helm,name=order-service
kubectl delete secret -n prod sh.helm.release.v1.order-service.v8
# ^ chỉ xoá secret của revision ĐANG KẸT, không xoá các revision khác
# 4. Trường hợp xấu nhất: đánh dấu lại trạng thái bằng plugin
helm plugin install https://github.com/jkroepke/helm-mapkubeapis
Phòng tránh: luôn dùng --atomic --timeout trong CI, và đặt timeout của job CI
lớn hơn timeout của Helm để Helm kịp tự rollback.
# Lỗi hay gặp 1: nil pointer
# Error: template: chart/templates/deployment.yaml:42:28:
# executing "..." at <.Values.ingress.annotations>: nil pointer evaluating interface {}
# Nguyên nhân: truy cập field lồng mà cha là nil.
# Sửa: dùng default hoặc with
{{- with .Values.ingress.annotations }}{{ toYaml . | nindent 4 }}{{- end }}
{{ (.Values.ingress | default dict).className | default "alb" }}
# Lỗi hay gặp 2: YAML không hợp lệ sau render
# Error: YAML parse error on chart/templates/deployment.yaml: error converting
# YAML to JSON: yaml: line 51: did not find expected key
# Nguyên nhân: thụt lề sai. In ra để xem dòng 51 thật:
helm template order-service ./chart -f envs/prod/values.yaml --debug 2>&1 | head -80
helm template order-service ./chart --show-only templates/deployment.yaml | cat -A | sed -n '45,60p'
# cat -A hiện ký tự ẩn: $ là cuối dòng, ^I là tab (tab trong YAML là LỖI)
# Lỗi hay gặp 3: selector bất biến
# Error: UPGRADE FAILED: cannot patch "x" with kind Deployment:
# spec.selector: Invalid value: field is immutable
# Nguyên nhân: selectorLabels đổi. Chỉ sửa được bằng cách xoá Deployment:
kubectl delete deploy order-service -n prod --cascade=orphan # giữ pod đang chạy
helm upgrade --install order-service ./chart -f envs/prod/values.yaml -n prod
# Lỗi hay gặp 4: giá trị không như mong đợi
# In ra values đã gộp để biết file nào thắng
helm template order-service ./chart -f envs/prod/values.yaml --debug 2>&1 \
| sed -n '/^USER-SUPPLIED VALUES/,/^COMPUTED VALUES/p'
# Tải dependency khai trong Chart.yaml về charts/
helm dependency update ./chart
helm dependency build ./chart # dùng Chart.lock có sẵn, KHÔNG cập nhật phiên bản
helm dependency list ./chart
# COMMIT Chart.lock vào Git. KHÔNG commit charts/*.tgz — thêm vào .gitignore:
# chart/charts/*.tgz
# Đọc chart bên thứ ba TRƯỚC khi cài vào production
helm show values prometheus-community/kube-prometheus-stack > prom-defaults.yaml
helm template prom prometheus-community/kube-prometheus-stack \
-f my-values.yaml | grep -A5 'kind: ClusterRole'
# ^ kiểm xem chart có tạo quyền quá rộng không
# Đăng nhập
aws ecr get-login-password --region ap-southeast-1 \
| helm registry login --username AWS --password-stdin \
123456789012.dkr.ecr.ap-southeast-1.amazonaws.com
# Đóng gói và đẩy
helm package ./chart --version 1.4.2 --app-version a3f8c21
helm push order-service-1.4.2.tgz \
oci://123456789012.dkr.ecr.ap-southeast-1.amazonaws.com/charts
# Cài trực tiếp từ OCI
helm upgrade --install order-service \
oci://123456789012.dkr.ecr.ap-southeast-1.amazonaws.com/charts/order-service \
--version 1.4.2 -f envs/prod/values.yaml -n prod
# Xem các phiên bản chart đã đẩy
aws ecr describe-images --repository-name charts/order-service \
--query 'sort_by(imageDetails,&imagePushedAt)[].imageTags' --output table
| Hạng mục | Vì sao | |
|---|---|---|
| ☐ | Có values.schema.json |
Fail ngay lúc render nếu values sai kiểu hoặc thiếu field bắt buộc. |
| ☐ | values.yaml có chú thích # -- cho mọi tham số |
helm-docs sinh README tự động, tài liệu không lệch với code. |
| ☐ | Chart.lock được commit, charts/*.tgz thì không |
Để CI và mọi người dùng đúng cùng phiên bản dependency. |
| ☐ | Dependency ghim phiên bản cụ thể cho prod, không dùng dải 1.x.x |
Dải phiên bản làm build không tái lập được. |
| ☐ | Tăng version khi sửa template, đổi appVersion khi deploy code mới |
Hai thứ độc lập; nhập nhằng làm mất khả năng truy vết. |
| Hạng mục | Vì sao | |
|---|---|---|
| ☐ | selectorLabels không chứa version hay thứ gì thay đổi |
spec.selector bất biến; đổi nó làm upgrade thất bại, phải xoá Deployment. |
| ☐ | Có checksum/config và checksum/secret annotation |
Không có thì sửa ConfigMap pod không restart. |
| ☐ | Dùng nindent chứ không indent cho khối YAML |
indent không thêm newline nên dòng đầu dính vào key cha. |
| ☐ | Có hàm validate dùng fail để chặn cấu hình sai |
Chặn minAvailable ≥ replicas, bật đồng thời HPA và KEDA, grace period quá nhỏ. |
| ☐ | List dùng mẫu base + extra |
Helm ghi đè list nguyên khối; thiếu mẫu này thì môi trường nào cần thêm phải khai lại cả danh sách. |
| ☐ | required cho giá trị không có mặc định an toàn |
Ví dụ image.repository — thiếu thì phải fail, không được render ra manifest sai. |
| Hạng mục | Vì sao | |
|---|---|---|
| ☐ | Mọi hạng mục của checklist chặng 04 đều được chart hỗ trợ | Chart là nơi áp đặt thói quen tốt cho mọi service cùng lúc. |
| ☐ | Probe, resource, PDB, topology spread đều cấu hình được qua values | Không hard-code trong template — mỗi môi trường có nhu cầu khác nhau. |
| ☐ | Mặc định trong values.yaml là an toàn nhất, không phải mạnh nhất |
Quên khai ở môi trường nào thì vẫn ra cấu hình chạy được, không phải cấu hình tốn kém. |
| Hạng mục | Vì sao | |
|---|---|---|
| ☐ | Job migration có before-hook-creation trong delete policy |
Thiếu là lần upgrade thứ hai lỗi "Job đã tồn tại". |
| ☐ | Không có hook-failed trong delete policy |
Để giữ log của Job migration thất bại — đúng lúc bạn cần nó nhất. |
| ☐ | Job migration có activeDeadlineSeconds |
Không có thì migration treo sẽ chặn deploy vô thời hạn. |
| ☐ | Migration dùng cùng image với app | Đảm bảo schema khớp với code sẽ chạy. |
| ☐ | Migration tương thích ngược giữa hai phiên bản liền kề | Rolling update luôn có hai phiên bản chạy đồng thời; và rollback phải an toàn. |
| ☐ | Khai cả helm.sh/hook và argocd.argoproj.io/hook |
ArgoCD bỏ qua annotation của Helm; chart cần dùng được ở cả hai cách deploy. |
| ☐ | CI dùng --atomic --timeout |
Thất bại thì tự rollback, tránh để release ở trạng thái pending-upgrade kẹt. |
| ☐ | CI chạy helm lint --strict và helm template |
Bắt lỗi cú pháp và schema trước khi chạm cluster. |
| ☐ | Pull request hiển thị helm diff upgrade |
Người review thấy hệ quả thật của thay đổi values, không phải đoán từ template. |
selectorLabels → upgrade thất bại, phải xoá Deployment (có downtime)checksum/config → sửa ConfigMap mà pod không nhận, tưởng đã áp dụng--atomic trong CI → release kẹt pending-upgrade, chặn mọi deploy saubefore-hook-creation → lần upgrade thứ hai lỗi "Job đã tồn tại"