Bài tập: Viết Helm chart cho notes-api
Bạn sẽ tự viết từ đầu Helm chart notes-api, gom toàn bộ phần notes-api của các chương trước (ConfigMap, Secret, Deployment, Service, HPA, HTTPRoute) vào một gói có tham số, kèm hai file values cho dev và prod. Chart phải đủ tốt để một đồng đội chưa từng đọc manifest gốc cũng cài được chỉ bằng values. Đây là bài tập mở: không có chấm tự động, cuối đề có bộ lệnh để bạn tự kiểm tra, và lời giải mẫu để đối chiếu.
Điểm xuất phát
- Cluster kind
hoc-k8s; imagenotes-api:1.0vànotes-api:1.1đã nạp bằngkind load docker-image. - Namespace
notescó StatefulSet + Servicepostgres, Deployment + Serviceredis, Secretnotes-db(ba keyPOSTGRES_USER,POSTGRES_PASSWORD,POSTGRES_DB). - Gateway
shared-gateway(namespacegateway-infra, listenerhttp,*.localtest.me) của Envoy Gateway từ chương 6; namespacenotesđã có labelshared-gateway-access=true. - Helm 3 hoặc 4 đã cài.
Gỡ notes-api cũ trước, nếu không Helm sẽ báo invalid ownership metadata vì tài nguyên cùng tên đã tồn tại mà không do Helm tạo:
# Nếu đã làm bài GitOps: xóa Application, finalizer khiến Argo CD xóa luôn tài nguyên notes-api
kubectl -n argocd delete application notes-api --ignore-not-found
# Nếu đang dùng Kustomize
kubectl delete -k k8s/overlays/dev --ignore-not-found
kubectl -n notes get deploy,svc,httproute,hpa # chỉ còn postgres, redisKết quả cần có:
notes-helm/
├── notes-api/ # chart
│ ├── Chart.yaml
│ ├── values.yaml
│ └── templates/
│ ├── _helpers.tpl
│ ├── configmap.yaml
│ ├── secret.yaml
│ ├── deployment.yaml
│ ├── service.yaml
│ ├── hpa.yaml
│ └── httproute.yaml
├── values-dev.yaml
└── values-prod.yamlCó thể bắt đầu bằng helm create notes-api rồi xóa những file không dùng (ingress.yaml, serviceaccount.yaml, NOTES.txt, tests/): các file mẫu này tham chiếu values bạn sẽ không có.
Yêu cầu
Chart và values
Chart.yaml:apiVersion: v2,name: notes-api,version: 0.1.0,appVersion: "1.0".values.yamlcó ít nhất:image.repository,image.tag(rỗng thì dùngappVersion),image.pullPolicy(mặc địnhIfNotPresent),replicaCount,containerPort,config(map biến môi trường thường),appConfig(nội dungapp-config.json),database(host,port,existingSecret,user,password,name),service(type,port,nodePort),probes(readiness,liveness),resources,autoscaling(enabled,minReplicas,maxReplicas,targetCPUUtilizationPercentage),httpRoute(enabled,hostnames,parentRefs). Giá trị mặc định phải an toàn: không có mật khẩu, HPA và HTTPRoute tắt._helpers.tplđịnh nghĩa ít nhấtnotes-api.name,notes-api.fullname(tôn trọngfullnameOverride),notes-api.labels,notes-api.selectorLabels. Selector label không chứa thứ gì thay đổi giữa các phiên bản.
Templates
configmap.yaml: một ConfigMap chứaPORT(lấy từcontainerPort) cùng mọi key trongconfig;app-config.jsonnằm ở một ConfigMap riêng (lý do như chương 7).secret.yaml: chỉ tạo Secret khidatabase.existingSecretrỗng; khi đó thiếudatabase.passwordthì render phải dừng với thông báo rõ ràng (required).deployment.yaml: container tênnotes-api; nhận ConfigMap bằngenvFrom; nhận ba biếnPOSTGRES_*bằngsecretKeyReftừ Secret có sẵn hoặc Secret của chart; ghépDATABASE_URLbằng$(…)với host và port lấy từ values; gắnapp-config.jsonchỉ đọc vào/etc/notes; probe vàresourceslấy nguyên khối từ values (không inresourcesnếu rỗng); bỏreplicaskhiautoscaling.enabled.- Pod tự rolling update khi nội dung ConfigMap (hoặc Secret của chart) thay đổi, và không tạo Pod mới khi upgrade với values y hệt.
- Pod vẫn mang label
app: notes-api, để NetworkPolicy của chương 11 và các lệnhkubectl -l app=notes-apitiếp tục đúng. service.yaml:typevàporttừ values,targetPortlà cổng tênhttp; chỉ ghinodePortkhi type làNodePortvà có giá trị.hpa.yaml:autoscaling/v2, chỉ render khiautoscaling.enabled.httproute.yaml: chỉ render khihttpRoute.enabled;hostnamesvàparentRefslấy từ values; backend là Service của chart.
Môi trường
values-dev.yaml: tên tài nguyên lànotes-api(không phảinotes-notes-api), 1 bản sao,LOG_LEVEL=debug, dùng Secret có sẵnnotes-db, ServiceNodePort30080, HTTPRoute bật chonotes.localtest.me.values-prod.yaml: image1.1, córesources, HPA 3–10 bản sao ở 70% CPU, ServiceClusterIP, HTTPRoute chonotes.example.com, và không chứa mật khẩu.
Điểm cộng (không bắt buộc): NOTES.txt in cách truy cập theo loại Service; values.schema.json để Helm từ chối values sai kiểu; Job migration dạng hook pre-install,pre-upgrade như bài Helm.
Tự kiểm tra
Chạy trong thư mục notes-helm/. Kết quả mong đợi ghi trong comment.
# 1. Chart hợp lệ và render được
helm lint ./notes-api -f values-dev.yaml # 1 chart(s) linted, 0 chart(s) failed
helm template notes ./notes-api -n notes -f values-dev.yaml | kubectl apply --dry-run=server -n notes -f -
# configmap/notes-api-config created (server dry run) ... httproute.../notes-api created (server dry run)
# 2. Bật/tắt theo values
helm template notes ./notes-api -f values-dev.yaml | grep -c 'kind: HorizontalPodAutoscaler' # 0
helm template notes ./notes-api -f values-prod.yaml --set database.password=x | grep '^kind:'
# Secret, ConfigMap, ConfigMap, Service, Deployment, HorizontalPodAutoscaler, HTTPRoute
helm template notes ./notes-api -f values-prod.yaml --set database.password=x | grep -c 'replicas:' # 0
# 3. Thiếu mật khẩu khi chart phải tự tạo Secret
helm template notes ./notes-api -f values-prod.yaml
# Error: execution error at (notes-api/templates/secret.yaml...): database.password là bắt buộc ...
# 4. Cài thật với dev
helm upgrade --install notes ./notes-api -n notes -f values-dev.yaml
kubectl -n notes rollout status deploy/notes-api # successfully rolled out
helm list -n notes # notes ... deployed notes-api-0.1.0 1.0
helm get manifest notes -n notes | grep '^kind:' # ConfigMap x2, Service, Deployment, HTTPRoute
curl -s localhost:30080/health # {"status":"ok"}
export GATEWAY_IP=$(kubectl -n gateway-infra get gateway shared-gateway -o jsonpath='{.status.addresses[0].value}')
curl -s --resolve notes.localtest.me:80:${GATEWAY_IP} http://notes.localtest.me/health # {"status":"ok"}
curl -s -X POST localhost:30080/notes -H 'Content-Type: application/json' -d '{"text":"helm chart"}'
curl -s localhost:30080/notes # có note "helm chart"
# 5. Upgrade với values y hệt: không có Pod mới
kubectl -n notes get pods -l app=notes-api # ghi lại tên Pod
helm upgrade --install notes ./notes-api -n notes -f values-dev.yaml
kubectl -n notes get pods -l app=notes-api # cùng tên Pod, AGE tiếp tục tăng
# 6. Đổi cấu hình: Pod được thay
helm upgrade notes ./notes-api -n notes -f values-dev.yaml --set config.LOG_LEVEL=warn
kubectl -n notes rollout status deploy/notes-api
kubectl exec -n notes deploy/notes-api -- printenv LOG_LEVEL # warn
# 7. Rollback về bản cài đầu tiên
helm rollback notes 1 -n notes
kubectl -n notes rollout status deploy/notes-api
kubectl exec -n notes deploy/notes-api -- printenv LOG_LEVEL # debug
helm history notes -n notes # revision 4: Rollback to 1Trên macOS/Windows, nếu không gọi được IP của Gateway, dùng cách port-forward + --connect-to ở bài Gateway API: GatewayClass, Gateway và HTTPRoute.
# ===== notes-api/Chart.yaml =====
apiVersion: v2
name: notes-api
description: Helm chart cho notes-api
type: application
# TODO: version (phiên bản chart) và appVersion (phiên bản ứng dụng, dùng làm tag mặc định)
# ===== notes-api/values.yaml =====
nameOverride: ""
fullnameOverride: ""
replicaCount: 1
image:
repository: notes-api
tag: "" # rỗng -> appVersion
pullPolicy: IfNotPresent
containerPort: 3000
config:
LOG_LEVEL: info
REDIS_URL: redis://redis:6379
appConfig: {}
database:
host: postgres
port: 5432
existingSecret: ""
user: notes
password: "" # KHÔNG điền mật khẩu thật ở đây
name: notes
# TODO: service (type, port, nodePort)
# TODO: probes.readiness và probes.liveness (httpGet /health, cổng tên http)
# TODO: resources (mặc định rỗng)
# TODO: autoscaling (enabled: false, minReplicas, maxReplicas, targetCPUUtilizationPercentage)
# TODO: httpRoute (enabled: false, hostnames, parentRefs tới shared-gateway / gateway-infra / http)
# ===== notes-api/templates/_helpers.tpl =====
{{- define "notes-api.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
{{- end }}
{{/* TODO: notes-api.fullname (fullnameOverride, hoặc <release>-<chart>) */}}
{{/* TODO: notes-api.selectorLabels (chỉ thứ không bao giờ đổi) */}}
{{/* TODO: notes-api.labels (selectorLabels + app: notes-api + version + managed-by) */}}
{{/* TODO: tên Secret database: existingSecret hoặc <fullname>-db */}}
# ===== notes-api/templates/configmap.yaml =====
# TODO: ConfigMap <fullname>-config: PORT (từ containerPort) + range qua .Values.config (quote mọi giá trị)
# ---
# TODO: ConfigMap <fullname>-app-config: key app-config.json từ .Values.appConfig (toPrettyJson)
# ===== notes-api/templates/secret.yaml =====
# TODO: chỉ khi database.existingSecret rỗng; stringData POSTGRES_USER / POSTGRES_PASSWORD (required) / POSTGRES_DB
# ===== notes-api/templates/deployment.yaml =====
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "notes-api.fullname" . }}
labels:
{{- include "notes-api.labels" . | nindent 4 }}
spec:
# TODO: replicas, chỉ khi autoscaling tắt
selector:
matchLabels:
{{- include "notes-api.selectorLabels" . | nindent 6 }}
template:
metadata:
# TODO: annotation checksum cho configmap.yaml (và secret.yaml)
labels:
{{- include "notes-api.labels" . | nindent 8 }}
spec:
containers:
- name: {{ .Chart.Name }}
# TODO: image (tag mặc định appVersion), imagePullPolicy, cổng tên http
# TODO: envFrom ConfigMap; POSTGRES_* bằng secretKeyRef; DATABASE_URL ghép bằng $(...)
# TODO: volumeMount app-config chỉ đọc tại /etc/notes
# TODO: readinessProbe / livenessProbe từ values (toYaml | nindent)
# TODO: resources chỉ khi khác rỗng (with)
# TODO: volumes
# ===== notes-api/templates/service.yaml =====
# TODO: type/port từ values, targetPort: http, nodePort chỉ khi type NodePort và có giá trị
# ===== notes-api/templates/hpa.yaml =====
# TODO: autoscaling/v2, chỉ khi autoscaling.enabled
# ===== notes-api/templates/httproute.yaml =====
# TODO: chỉ khi httpRoute.enabled; parentRefs và hostnames từ values; backend = Service của chart
# ===== values-dev.yaml =====
# TODO: tên tài nguyên notes-api, 1 bản sao, LOG_LEVEL=debug, existingSecret notes-db,
# NodePort 30080, HTTPRoute bật cho notes.localtest.me
# ===== values-prod.yaml =====
# TODO: image 1.1, resources, HPA 3-10 ở 70% CPU, ClusterIP, HTTPRoute notes.example.com, KHÔNG có mật khẩu
Comments