Ở bài trước, migration đã thành Job, nhưng trên namespace mới phải tự chờ postgres-0 trước khi chạy Job, không thì Pod đầu tiên lỗi "no such host". Bài này mình sẽ giới thiệu với mọi người về init container, sidecar và DaemonSet: init container chờ PostgreSQL cho Job migration, native sidecar, triển khai notifier gRPC của TaskFlow, và DaemonSet chạy một Pod trên mỗi node. Bài dùng lại cụm taskflow ở trạng thái cuối Bài 20.
1. Init container là gì?
Init container là container khai báo trong
spec.initContainerscủa Pod, chạy lần lượt từng cái và phải thoát với mã 0 trước khi các container chính (spec.containers) được khởi động.
Nó làm việc của depends_on kèm condition ở bài thứ tự khởi động trong Docker Compose, nhưng nằm ngay trong Pod:
- Trong lúc chạy,
kubectl get podshiệnInit:0/1,Init:1/2...; container chính chưa có nên Pod chưa Ready, chưa nhận traffic. Init container không có probe. - Với
restartPolicy: Never(Pod của Job) init container lỗi là PodFailed, tính một lần thử của Job; vớiAlways/OnFailurekubelet chạy lại nó (Init:CrashLoopBackOff), nên nó phải idempotent. - Init container không chạy cùng lúc với container chính, nên request hiệu lực của Pod là số lớn hơn giữa request lớn nhất của các init container và tổng request của các container chính; scheduler và ResourceQuota tính theo số này. LimitRange (Bài 16) điền mặc định cho init container như mọi container.
2. Chờ PostgreSQL trước migration.
Mình thêm vào Job một init container dùng postgres:18-alpine (có sẵn pg_isready), hỏi PostgreSQL qua tên Service postgres tới khi nó nhận kết nối:
- jobs/migrate.yaml (phần thêm vào template.spec)
# Pod lỗi được giữ lại để đọc log, lần thử sau là Pod mới
restartPolicy: Never
# chạy xong mới tới container migrate (Bài 21): chờ PostgreSQL nhận kết nối,
# thử tối đa 60 lần cách nhau 2 giây, hết lượt thì thoát mã 1: Pod lỗi, Job thử lại
initContainers:
- name: wait-postgres
image: postgres:18-alpine
imagePullPolicy: IfNotPresent
command: ["sh", "-c"]
args:
- |
for i in $(seq 60); do
pg_isready -h postgres -t 2 && exit 0
sleep 2
done
echo "PostgreSQL chưa sẵn sàng sau 60 lần thử"
exit 1
containers:
- name: migrate
# ... như Bài 20
pg_isready không cần mật khẩu, thoát 0 khi server nhận kết nối; tên postgres chưa phân giải được (headless Service chưa có Pod Ready, Bài 19) thì nó in no response. Vòng lặp có giới hạn để PostgreSQL hỏng thật thì Pod lỗi và Job thử lại theo backoffLimit, trong activeDeadlineSeconds: 300. LimitRange điền 50m/64Mi nên request hiệu lực của Pod không đổi.
Để thấy nó làm việc, mình xóa namespace rồi dựng lại và chạy Job ngay, không chờ postgres-0 (dữ liệu thử của các bài trước mất theo namespace):
kubectl delete namespace taskflow --wait=true --timeout=180s
# namespace "taskflow" deleted
kubectl apply -f k8s/namespace.yaml && kubectl apply -f k8s/
# namespace/taskflow created
# ...
kubectl replace --force -f jobs/migrate.yaml
# job.batch/taskflow-migrate replaced
kubectl get pods -l batch.kubernetes.io/job-name=taskflow-migrate -w
# NAME READY STATUS RESTARTS AGE
# taskflow-migrate-zq8nl 0/1 Init:0/1 0 0s
# ...
# taskflow-migrate-zq8nl 0/1 PodInitializing 0 30s
# taskflow-migrate-zq8nl 1/1 Running 0 30s
# taskflow-migrate-zq8nl 0/1 Completed 0 31s
kubectl logs job/taskflow-migrate -c wait-postgres
# postgres:5432 - no response
# ...
# postgres:5432 - accepting connections
Pod đứng ở Init:0/1 khoảng 30 giây trong lúc PostgreSQL chạy initdb trên volume mới, init container in 14 dòng no response rồi thoát 0, lúc đó container migrate mới được tạo và chạy đủ 7 migration ngay lần đầu (kubectl logs job/taskflow-migrate mặc định chọn container migrate). Không còn Pod lỗi "no such host", và README của repo bỏ bước kubectl wait ... pod/postgres-0. Sau đó mình đăng ký lại [email protected], tạo project Kubernetes và task 1 như Bài 19.
Có nên thêm init container cho taskflow-api?
Ba Pod taskflow-api tạo cùng lúc với Job ở trên crash vì "database còn migration chưa chạy" rồi tự lên sau vài lần khởi động lại (2–3 lần, tùy lúc PostgreSQL sẵn sàng). Mình không thêm init container cho Deployment này. Chờ database là chưa đủ, TaskFlow còn từ chối chạy khi schema cũ hơn code, mà image không có lệnh chỉ kiểm tra migration; dùng -migrate thì mỗi replica tự migrate, đúng điều Bài 20 tránh. Khi lên version, Job migration xong trước kubectl apply -f k8s/ nên Pod mới không gặp migration còn treo, có lỗi thì maxUnavailable: 0 và readiness probe (Bài 15) giữ Pod cũ phục vụ. Trên cụm mới, CrashLoopBackOff tự hết: lần chạy lại README cuối bài, ba Pod Ready khoảng 20 giây sau apply, và số restart là tín hiệu thật thay vì Pod đứng im ở Init:0/1. Database mất giữa chừng thì init container cũng không giúp gì, việc đó đã có /ready.
Init container hợp với việc phải xong trước, một lần cho mỗi Pod: chờ dependency cho tác vụ chạy một lần, sinh file cấu hình vào emptyDir, dùng công cụ không có trong image chính (image TaskFlow là distroless, không có shell).
3. Native sidecar container.
Sidecar kiểu cũ ở Bài 6 chỉ là container thứ hai trong containers: không có thứ tự (proxy, agent gửi log có thể lên sau ứng dụng và tắt trước nó), và Pod của Job chỉ xong khi mọi container thoát, mà sidecar thì chạy mãi. Native sidecar (bật mặc định từ Kubernetes 1.29, stable từ 1.33) là init container có restartPolicy: Always: khởi động theo thứ tự như init container nhưng không cần thoát, chạy suốt đời Pod và chỉ bị dừng sau khi container chính đã dừng.
Thử bằng Job thu-sidecar.yaml (ngoài repo): app ghi ba dòng vào file trên emptyDir rồi thoát, sidecar log-shipper đọc file đó ra stdout như một agent gửi log:
- thu-sidecar.yaml
apiVersion: batch/v1
kind: Job
metadata:
name: thu-sidecar
namespace: taskflow
spec:
ttlSecondsAfterFinished: 300
template:
spec:
restartPolicy: Never
initContainers:
# native sidecar: init container có restartPolicy Always, chạy suốt đời Pod
- name: log-shipper
image: busybox:1.37
restartPolicy: Always
command: ["sh", "-c"]
args:
- |
trap 'echo "log-shipper: nhận SIGTERM lúc $(date +%T)"; exit 0' TERM
echo "log-shipper: bắt đầu lúc $(date +%T)"
tail -F /var/log/app/app.log &
wait
# ... volumeMounts: logs → /var/log/app (cả hai container)
containers:
- name: app
image: busybox:1.37
command: ["sh", "-c"]
args:
- |
for i in 1 2 3; do
echo "app: dòng $i lúc $(date +%T)" >> /var/log/app/app.log
sleep 2
done
# ... volumes: logs là emptyDir
kubectl apply -f thu-sidecar.yaml
# job.batch/thu-sidecar created
kubectl get pods -l batch.kubernetes.io/job-name=thu-sidecar -w
# NAME READY STATUS RESTARTS AGE
# ...
# thu-sidecar-rlpjq 0/2 Init:0/1 0 0s
# thu-sidecar-rlpjq 1/2 PodInitializing 0 6s
# thu-sidecar-rlpjq 2/2 Running 0 6s
# thu-sidecar-rlpjq 1/2 Completed 0 13s
# thu-sidecar-rlpjq 0/2 Completed 0 13s
kubectl get job thu-sidecar
# NAME STATUS COMPLETIONS DURATION AGE
# thu-sidecar Complete 1/1 15s 30s
kubectl logs job/thu-sidecar -c log-shipper
# log-shipper: bắt đầu lúc 15:33:23
# tail: can't open '/var/log/app/app.log': No such file or directory
# tail: /var/log/app/app.log has appeared; following end of new file
# app: dòng 1 lúc 15:33:23
# app: dòng 2 lúc 15:33:25
# app: dòng 3 lúc 15:33:27
# log-shipper: nhận SIGTERM lúc 15:33:30
- Sidecar lên trước (
1/2 PodInitializing) và được tính vàoREADY. kubelet chỉ khởi động container kế tiếp khi sidecar đã chạy, hoặcstartupProbecủa nó đã qua: sidecar nhận được probe. appthoát (sau dòng cuối lúc 15:33:27) rồi sidecar mới nhận SIGTERM, nên đọc được tới dòng cuối. Xóa Pod của Deployment cũng vậy.- Job
Completemà không cần sidecar tự thoát: Job chỉ xét container chính.
Chuyển log-shipper sang containers (file thu-sidecar-cu.yaml) thì 40 giây sau kubectl get job vẫn là Running 0/1, Pod 1/2 NotReady: app đã thoát từ lâu nhưng sidecar còn chạy, Job không bao giờ xong (xóa bằng kubectl delete -f thu-sidecar-cu.yaml). Request của sidecar cộng vào tổng của Pod vì nó chạy cùng container chính. Sidecar thật thường là agent gửi log, proxy của service mesh hay proxy kết nối database của cloud; TaskFlow ghi log ra stdout nên chưa cần.
4. Triển khai notifier của TaskFlow.
Notifier là gRPC server nhận thông báo từ API (bài gRPC phần 1 và phần 2 của series Golang): cùng image taskflow-api:0.53.0, chạy bằng /notifier, nghe ở TASKFLOW_NOTIFIER_ADDR (mặc định :9090), bắt buộc TASKFLOW_NOTIFIER_TOKEN dài ít nhất 32 byte, và có cài gRPC health service. Token là bí mật dùng chung với API, địa chỉ thì không:
k8s/secret.yaml(và file mẫu): thêmTASKFLOW_NOTIFIER_TOKEN: doi-token-notifier-nay-dai-it-nhat-32-bytevàostringDatacủataskflow-secrets; giá trị thật lấy từopenssl rand -hex 32.k8s/configmap.yaml: thêmTASKFLOW_NOTIFIER_ADDR: taskflow-notifier:9090, tên Service ngắn cùng namespace và port.
- k8s/notifier.yaml (phần Deployment, lược bớt)
spec:
# một bản: notifier giữ khóa chống gửi trùng và các stream Watch trong bộ nhớ
replicas: 1
# ... revisionHistoryLimit, selector name=taskflow-notifier + component=notifier
template:
# ... label của Pod, thêm app.kubernetes.io/version: "0.53.0"
spec:
containers:
- name: notifier
image: taskflow-api:0.53.0
imagePullPolicy: IfNotPresent
# thay ENTRYPOINT /api của image
command: ["/notifier"]
ports:
- name: grpc
containerPort: 9090
# chỉ cần token, lấy đúng một key của taskflow-secrets. Không dùng envFrom
# ConfigMap taskflow-config: TASKFLOW_NOTIFIER_ADDR trong đó là địa chỉ api
# gọi tới, còn với notifier biến này là địa chỉ lắng nghe (mặc định :9090)
env:
- name: TASKFLOW_NOTIFIER_TOKEN
valueFrom:
secretKeyRef:
name: taskflow-secrets
key: TASKFLOW_NOTIFIER_TOKEN
resources:
requests:
cpu: 20m
memory: 32Mi
limits:
memory: 64Mi
# grpc.health.v1.Health/Check, notifier không đòi token cho RPC này;
# port của grpc chỉ nhận số
readinessProbe:
grpc:
port: 9090
periodSeconds: 5
failureThreshold: 2
# ... livenessProbe grpc cùng port, mỗi 10 giây, 3 lần lỗi liền
Trong đó:
commandthayENTRYPOINTnhưentrypointcủa Compose.secretKeyRefthay vìenvFrom: notifier không cầnDATABASE_URLhayTASKFLOW_JWT_SECRET, và không được nhận ConfigMap của API. Chạy thử notifier vớiTASKFLOW_NOTIFIER_ADDR=taskflow-notifier:9090, nó thoát ngay:listen tcp 10.96.16.215:9090: bind: cannot assign requested address.- Probe
grpcmà Bài 15 đã hẹn: kubelet gọigrpc.health.v1.Health/Checkvới service rỗng (cả server). Notifier cho RPC này qua không cần token, không ghi log khiSERVING, và chuyển sangNOT_SERVINGkhi bắt đầu tắt. - Đo bằng Summary API của kubelet như Bài 16, notifier lúc rảnh dùng khoảng 8Mi, nên request 32Mi, limit 64Mi.
- Một replica vì trạng thái trong bộ nhớ; hơn nữa gRPC giữ một kết nối HTTP/2 lâu dài mà kube-proxy chỉ cân bằng theo kết nối, nhiều replica thì mỗi Pod API vẫn chỉ gọi một notifier.
Sau dấu --- là Service ClusterIP taskflow-notifier, port 9090 tên grpc. Các biến TASKFLOW_NOTIFIER_SERVICE_HOST, TASKFLOW_NOTIFIER_PORT_9090_TCP_ADDR... mà Service sinh ra (Bài 12) không trùng hai key TaskFlow đọc. Apply Secret và notifier trước, rồi ConfigMap và restart API (biến từ envFrom không tự cập nhật, Bài 13):
kubectl apply -f k8s/secret.yaml -f k8s/notifier.yaml
# secret/taskflow-secrets configured
# ...
# deployment.apps/taskflow-notifier created
# service/taskflow-notifier created
kubectl rollout status deploy/taskflow-notifier
# Waiting for deployment "taskflow-notifier" rollout to finish: 0 of 1 updated replicas are available...
# deployment "taskflow-notifier" successfully rolled out
kubectl logs deploy/taskflow-notifier
# time=2026-11-24T15:35:53.131Z level=INFO msg="notifier đang chạy" addr=[::]:9090
kubectl apply -f k8s/configmap.yaml
# configmap/taskflow-config configured
kubectl rollout restart deploy/taskflow-api && kubectl rollout status deploy/taskflow-api
# ...
# deployment "taskflow-api" successfully rolled out
Pod API mới log "gửi thông báo qua notifier gRPC","addr":"taskflow-notifier:9090". TaskFlow báo "task đã xong" cho chủ project và người được giao, trừ người vừa đổi status. Nên mình đăng ký thêm Bình, An tạo task giao cho Bình rồi chuyển nó sang done (API và TOKEN của An lấy như Bài 19):
curl -s -X POST $API/auth/register -H "Content-Type: application/json" -d '{"email":"[email protected]","name":"Bình","password":"doi-mat-khau-nay"}'
# {"id":2,"email":"[email protected]","name":"Bình","created_at":"2026-11-24T15:36:39.35882Z"}
curl -s -X POST $API/tasks -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d '{"project_id":1,"title":"Trien khai notifier","assignee_id":2}'
# {"id":2,"project_id":1,"title":"Trien khai notifier","status":"todo","assignee_id":2}
curl -s -i -X PATCH $API/tasks/2 -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d '{"status":"done"}'
# HTTP/1.1 200 OK
# ...
# X-Request-Id: HG5MKCLZIN2KRTE37WHO7ZM32H
# ...
kubectl logs deploy/taskflow-notifier
# time=2026-11-24T15:35:53.131Z level=INFO msg="notifier đang chạy" addr=[::]:9090
# time=2026-11-24T15:36:39.995Z level=INFO msg="thông báo: task đã xong" to_user=2 task_id=2 title="Trien khai notifier" done_by=1 request_id=HG5MKCLZIN2KRTE37WHO7ZM32H
# time=2026-11-24T15:36:39.995Z level=INFO msg=rpc method=/notify.v1.NotificationService/Send code=OK duration=109µs timeout=4.825s request_id=HG5MKCLZIN2KRTE37WHO7ZM32H
API đưa job vào hàng đợi Redis, một worker gọi Send qua Service taskflow-notifier, và notifier ghi thông báo cho user 2 với đúng request_id của request HTTP. Tắt notifier (kubectl scale deploy/taskflow-notifier --replicas=0) rồi hoàn thành task 3 thì API vẫn trả 200, log có "job lỗi, sẽ chạy lại"; scale lại 1 thì khoảng 10 giây sau thông báo tới nơi. Notifier không cần lên trước API, nên API cũng không cần init container chờ nó.
5. DaemonSet.
DaemonSet là controller chạy đúng một Pod trên mỗi node phù hợp: node mới vào cụm thì có Pod mới, node rời cụm thì Pod bị dọn. Không có
replicas, số Pod bằng số node.
Đó là cách chạy agent của node: mạng (kindnet, kube-proxy ở Bài 2; kubectl get daemonset -n kube-system cho thấy DESIRED 3), gom log, metric của node (node-exporter ở Bài 30). Thử một agent nhỏ thu-node-log.yaml (ngoài repo): busybox gắn /var/log/pods của node, nơi kubelet ghi stdout/stderr của mọi container, bằng hostPath chỉ đọc, rồi đếm số thư mục log mỗi 30 giây:
- thu-node-log.yaml (lược bớt label)
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: thu-node-log
namespace: taskflow
spec:
selector:
matchLabels:
app.kubernetes.io/name: thu-node-log
# mặc định: thay lần lượt từng node, mỗi lúc tối đa 1 Pod không chạy
updateStrategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 1
template:
# ... label app.kubernetes.io/name: thu-node-log
spec:
containers:
- name: reader
image: busybox:1.37
command: ["sh", "-c"]
args:
- |
while true; do
echo "$(date +%T) $NODE_NAME: $(ls /var/log/pods | wc -l) thư mục log Pod"
sleep 30
done
env:
# tên node đang chạy Pod này (downward API)
- name: NODE_NAME
valueFrom:
fieldRef:
fieldPath: spec.nodeName
volumeMounts:
- name: pod-logs
mountPath: /var/log/pods
readOnly: true
# ... resources: request 10m/16Mi, limit 32Mi
volumes:
# thư mục log container của node, nơi kubelet ghi stdout/stderr của mọi Pod
- name: pod-logs
hostPath:
path: /var/log/pods
type: Directory
kubectl apply -f thu-node-log.yaml
# daemonset.apps/thu-node-log created
kubectl get daemonset thu-node-log
# NAME DESIRED CURRENT READY UP-TO-DATE AVAILABLE NODE SELECTOR AGE
# thu-node-log 2 2 2 2 2 <none> 8s
kubectl logs -l app.kubernetes.io/name=thu-node-log --prefix
# [pod/thu-node-log-g7djh/reader] 15:38:40 taskflow-worker: 7 thư mục log Pod
# [pod/thu-node-log-zpqq7/reader] 15:38:44 taskflow-worker2: 8 thư mục log Pod
Cụm có ba node mà DESIRED là 2: control plane mang taint node-role.kubernetes.io/control-plane:NoSchedule (xem bằng kubectl describe node taskflow-control-plane) nên không nhận Pod thường. kindnet và kube-proxy chạy được ở đó nhờ toleration operator: Exists (chấp nhận mọi taint). Agent gom log cũng cần log của control plane, nên mình thêm toleration vào template.spec (taint và toleration học kỹ ở Bài 26):
# chạy cả trên control plane: chấp nhận taint NoSchedule của node đó
tolerations:
- key: node-role.kubernetes.io/control-plane
operator: Exists
effect: NoSchedule
kubectl apply -f thu-node-log.yaml && kubectl rollout status ds/thu-node-log
# daemonset.apps/thu-node-log configured
# Waiting for daemon set "thu-node-log" rollout to finish: 1 out of 3 new pods have been updated...
# ...
# daemon set "thu-node-log" successfully rolled out
kubectl get pods -l app.kubernetes.io/name=thu-node-log -o wide
# NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
# thu-node-log-29swq 1/1 Running 0 66s 10.244.0.5 taskflow-control-plane <none> <none>
# thu-node-log-k8wv9 1/1 Running 0 31s 10.244.1.15 taskflow-worker <none> <none>
# thu-node-log-tdcfm 1/1 Running 0 0s 10.244.2.22 taskflow-worker2 <none> <none>
Đổi Pod template là một rolling update: control plane được tạo Pod ngay, còn trên hai worker DaemonSet xóa Pod cũ rồi mới tạo Pod mới, từng node một (tuổi 66, 31, 0 giây). Mỗi node mất khoảng 30 giây vì sh là PID 1 không xử lý SIGTERM, kubelet chờ hết terminationGracePeriodSeconds; có trap như log-shipper thì thoát ngay. rollout history, rollout undo dùng như Deployment ở Bài 10. Đặt maxSurge: 1, maxUnavailable: 0 thì Pod mới lên trước khi Pod cũ bị xóa, hợp với agent không được gián đoạn; type: OnDelete thì chỉ thay Pod khi ta tự xóa nó.
Lúc chạy, quota lên 9/20 Pod. Agent thật như Fluent Bit, Vector hay Grafana Alloy đọc chính các file log này, nhưng là hạ tầng của cụm nên đặt ở namespace riêng (như Traefik ở platform/), và Pod Security ở Bài 28 sẽ cấm hostPath trong namespace ứng dụng. Vì vậy DaemonSet này không vào repo; dọn bằng kubectl delete -f thu-node-log.yaml.
Cuối bài namespace có 6/20 Pod, requests 470m CPU, 544Mi memory, kubectl diff -f k8s/ trả exit 0, và phần "Cài trên cụm mới" của README chạy lại trên namespace mới vẫn qua. Xem thêm về init container, sidecar container và DaemonSet trên trang của Kubernetes.
Code đầy đủ của series sau bài này nằm ở tag bai-21 trên GitHub; các thay đổi của riêng bài này: so sánh bai-20...bai-21.
6. Lời kết.
Như vậy mình đã giới thiệu với mọi người về init container, sidecar và DaemonSet: init container wait-postgres cho Job migration, native sidecar giúp Job kết thúc đúng lúc, notifier gRPC với probe grpc, và DaemonSet chạy agent trên mọi node. Giờ version image lặp ở ba file (deployment.yaml, notifier.yaml, jobs/migrate.yaml), mật khẩu lặp ở hai Secret; bài sau mình sẽ giới thiệu Kustomize: base và overlay cho dev, prod, sinh ConfigMap, Secret bằng generator và đổi version image ở một chỗ.
Đăng ký nhận tin.
Chúng tôi chỉ gửi tối đa 2 lần trên 1 tháng. Tuyên bố không spam mail!





0 Comments