Ở bài trước, file upload của TaskFlow đã nằm trên PVC, nhưng người dùng, project và task vẫn ở trong bộ nhớ của từng Pod nên taskflow-api phải chạy một replica. Bài này mình sẽ giới thiệu với mọi người về StatefulSet qua việc chạy PostgreSQL trên Kubernetes: headless Service, volumeClaimTemplates, danh tính cố định của Pod, thêm Redis bằng Deployment, chạy migration, rồi lần đầu chạy TaskFlow đầy đủ với database. Bài dùng lại cụm taskflow ở trạng thái cuối Bài 18.
1. Vì sao không chạy database bằng Deployment?
Deployment (Bài 9) coi các Pod là giống hệt nhau, thay cho nhau được: tên có đuôi ngẫu nhiên, rolling update tạo Pod mới trước rồi mới xóa Pod cũ. Với TaskFlow API, vốn không giữ trạng thái, vậy là đúng. Với database thì không:
- Dữ liệu: mọi Pod của Deployment dùng chung một PVC. Hai PostgreSQL cùng ghi một thư mục là hỏng dữ liệu, và rolling update với
maxSurge: 1tạo ra đúng tình huống đó. - Danh tính: Pod mới mang tên mới, IP mới, trong khi replica của database cần tìm primary theo một tên không đổi.
- Thứ tự: replica chỉ nên khởi động khi primary đã sẵn sàng, tắt thì ngược lại.
StatefulSet là controller chạy các Pod có danh tính cố định: Pod tên
<tên StatefulSet>-0,-1,-2..., mỗi Pod có tên DNS riêng qua một headless Service và một PVC riêng sinh từvolumeClaimTemplates. Pod được tạo lần lượt theo số thứ tự và xóa theo thứ tự ngược lại.
StatefulSet cũng không bao giờ chạy hai Pod cùng tên một lúc: node chứa postgres-0 mất liên lạc thì nó chờ tới khi chắc chắn Pod cũ đã dừng mới tạo lại, chấp nhận gián đoạn còn hơn hai bản cùng ghi một volume.
2. Headless Service và StatefulSet postgres.
Image postgres:18-alpine đọc POSTGRES_PASSWORD, POSTGRES_USER, POSTGRES_DB như ở bài chạy PostgreSQL và Redis của series Docker. Để mật khẩu trong taskflow-secrets thì taskflow-api, vốn nạp mọi key bằng envFrom (Bài 14), nhận thêm POSTGRES_PASSWORD nó không cần. Mình tách ra Secret riêng postgres-secrets: Pod nào chỉ thấy bí mật của Pod đó, taskflow-secrets vẫn chỉ chứa biến của TaskFlow như quy ước ở Bài 14, và phân quyền (Bài 27) làm được theo từng Secret.
- k8s/secret.yaml (thêm vào cuối, file mẫu k8s/secret.yaml.example cũng vậy)
---
# Mật khẩu PostgreSQL, chỉ StatefulSet postgres đọc (Bài 19)
apiVersion: v1
kind: Secret
metadata:
name: postgres-secrets
namespace: taskflow
# ... label name=postgres-secrets, component=database, part-of=taskflow
type: Opaque
stringData:
# chỉ có tác dụng lần khởi tạo đầu tiên, khi volume còn trống
POSTGRES_PASSWORD: doi-mat-khau-postgres
# ... Secret redis-secrets (REDIS_PASSWORD: doi-mat-khau-redis) viết tương tự, dùng ở phần 4
File k8s/postgres.yaml mở đầu bằng Service postgres: clusterIP: None (headless), selector name: postgres + component: database, port 5432 tên postgres. Sau dấu --- là StatefulSet:
- k8s/postgres.yaml (phần StatefulSet)
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgres
namespace: taskflow
# ... label name=postgres, component=database, part-of=taskflow
spec:
# headless Service ở trên, cho Pod tên DNS cố định
serviceName: postgres
# một bản: thêm replica KHÔNG tạo cụm PostgreSQL (xem bài)
replicas: 1
selector:
matchLabels:
app.kubernetes.io/name: postgres
app.kubernetes.io/component: database
# PVC sinh từ volumeClaimTemplates được giữ lại cả khi xóa StatefulSet hay giảm replicas
persistentVolumeClaimRetentionPolicy:
whenDeleted: Retain
whenScaled: Retain
template:
# ... label của Pod, thêm app.kubernetes.io/version: "18"
spec:
# PostgreSQL cần thời gian ghi checkpoint khi tắt
terminationGracePeriodSeconds: 60
containers:
- name: postgres
image: postgres:18-alpine
imagePullPolicy: IfNotPresent
ports:
- name: postgres
containerPort: 5432
env:
- name: POSTGRES_USER
value: taskflow
- name: POSTGRES_DB
value: taskflow
# chỉ lấy đúng một key của Secret postgres-secrets (k8s/secret.yaml)
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: postgres-secrets
key: POSTGRES_PASSWORD
# PostgreSQL 18: gắn volume ở /var/lib/postgresql, dữ liệu nằm trong
# PGDATA=/var/lib/postgresql/18/docker (mặc định của image)
volumeMounts:
- name: data
mountPath: /var/lib/postgresql
resources:
requests:
cpu: 100m
memory: 256Mi
limits:
memory: 512Mi
# lần đầu chạy initdb: chờ tối đa 2 x 30 = 60 giây
startupProbe:
exec:
command: ["pg_isready", "-h", "127.0.0.1", "-U", "taskflow", "-d", "taskflow"]
periodSeconds: 2
failureThreshold: 30
# ... livenessProbe (10s, timeout 5s, 6 lần) và readinessProbe (5s, timeout 3s,
# 2 lần) dùng cùng lệnh pg_isready
# mỗi Pod một PVC riêng: data-postgres-0, data-postgres-1...
volumeClaimTemplates:
- metadata:
name: data
# ... label như trên
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
Trong đó:
serviceNametrỏ tới headless Service (Bài 12) lo tên DNS cho từng Pod.volumeClaimTemplateslà mẫu PVC: mỗi Pod được một PVC tên<template>-<tên Pod>, ở đâydata-postgres-0. 1Gi vừa với quotarequests.storage: 10Gicủa Bài 18.- Volume gắn ở
/var/lib/postgresqlchứ không phải.../datanhư bản cũ, đúng như bài Docker. PGDATA là thư mục con nên ổ cloud mới format cólost+foundở gốc cũng không làminitdbbáo thư mục không trống. - Probe dùng
execchạypg_isready: image distroless của TaskFlow không có shell nên Bài 15 phải dùnghttpGet, còn image PostgreSQL có đủ công cụ.-h 127.0.0.1bắt kiểm tra qua TCP, vì lúc khởi tạo lần đầu entrypoint chạy một server tạm chỉ nghe Unix socket. - Request 256Mi vượt mặc định của LimitRange (Bài 16) nên tự đặt limit 512Mi, dưới max 1Gi.
kubectl apply -f k8s/secret.yaml
# ...
# secret/postgres-secrets created
# secret/redis-secrets created
kubectl apply -f k8s/postgres.yaml
# service/postgres created
# statefulset.apps/postgres created
kubectl get statefulset,pvc
# NAME READY AGE
# statefulset.apps/postgres 1/1 40s
# ...
# persistentvolumeclaim/data-postgres-0 Bound pvc-c2ae99e0-b375-488a-90ea-8f1ce7902a8e 1Gi RWO standard <unset> 40s
# ...
Pod tên đúng postgres-0, Ready sau khoảng 18 giây (initdb rồi tới server thật), PVC data-postgres-0 do StatefulSet tạo và local-path cấp PV như Bài 18. Trong container, $PGDATA là /var/lib/postgresql/18/docker, thuộc uid 70 (postgres của image Alpine).
3. Danh tính của Pod trong StatefulSet.
Tên Pod cũng là hostname (hostname trong container in ra postgres-0), và nhờ headless Service, Pod có tên DNS riêng như Bài 12 đã nhắc trước:
kubectl exec postgres-0 -- nslookup postgres-0.postgres.taskflow.svc.cluster.local
# ...
# Name: postgres-0.postgres.taskflow.svc.cluster.local
# Address: 10.244.1.4
Cùng namespace thì gọi ngắn postgres-0.postgres. Pod còn có label statefulset.kubernetes.io/pod-name: postgres-0, tiện để chọn đúng một Pod. Ghi thử dữ liệu rồi xóa Pod:
kubectl exec postgres-0 -- psql -U taskflow -c "create table ghi_chu (noi_dung text); insert into ghi_chu values ('truoc khi xoa Pod');"
# CREATE TABLE
# INSERT 0 1
kubectl delete pod postgres-0
# pod "postgres-0" deleted from taskflow namespace
kubectl get pods -l app.kubernetes.io/name=postgres -o wide -w
# ...
# postgres-0 1/1 Running 0 3s 10.244.1.5 taskflow-worker2 <none> <none>
kubectl exec postgres-0 -- psql -U taskflow -c 'select * from ghi_chu;'
# ...
# truoc khi xoa Pod
# (1 row)
Pod mới vẫn tên postgres-0, vẫn ở taskflow-worker2 (node affinity của PV), gắn lại PVC data-postgres-0, nên log báo "Database directory appears to contain a database; Skipping initialization" và dữ liệu còn nguyên. Chỉ IP đổi, DNS tự cập nhật theo, vì vậy luôn gọi database bằng tên.
Thêm replica không tạo ra cụm PostgreSQL
kubectl scale statefulset postgres --replicas=3
# statefulset.apps/postgres scaled
kubectl get pods -l app.kubernetes.io/name=postgres -w
# ...
# postgres-1 1/1 Running 0 17s
# postgres-2 0/1 Pending 0 0s
# ...
kubectl exec postgres-1 -- psql -U taskflow -c 'select * from ghi_chu;'
# ERROR: relation "ghi_chu" does not exist
# ...
postgres-2 chỉ được tạo khi postgres-1 đã Ready (podManagementPolicy: OrderedReady, mặc định; Parallel thì tạo cùng lúc). Mỗi Pod có PVC riêng (data-postgres-1, data-postgres-2), nên postgres-1 là một database trống: StatefulSet chỉ cho tên, volume và thứ tự, không biết gì về replication của PostgreSQL. Tệ hơn, nslookup postgres giờ trả về ba IP, ứng dụng gọi postgres sẽ ghi vào ba database khác nhau.
Muốn có primary, replica và tự chuyển primary khi lỗi thì cần một operator như CloudNativePG: nó thêm resource Cluster, lo streaming replication, failover, backup, tạo Service -rw trỏ tới primary và -ro tới replica. Series giữ replicas: 1.
Giảm lại bằng kubectl scale statefulset postgres --replicas=1: Pod bị xóa theo thứ tự ngược (postgres-2 trước), còn PVC ở lại, phải tự xóa bằng kubectl delete pvc data-postgres-1 data-postgres-2. Đó là persistentVolumeClaimRetentionPolicy: whenScaled (giảm replicas) và whenDeleted (xóa StatefulSet) mặc định đều là Retain, mình ghi rõ trong file. Đặt Delete thì PVC mất theo, kéo theo dữ liệu (reclaim policy Delete). Đổi Pod template (VD image mới) thì StatefulSet cập nhật từng Pod một, từ số lớn về 0. Xong thì xóa bảng thử: kubectl exec postgres-0 -- psql -U taskflow -c 'drop table ghi_chu;'.
4. Redis bằng Deployment.
TaskFlow dùng Redis cho cache, rate limit, realtime và hàng đợi job (bài hàng đợi job với Redis của series Golang). Một Redis đơn không cần danh tính hay thứ tự nên Deployment là đủ. Cache mất không sao nhưng job đang chờ thì không, nên mình bật AOF như compose của series Golang và đặt /data trên PVC redis-data (1Gi) thay vì emptyDir. File k8s/redis.yaml gồm PVC đó, Deployment và Service ClusterIP redis port 6379, label component: cache:
- k8s/redis.yaml (phần Deployment, lược bớt)
# dừng Pod cũ rồi mới tạo Pod mới: không bao giờ có hai Redis cùng ghi một file AOF
strategy:
type: Recreate
# ...
- name: redis
image: redis:8-alpine
# $(REDIS_PASSWORD) được Kubernetes thay bằng giá trị biến môi trường bên dưới
args:
- redis-server
- --appendonly
- "yes"
- --maxmemory
- 128mb
- --maxmemory-policy
- noeviction
- --requirepass
- $(REDIS_PASSWORD)
env:
- name: REDIS_PASSWORD
valueFrom:
secretKeyRef:
name: redis-secrets
key: REDIS_PASSWORD
# ... REDISCLI_AUTH cùng secretKeyRef: redis-cli tự đọc mật khẩu từ biến này
# ... volumeMounts: data → /data (PVC redis-data)
resources:
requests:
cpu: 50m
memory: 64Mi
# lớn hơn maxmemory 128mb để còn chỗ cho buffer, AOF rewrite
limits:
memory: 256Mi
# redis-cli trả exit 0 cả khi báo lỗi (NOAUTH...), nên phải kiểm tra chữ PONG
readinessProbe:
exec:
command: ["sh", "-c", "redis-cli ping | grep -q PONG"]
# ... livenessProbe cùng lệnh
strategy: Recreate: rolling update tạo Pod mới khi Pod cũ còn chạy, mà RWO trên local-path cho hai Pod cùng node gắn chung (Bài 18), tức hai Redis cùng ghi một AOF.Recreatexóa Pod cũ trước, đổi lại vài giây không có Redis.$(TÊN)trongargshaycommandđược thay bằng biến môi trường của container: image Redis không đọc mật khẩu từ biến môi trường như PostgreSQL, nên truyền qua tham số mà mật khẩu vẫn nằm trong Secret.noeviction: Redis đầy thì lệnh ghi báo lỗi chứ không tự xóa job; limit 256Mi cao hơnmaxmemoryđể Redis tự từ chối ghi trước khi bị OOMKilled.
kubectl apply -f k8s/redis.yaml
# persistentvolumeclaim/redis-data created
# deployment.apps/redis created
# service/redis created
kubectl exec deploy/redis -- redis-cli ping
# PONG
Thử redis-cli -a sai ping thì nhận NOAUTH Authentication required. mà exit code vẫn là 0, vì vậy probe phải grep chữ PONG. Mật khẩu không lộ qua ps (Redis đổi tên tiến trình thành redis-server *:6379), kubectl get pod -o yaml cũng chỉ thấy $(REDIS_PASSWORD). Thử Recreate và AOF: ghi một key rồi apply một thay đổi Pod template (mình sửa probe):
kubectl exec deploy/redis -- redis-cli set bai 19
# OK
kubectl apply -f k8s/redis.yaml && kubectl get pods -l app.kubernetes.io/name=redis -w
# ...
# redis-657ddb86dc-ktp9p 1/1 Terminating 0 26s
# redis-657ddb86dc-ktp9p 0/1 Completed 0 26s
# redis-7469dd4fc7-c7d7v 0/1 Pending 0 0s
# ...
kubectl exec deploy/redis -- redis-cli get bai
# 19
Pod cũ dừng hẳn rồi Pod mới mới được tạo, đọc lại AOF trên PVC nên key vẫn còn (xóa bằng redis-cli del bai).
5. Nối TaskFlow với PostgreSQL và Redis.
DATABASE_URL và TASKFLOW_REDIS_URL chứa mật khẩu nên thuộc taskflow-secrets, như đã định từ Bài 13. Host là tên Service ngắn cùng namespace:
- k8s/secret.yaml (thêm vào stringData của taskflow-secrets)
# PostgreSQL và Redis (Bài 19): mật khẩu phải trùng với postgres-secrets, redis-secrets bên dưới
DATABASE_URL: postgres://taskflow:doi-mat-khau-postgres@postgres:5432/taskflow?sslmode=disable
TASKFLOW_REDIS_URL: redis://:doi-mat-khau-redis@redis:6379/0
Mật khẩu giờ ở hai chỗ, đổi chỗ này phải đổi chỗ kia; Kustomize (Bài 22) và Helm (Bài 24) giúp sinh chúng từ một nguồn. Biến từ envFrom không tự cập nhật (Bài 14) nên phải restart Deployment:
kubectl apply -f k8s/secret.yaml
# secret/taskflow-secrets configured
# ...
kubectl rollout restart deploy/taskflow-api
# deployment.apps/taskflow-api restarted
kubectl get pods -l app.kubernetes.io/name=taskflow-api
# NAME READY STATUS RESTARTS AGE
# taskflow-api-5f676d5d57-dbmpj 0/1 CrashLoopBackOff 3 (4s ago) 40s
# taskflow-api-758876d677-vnn6s 1/1 Running 0 5m24s
kubectl logs taskflow-api-5f676d5d57-dbmpj | tail -1
# {"time":"2026-11-24T14:33:21.102147875Z","level":"ERROR","msg":"server dừng vì lỗi","err":"khởi tạo store: database còn migration chưa chạy, hãy chạy với -migrate trước"}
TaskFlow kết nối được nhưng từ chối chạy khi schema cũ hơn code. Nhờ maxUnavailable: 0 (Bài 10) và readiness probe, Pod cũ vẫn phục vụ trong lúc Pod mới crash.
Chạy migration bằng một Pod
Migration là lệnh /api -migrate của cùng image (bài migration với goose của series Golang), chỉ cần DATABASE_URL. Tạm thời chạy nó bằng một Pod (file ngoài repo):
- thu-migrate.yaml
apiVersion: v1
kind: Pod
metadata:
name: taskflow-migrate
namespace: taskflow
labels:
app.kubernetes.io/name: taskflow-migrate
app.kubernetes.io/component: migration
app.kubernetes.io/part-of: taskflow
spec:
# chạy một lần: xong (hay lỗi) thì thôi, không khởi động lại
restartPolicy: Never
containers:
- name: migrate
image: taskflow-api:0.53.0
imagePullPolicy: IfNotPresent
# entrypoint của image là /api, thêm cờ -migrate
args: ["-migrate"]
# chỉ cần DATABASE_URL
envFrom:
- secretRef:
name: taskflow-secrets
kubectl apply -f thu-migrate.yaml
# pod/taskflow-migrate created
kubectl wait --for=jsonpath='{.status.phase}'=Succeeded pod/taskflow-migrate --timeout=60s
# pod/taskflow-migrate condition met
kubectl logs taskflow-migrate | tail -2
# time=2026-11-24T14:33:34.715Z level=INFO msg="đã chạy migration" file=00007_task_reminders.sql duration=6.299632ms
# time=2026-11-24T14:33:34.715Z level=INFO msg="database đã ở phiên bản mới nhất" version=7
kubectl rollout status deploy/taskflow-api
# ...
# deployment "taskflow-api" successfully rolled out
kubectl delete pod taskflow-migrate
# pod "taskflow-migrate" deleted from taskflow namespace
Pod mới tự lên ở lần khởi động lại kế tiếp của CrashLoopBackOff (log có "đã kết nối PostgreSQL", "đã kết nối Redis", "hàng đợi job trong Redis (asynq)"), rồi rollout xóa Pod cũ. Pod chạy tay phải nhớ chạy mỗi lần lên version, lỗi thì không ai chạy lại; Bài 20 sẽ chuyển nó thành Job. Trên cụm mới, apply -f k8s/ xong thì các Pod taskflow-api cũng đứng CrashLoopBackOff tới khi chạy migration, README của repo ghi lại thứ tự này.
6. TaskFlow chạy đầy đủ.
Dữ liệu đã nằm trong PostgreSQL, Pod nào trả lời cũng như nhau, nên đổi replicas: 1 trong k8s/deployment.yaml thành replicas: 3 như Bài 18 đã hẹn (comment đổi theo):
kubectl apply -f k8s/deployment.yaml && kubectl rollout status deploy/taskflow-api
# deployment.apps/taskflow-api configured
# ...
# deployment "taskflow-api" successfully rolled out
kubectl get pods -o wide cho thấy ba Pod API cùng ở taskflow-worker, node chứa PV upload, còn postgres-0 ở taskflow-worker2. Mỗi Pod mở tối đa 25 kết nối database, ba Pod là 75, dưới max_connections mặc định 100; autoscale (Bài 25) phải tính tới điều này. Gọi thử qua Gateway với dòng 127.0.0.1 taskflow.local trong /etc/hosts như Bài 17; không sửa được file đó thì thêm --resolve taskflow.local:8080:127.0.0.1 vào mỗi lệnh curl:
API=http://taskflow.local:8080/api/v1
curl -s -X POST $API/auth/register -H "Content-Type: application/json" -d '{"email":"[email protected]","name":"An","password":"doi-mat-khau-nay"}'
# {"id":1,"email":"[email protected]","name":"An","created_at":"2026-11-24T14:34:39.837845Z"}
TOKEN=$(curl -s -X POST $API/auth/login -H "Content-Type: application/json" -d '{"email":"[email protected]","password":"doi-mat-khau-nay"}' | grep -o '"access_token":"[^"]*"' | cut -d'"' -f4)
curl -s -X POST $API/projects -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d '{"name":"Kubernetes"}'
# {"id":1,"name":"Kubernetes","owner_id":1}
curl -s -X POST $API/tasks -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d '{"project_id":1,"title":"Chay PostgreSQL bang StatefulSet"}'
# {"id":1,"project_id":1,"title":"Chay PostgreSQL bang StatefulSet","status":"todo"}
Ở Bài 18 các bước này rơi vào các Pod khác nhau và hỏng; giờ ba Pod dùng chung database. Đăng nhập thêm vài lần để thấy Redis làm việc:
for i in 1 2 3 4 5 6; do curl -s -X POST $API/auth/login -H "Content-Type: application/json" -d '{"email":"[email protected]","password":"doi-mat-khau-nay"}' | cut -c1-40; echo; done
# {"access_token":"eyJhbGciOiJIUzI1NiIsInR
# ...
# {"access_token":"eyJhbGciOiJIUzI1NiIsInR
# {"error":"quá nhiều request, hãy thử lại
# {"error":"quá nhiều request, hãy thử lại
kubectl logs -l app.kubernetes.io/name=taskflow-api --tail=-1 --prefix | grep /auth/login | sed -E 's/^.pod.([^/]*).*"status":([0-9]+).*/\1 \2/'
# taskflow-api-5f676d5d57-85c2p 200
# taskflow-api-5f676d5d57-85c2p 200
# taskflow-api-5f676d5d57-dbmpj 200
# taskflow-api-5f676d5d57-dbmpj 429
# taskflow-api-5f676d5d57-njkzm 200
# taskflow-api-5f676d5d57-njkzm 200
# taskflow-api-5f676d5d57-njkzm 429
Giới hạn 5 lần đăng nhập mỗi 10 phút cho một email (bài rate limiting của series Golang) được đếm trong Redis: tính cả lần lấy TOKEN, lần thứ sáu bị chặn dù rơi vào Pod khác. Không có Redis, mỗi Pod đếm riêng, người dùng được thử gấp ba. (Email này phải chờ 10 phút mới đăng nhập lại được; $TOKEN sống 15 phút.) Giờ xóa Pod database:
kubectl delete pod postgres-0 && kubectl wait --for=condition=Ready pod/postgres-0 --timeout=90s
# pod "postgres-0" deleted from taskflow namespace
# pod/postgres-0 condition met
curl -s $API/tasks -H "Authorization: Bearer $TOKEN"
# {"data":[{"id":1,"project_id":1,"title":"Chay PostgreSQL bang StatefulSet","status":"todo"}]}
Khi database ngừng hẳn
Từ khi có DATABASE_URL, /ready của TaskFlow ping database (Bài 15). Tắt PostgreSQL bằng cách giảm StatefulSet về 0:
kubectl scale statefulset postgres --replicas=0
# statefulset.apps/postgres scaled
kubectl wait --for=condition=Ready=false pod -l app.kubernetes.io/name=taskflow-api --timeout=60s
# pod/taskflow-api-5f676d5d57-85c2p condition met
# ...
kubectl get endpointslice -l kubernetes.io/service-name=taskflow-api -o jsonpath='{range .items[*].endpoints[*]}{.addresses[0]} {.conditions}{"\n"}{end}'
# 10.244.2.10 {"ready":false,"serving":false,"terminating":false}
# 10.244.2.11 {"ready":false,"serving":false,"terminating":false}
# 10.244.2.12 {"ready":false,"serving":false,"terminating":false}
curl -si http://taskflow.local:8080/api/v1/tasks
# HTTP/1.1 503 Service Unavailable
# ...
# no available server
Readiness probe nhận 503 "database không phản hồi", cả ba Pod 0/1, mọi endpoint ready: false, và Traefik tự trả 503 no available server (không có X-Request-Id). Traefik cập nhật chậm vài giây: curl ngay sau kubectl wait vẫn tới được TaskFlow. Liveness hỏi /health, không đụng database, nên RESTARTS không tăng.
Bật lại bằng kubectl scale statefulset postgres --replicas=1: vài giây sau ba Pod Ready, curl $API/tasks trả lại task cũ, không Pod API nào phải khởi động lại. Quota lúc này: 5/20 Pod, 3/10 PVC, 3Gi storage, requests.memory 512Mi, limits.memory 1152Mi. kubectl diff -f k8s/ trả exit 0. Các bạn có thể xem thêm về StatefulSet tại đây.
Code đầy đủ của series sau bài này nằm ở tag bai-19 trên GitHub; các thay đổi của riêng bài này: so sánh bai-18...bai-19.
7. Lời kết.
Như vậy mình đã giới thiệu với mọi người về StatefulSet: headless Service và tên postgres-0.postgres, volumeClaimTemplates, thứ tự tạo và xóa Pod, persistentVolumeClaimRetentionPolicy, vì sao thêm replica không tạo ra cụm PostgreSQL, Redis bằng Deployment với Recreate, và TaskFlow lần đầu chạy đầy đủ với ba replica. Bài sau chúng ta sẽ tìm hiểu Job và CronJob trong Kubernetes: chuyển Pod migration chạy tay ở bài này thành Job, và backup database định kỳ bằng CronJob.
Đă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