StatefulSet: chạy PostgreSQL trên Kubernetes
Bài PersistentVolume, PersistentVolumeClaim và StorageClass kết thúc với Postgres chạy bằng Deployment + PVC: dữ liệu đã bền, nhưng rolling update có thể kẹt, scale lên là hỏng dữ liệu, và Pod không có danh tính ổn định. Bài này giới thiệu StatefulSet, workload controller dành cho ứng dụng có trạng thái: tên Pod cố định, mỗi Pod một PVC riêng, DNS riêng cho từng Pod qua headless Service, triển khai và cập nhật có thứ tự. Sau đó bạn thay Postgres của notes-api bằng một StatefulSet hoàn chỉnh, kiểm chứng danh tính và dữ liệu, rồi tìm hiểu vì sao scale StatefulSet không tạo ra cụm database, cách sao lưu, và những cái bẫy khi vận hành.
Vì sao cần StatefulSet
Với Compose, một service database thường có container_name: postgres và một named volume: tên cố định, ổ đĩa cố định, trên một máy. Ứng dụng có trạng thái trong cluster cần đúng những thứ đó, nhân lên cho nhiều thành viên:
- Danh tính mạng ổn định và duy nhất: thành viên số 0 luôn tên
postgres-0, được gọi bằng một tên DNS riêng, kể cả sau khi bị tạo lại ở node khác. - Lưu trữ ổn định cho từng thành viên:
postgres-0luôn gắn với ổ đĩa củapostgres-0, không bao giờ của ai khác. - Thứ tự: khởi động, dừng, cập nhật từng thành viên một theo thứ tự xác định (cụm database thường cần primary lên trước replica).
| Deployment | StatefulSet | |
|---|---|---|
| Tên Pod | Ngẫu nhiên (postgres-6b9f8d7c5d-q2w8x) | Theo số thứ tự (postgres-0, postgres-1) |
| Lưu trữ | Mọi Pod dùng chung PVC khai báo trong template | Mỗi Pod một PVC riêng từ volumeClaimTemplates |
| DNS | Chỉ có tên Service | Thêm tên riêng cho từng Pod qua headless Service |
| Thay Pod bị xóa | Tạo Pod mới ngay, kể cả khi Pod cũ còn Terminating | Chỉ tạo lại khi Pod cũ đã biến mất hẳn |
| Thứ tự | Không có | Tạo 0 → N-1, xóa và cập nhật N-1 → 0 |
Cơ chế
Danh tính theo số thứ tự
StatefulSet postgres với replicas: 3 tạo postgres-0, postgres-1, postgres-2. Mỗi Pod có thêm label statefulset.kubernetes.io/pod-name: postgres-0... Khi postgres-1 bị xóa hoặc node của nó chết, Pod được tạo lại cùng tên, gắn cùng PVC. IP thì vẫn có thể đổi: danh tính nằm ở tên và DNS, không ở IP.
Khác biệt quan trọng nhất với Deployment là ngữ nghĩa "nhiều nhất một" (at most one): StatefulSet không bao giờ tạo postgres-0 mới khi postgres-0 cũ còn tồn tại, kể cả đang Terminating. Hai Pod cùng danh tính chạy song song (cùng ghi một ổ đĩa) là thứ một database không được phép gặp.
volumeClaimTemplates: mỗi Pod một PVC
Mỗi phần tử trong volumeClaimTemplates sinh ra một PVC cho mỗi Pod, tên <tên template>-<tên StatefulSet>-<số thứ tự>: data-postgres-0, data-postgres-1. Nếu PVC trùng tên đã tồn tại, StatefulSet dùng luôn nó: đây là cách Pod tạo lại tìm lại đúng dữ liệu của mình.
Mặc định PVC được giữ lại khi Pod bị xóa, khi scale xuống, và cả khi xóa StatefulSet: Kubernetes chọn an toàn cho dữ liệu. Trường persistentVolumeClaimRetentionPolicy đổi được hành vi này:
persistentVolumeClaimRetentionPolicy:
whenDeleted: Retain # xóa StatefulSet: giữ PVC (Delete = xóa theo)
whenScaled: Retain # scale xuống: giữ PVC của Pod bị bỏ (Delete = xóa theo)Headless Service và DNS từng Pod
StatefulSet bắt buộc có serviceName trỏ tới một headless Service (clusterIP: None) mà bạn tự tạo (bài Service: ClusterIP, NodePort, LoadBalancer và headless). Nhờ nó, CoreDNS tạo bản ghi riêng cho từng Pod:
postgres-0.postgres.notes.svc.cluster.local -> IP hiện tại của postgres-0
postgres.notes.svc.cluster.local -> IP của mọi Pod đang ReadyTrong cùng namespace, chỉ cần viết postgres-0.postgres. Mặc định chỉ Pod Ready mới có bản ghi; ứng dụng cần các thành viên tìm thấy nhau trước khi Ready thì đặt publishNotReadyAddresses: true cho Service.
podManagementPolicy: thứ tự tạo và xóa
OrderedReady(mặc định): tạopostgres-0, đợi nó Running và Ready, rồi mới tạopostgres-1... Scale xuống thì xóa từ số lớn nhất về. Một Pod không khỏe là mọi thao tác dừng lại.Parallel: tạo và xóa đồng loạt, không chờ nhau. Hợp với ứng dụng chỉ cần danh tính và ổ đĩa riêng, không cần thứ tự. Chỉ ảnh hưởng scale, không ảnh hưởng cập nhật.
Trường này chỉ đặt được lúc tạo StatefulSet.
updateStrategy: cập nhật có kiểm soát
RollingUpdate(mặc định): khi template đổi, cập nhật từng Pod một từ số lớn nhất về 0, đợi Pod vừa cập nhật Ready rồi mới sang Pod tiếp theo. Với cụm database, replica (số lớn) được cập nhật trước, primary (-0) sau cùng.partition: chỉ Pod có số thứ tự ≥ partition được cập nhật. Với 3 replica vàpartition: 2, chỉpostgres-2lên bản mới: một kiểu canary. Hạ dần partition về 0 để cập nhật nốt.OnDelete: controller không tự cập nhật; Pod chỉ nhận template mới khi bạn xóa nó. Hợp khi cần kiểm soát hoàn toàn (thường do operator đảm nhận).
updateStrategy:
type: RollingUpdate
rollingUpdate:
partition: 2Thực hành: Postgres của notes-api bằng StatefulSet
Headless hay ClusterIP cho tên postgres?
Phải giữ tên Service postgres để DATABASE_URL của notes-api (postgres://notes:...@postgres:5432/notes) không đổi. Có hai cách:
- Biến
postgresthành headless và dùng nó làmserviceName. Tênpostgresphân giải thẳng ra IP của Pod Ready, có thêmpostgres-0.postgres. Một Service, đơn giản. - Giữ
postgreslà ClusterIP cho client và thêm một Service headless riêng (ví dụpostgres-headless) làmserviceName.
Với một instance, ta chọn cách 1. Cái giá: không còn IP ảo cố định. Khi Pod được tạo lại với IP mới, client phải phân giải DNS lại; driver pg của Node.js phân giải mỗi lần mở kết nối mới nên pool tự hồi phục, nhưng ứng dụng nào cache DNS mãi mãi sẽ gặp lỗi. Lúc Pod chưa Ready, tên postgres không phân giải được (lỗi DNS) thay vì báo từ chối kết nối. Khi có nhiều thành viên (primary + replica), người ta dùng nhiều Service kiểu cách 2: postgres-rw trỏ primary, postgres-ro trỏ replica.
Manifest
apiVersion: v1
kind: Service
metadata:
name: postgres
namespace: notes
labels:
app: postgres
spec:
clusterIP: None # headless
selector:
app: postgres
ports:
- name: postgres
port: 5432
targetPort: 5432
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgres
namespace: notes
labels:
app: postgres
spec:
serviceName: postgres
replicas: 1
selector:
matchLabels:
app: postgres
persistentVolumeClaimRetentionPolicy:
whenDeleted: Retain
whenScaled: Retain
template:
metadata:
labels:
app: postgres
spec:
terminationGracePeriodSeconds: 60
containers:
- name: postgres
image: postgres:18
ports:
- name: postgres
containerPort: 5432
envFrom:
- secretRef:
name: notes-db # POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_DB
readinessProbe:
exec:
command: ["sh", "-c", "pg_isready -h 127.0.0.1 -U \"$POSTGRES_USER\" -d \"$POSTGRES_DB\""]
periodSeconds: 5
failureThreshold: 3
resources:
requests:
cpu: 250m
memory: 256Mi
limits:
memory: 512Mi
volumeMounts:
- name: data
mountPath: /var/lib/postgresql
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: standard
resources:
requests:
storage: 1GiVài quyết định đáng chú ý:
pg_isready -h 127.0.0.1: lần chạy đầu, entrypoint của image chạyinitdbvới một server tạm chỉ nghe Unix socket. Kiểm tra qua TCP nên Pod chỉ Ready khi server thật đã lên, không Ready "nhầm" giữa lúc khởi tạo.- Không đặt livenessProbe gắt: khởi động lại Postgres giữa lúc nó đang khôi phục sau sự cố (crash recovery) chỉ làm mọi chuyện tệ hơn. Readiness đủ để Service không gửi kết nối tới Pod chưa sẵn sàng.
terminationGracePeriodSeconds: 60: cho Postgres đủ thời gian dừng sạch (checkpoint) trước khi bị SIGKILL.limits.memorychặn Postgres ăn hết RAM của node; không đặt limit CPU để tránh bị bóp hiệu năng (chương 9).
Chuyển dữ liệu từ Deployment sang StatefulSet
StatefulSet tạo PVC mới data-postgres-0, không dùng postgres-data của bài trước. Sao lưu trước, khôi phục sau:
kubectl -n notes exec deploy/postgres -- pg_dump -U notes -d notes > notes-backup.sql
kubectl -n notes delete deployment postgres
kubectl -n notes delete service postgres
kubectl apply -f postgres-statefulset.yaml
kubectl -n notes rollout status statefulset/postgres
kubectl -n notes get statefulset,pod,pvc -l app=postgresdeployment.apps "postgres" deleted
service "postgres" deleted
service/postgres created
statefulset.apps/postgres created
Waiting for 1 pods to be ready...
statefulset rolling update complete 1 pods at revision postgres-7d4b9c8f6d...
NAME READY AGE
statefulset.apps/postgres 1/1 35s
NAME READY STATUS RESTARTS AGE
pod/postgres-0 1/1 Running 0 35s
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS VOLUMEATTRIBUTESCLASS AGE
persistentvolumeclaim/data-postgres-0 Bound pvc-8a1e4c2b-6d3f-4e9a-b7c5-1f2e3d4c5b6a 1Gi RWO standard <unset> 35sPhải xóa Service cũ vì spec.clusterIP là trường bất biến: không thể sửa một ClusterIP Service thành headless bằng kubectl apply. Khôi phục dữ liệu (kết quả từng câu lệnh trong file dump được bỏ đi, lỗi vẫn hiện ra) và khởi động lại notes-api để pool kết nối làm mới:
kubectl -n notes exec -i postgres-0 -- psql -q -U notes -d notes < notes-backup.sql > /dev/null
kubectl -n notes exec postgres-0 -- psql -U notes -d notes -c "SELECT * FROM ghi_chu;"
kubectl -n notes rollout restart deploy/notes-api id | noi_dung
----+---------------------------
1 | Dữ liệu này phải sống sót
(1 row)
deployment.apps/notes-api restartedKiểm tra xong thì xóa PVC cũ: kubectl -n notes delete pvc postgres-data. Đồng thời xóa phần Postgres (Deployment và Service) khỏi deps-dev.yaml, chỉ giữ Namespace và Redis; nếu không, lần kubectl apply -f deps-dev.yaml sau sẽ tạo lại Deployment postgres có cùng label app: postgres và Pod của nó lọt vào Service. Từ đây Postgres sống trong postgres-statefulset.yaml.
Kiểm tra DNS và danh tính
kubectl -n notes run dns-test --rm -it --restart=Never --image=busybox:1.37 -- nslookup postgres-0.postgres.notes.svc.cluster.localServer: 10.96.0.10
Address: 10.96.0.10:53
Name: postgres-0.postgres.notes.svc.cluster.local
Address: 10.244.2.21
pod "dns-test" deletedGiờ xóa Pod và quan sát:
kubectl -n notes get pod -l app=postgres -w
# terminal khác:
kubectl -n notes delete pod postgres-0NAME READY STATUS RESTARTS AGE
postgres-0 1/1 Running 0 12m
postgres-0 1/1 Terminating 0 12m
postgres-0 0/1 Terminating 0 12m
postgres-0 0/1 Pending 0 0s
postgres-0 0/1 ContainerCreating 0 0s
postgres-0 0/1 Running 0 2s
postgres-0 1/1 Running 0 7sSo với Deployment ở chương 4: Pod mới chỉ xuất hiện sau khi Pod cũ biến mất hẳn, và mang đúng tên cũ. Chạy lại câu SELECT ở trên: dữ liệu vẫn còn, vì postgres-0 mới gắn lại data-postgres-0.
Scale StatefulSet không tạo ra cụm database
kubectl -n notes scale statefulset postgres --replicas=3
kubectl -n notes rollout status statefulset/postgres
kubectl -n notes exec postgres-1 -- psql -U notes -d notes -c "SELECT count(*) FROM ghi_chu;"statefulset.apps/postgres scaled
statefulset rolling update complete 3 pods at revision postgres-7d4b9c8f6d...
ERROR: relation "ghi_chu" does not exist
LINE 1: SELECT count(*) FROM ghi_chu;
^
command terminated with exit code 1postgres-1 và postgres-2 là hai database độc lập, trống trơn, mỗi cái một PVC riêng. Tệ hơn, tên headless postgres giờ trả về 3 IP, nên notes-api nối ngẫu nhiên vào 3 database khác nhau. StatefulSet chỉ cho danh tính và ổ đĩa; nhân bản dữ liệu là việc của chính phần mềm (streaming replication của Postgres, cấu hình primary/replica, failover...). Đưa về như cũ và dọn PVC thừa (bị giữ lại vì whenScaled: Retain):
kubectl -n notes scale statefulset postgres --replicas=1
kubectl -n notes delete pvc data-postgres-1 data-postgres-2Operator hoặc database được quản lý
Muốn Postgres có replica, tự failover, backup liên tục, đừng tự viết script quanh StatefulSet. Có hai hướng:
- Operator (chương 14): phần mềm chạy trong cluster, hiểu Postgres và tự vận hành nó. CloudNativePG là lựa chọn phổ biến: bạn khai báo một đối tượng
Cluster(postgresql.cnpg.io/v1) vớiinstances: 3, operator dựng primary và replica, tạo Service<tên>-rw/<tên>-ro, tự chuyển primary khi node chết, sao lưu lên object storage. - Database được quản lý (Amazon RDS, Google Cloud SQL, Azure Database for PostgreSQL): nhà cung cấp lo replica, backup, vá lỗi. Ứng dụng trong cluster chỉ cần
DATABASE_URL. Với nhiều team, đây là lựa chọn ít rủi ro nhất.
| StatefulSet tự viết | Operator (CloudNativePG) | Database được quản lý | |
|---|---|---|---|
| Nhân bản, failover | Tự làm | Có | Có |
| Backup, khôi phục theo thời điểm | Tự làm | Có | Có |
| Chi phí vận hành | Cao | Trung bình | Thấp (tốn tiền hơn) |
| Hợp với | Học, môi trường dev | Cần chạy trong cluster | Phần lớn production |
Sao lưu
PVC bền không phải là backup: xóa nhầm bảng, xóa nhầm PVC, hỏng ổ đĩa đều làm mất dữ liệu. Tối thiểu nên có:
- Backup logic định kỳ bằng CronJob (bài DaemonSet, Job và CronJob):
apiVersion: batch/v1
kind: CronJob
metadata:
name: postgres-backup
namespace: notes
spec:
schedule: "0 2 * * *"
concurrencyPolicy: Forbid
jobTemplate:
spec:
backoffLimit: 2
template:
spec:
restartPolicy: OnFailure
containers:
- name: pg-dump
image: postgres:18
envFrom:
- secretRef:
name: notes-db
command: ["sh", "-c"]
args:
- PGPASSWORD="$POSTGRES_PASSWORD" pg_dump -h postgres-0.postgres -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Fc -f /backup/notes-$(date +%F).dump
volumeMounts:
- name: backup
mountPath: /backup
volumes:
- name: backup
persistentVolumeClaim:
claimName: postgres-backup # PVC tạo riêng như bài trướcTrên production, đẩy file dump lên object storage (S3, GCS) ngoài cluster: backup nằm cùng chỗ với dữ liệu thì chết cùng dữ liệu.
- VolumeSnapshot nếu CSI driver hỗ trợ: nhanh, nhưng chỉ crash-consistent và thường nằm cùng hạ tầng.
- Thử khôi phục định kỳ. Backup chưa từng được khôi phục thử thì chưa chắc là backup.
Bẫy thường gặp
1. Xóa PVC hoặc namespace
kubectl delete statefulset postgresgiữ PVC, nhưngkubectl delete pvc data-postgres-0haykubectl delete namespace notesthì xóa luôn ổ đĩa nếu reclaim policy làDelete.- Cách phòng: StorageClass
Retaincho dữ liệu thật, backup ngoài cluster, cẩn thận với lệnh xóa namespace.
2. Node chết, Pod kẹt mãi
- Triệu chứng: node chứa
postgres-0mất liên lạc; sau vài phút Pod thànhTerminating(hoặcUnknown) và không có Pod thay thế. - Nguyên nhân: ngữ nghĩa "nhiều nhất một". Kubelet không còn để xác nhận container đã dừng, nên StatefulSet không dám tạo
postgres-0mới. Với local-path, dữ liệu lại nằm ngay trên node đó nên không thể dời đi. - Cách xử lý (với đĩa mạng): xác nhận máy đã thật sự tắt, rồi gắn taint
node.kubernetes.io/out-of-service=nodeshutdown:NoExecutecho node (Kubernetes xóa Pod và tháo volume), hoặc xóa đối tượng Node, hoặckubectl delete pod postgres-0 --force --grace-period=0.
CAUTION
Force delete chỉ xóa bản ghi trong API server, không dừng được container trên node mất liên lạc. Nếu node thật ra vẫn sống (chỉ đứt mạng), bạn sẽ có hai postgres-0 cùng ghi vào một ổ đĩa: hỏng dữ liệu. Luôn chắc chắn máy cũ đã tắt (fencing) trước khi force.
3. Rolling update hỏng và kẹt
- Triệu chứng: đổi image sai (
postgres:18-typo),postgres-0kẹtImagePullBackOff; sửa lại template đúng mà Pod vẫn kẹt. - Nguyên nhân: với
OrderedReady, StatefulSet chờ Pod lỗi Ready rồi mới đi tiếp, kể cả khi bạn đã quay lại template cũ. - Cách sửa: sau khi sửa template, xóa Pod đang kẹt để nó được tạo lại theo template đúng.
4. Sửa volumeClaimTemplates bị từ chối
- Triệu chứng: tăng
storagetrong template rồi apply, nhận lỗiupdates to statefulset spec for fields other than ... are forbidden. - Cách làm: tăng dung lượng từng PVC (
kubectl patch pvc data-postgres-0 ..., class phải cho phép); muốn template khớp cho Pod tương lai,kubectl delete statefulset postgres --cascade=orphan(giữ Pod và PVC) rồi apply manifest mới.
5. Thiếu headless Service hoặc serviceName sai
- Triệu chứng: Pod chạy nhưng
postgres-0.postgreskhông phân giải được. - Cách sửa: tạo Service
clusterIP: Nonecó selector khớp label Pod và tên đúng bằngserviceName.
Tóm tắt
- StatefulSet cho mỗi Pod danh tính ổn định: tên theo số thứ tự (
postgres-0), PVC riêng từvolumeClaimTemplates(data-postgres-0), DNS riêngpostgres-0.postgres.notes.svc.cluster.localqua headless Service bắt buộc. - Ngữ nghĩa "nhiều nhất một": không tạo Pod mới khi Pod cũ cùng tên còn tồn tại.
- PVC được giữ khi xóa Pod, scale xuống hay xóa StatefulSet; đổi bằng
persistentVolumeClaimRetentionPolicy. podManagementPolicy:OrderedReady(mặc định, tuần tự) hoặcParallel.updateStrategy:RollingUpdatetừ số lớn về 0, cópartition; hoặcOnDelete.- notes-api: Service
postgresthành headless để giữ nguyênDATABASE_URL; đổi ClusterIP sang headless phải xóa Service cũ; chuyển dữ liệu bằngpg_dump/psql; bỏ Postgres khỏideps-dev.yaml. - Readiness
pg_isready -h 127.0.0.1, córesources, không đặt liveness gắt, volume tại/var/lib/postgresql. - Scale StatefulSet chỉ tạo thêm database độc lập; nhân bản là việc của phần mềm. Cần HA thì dùng operator (CloudNativePG) hoặc database được quản lý.
- Backup bằng CronJob
pg_dumpđẩy ra ngoài cluster, thêm VolumeSnapshot nếu có, và thử khôi phục định kỳ. - Node chết với RWO: Pod kẹt là có chủ đích; chỉ force delete hay dùng taint
out-of-servicekhi chắc chắn máy cũ đã tắt.
Comments