Bài tập lớn: Đưa ứng dụng của bạn lên Kubernetes
Bài dự án tổng kết dắt bạn đi từng bước. Bài tập lớn này thì không: bạn tự thiết kế, tự viết và tự triển khai một hệ thống đạt chuẩn production trên cluster hoc-k8s, rồi tự chấm bằng bảng tiêu chí ở cuối đề. Đây là bài tập mở: không có chấm tự động. Lời giải mẫu dành cho biến thể B (notes-api + worker); nếu chọn biến thể A, dùng nó làm tài liệu đối chiếu.
Kết quả cuối cùng là một repo git mà người khác clone về, đọc README và dựng lại được toàn bộ hệ thống trên một cluster trống. Đó cũng là thứ đáng đưa vào hồ sơ xin việc nhất của cả khóa học.
Chọn biến thể
Biến thể A: ứng dụng của chính bạn. Điều kiện tối thiểu: một thành phần web nói HTTP có endpoint kiểm tra sức khỏe, ít nhất một phụ thuộc có trạng thái (PostgreSQL, MySQL, MongoDB…), image chạy được bằng user không phải root. Ứng dụng có hàng đợi hay tác vụ nền thì càng tốt.
Biến thể B: notes-api + worker. Thêm một thành phần mới vào notes-api: mỗi khi có ghi chú mới, notes-api đẩy một sự kiện vào danh sách Redis notes:events; một worker chạy nền lấy sự kiện ra, đếm số từ và ghi vào bảng note_stats. Mô hình này (web nhận request, worker xử lý bất đồng bộ qua hàng đợi) có mặt trong rất nhiều hệ thống thật.
Mã nguồn cho biến thể B
Trong server.js, route POST /notes thêm một dòng sau câu INSERT:
app.post("/notes", async (req, res) => {
const { rows } = await pool.query(
"INSERT INTO notes (text) VALUES ($1) RETURNING id, text",
[req.body.text]
);
await redis.rPush("notes:events", JSON.stringify(rows[0])); // dòng mới
res.status(201).json(rows[0]);
});Tạo file mới worker.js cạnh server.js:
const fs = require("fs");
const { createClient } = require("redis");
const { Pool } = require("pg");
const QUEUE = "notes:events";
const redis = createClient({ url: process.env.REDIS_URL });
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
redis.on("error", (err) => console.error("redis error:", err.message));
let running = true;
process.on("SIGTERM", () => {
console.log("SIGTERM: dung nhan viec moi");
running = false;
});
// Nhịp tim cho livenessProbe: vòng lặp còn quay thì file còn mới
const beat = () => fs.writeFileSync("/tmp/heartbeat", String(Date.now()));
async function main() {
await redis.connect();
await pool.query(`CREATE TABLE IF NOT EXISTS note_stats (
note_id INT PRIMARY KEY,
words INT NOT NULL
)`);
console.log("worker started");
while (running) {
beat();
const item = await redis.blPop(QUEUE, 5); // chờ tối đa 5 giây
if (!item) continue;
const { id, text } = JSON.parse(item.element);
const words = String(text).trim().split(/\s+/).filter(Boolean).length;
await pool.query(
"INSERT INTO note_stats (note_id, words) VALUES ($1, $2) ON CONFLICT (note_id) DO UPDATE SET words = $2",
[id, words]
);
await redis.incr("worker:processed");
console.log(`note ${id}: ${words} tu`);
}
await redis.quit();
await pool.end();
console.log("worker stopped");
}
main().catch((err) => {
console.error("worker failed:", err.message);
process.exit(1);
});Dockerfile giữ nguyên (COPY . . đã đưa cả worker.js vào image). Một image, hai cách chạy: node server.js cho web, node worker.js cho worker.
docker build -t notes-api:2.0 app/
kind load docker-image notes-api:2.0 --name hoc-k8sĐiểm xuất phát
- Cluster
hoc-k8scó đủ add-on nền tảng của bài Dự án tổng kết (bước 0 và 1): metrics-server, cloud-provider-kind, Gateway API + Envoy Gateway, cert-manager với ClusterIssuerhoc-k8s-ca, Gatewayshared-gateway, Argo CD; kube-prometheus-stack nếu muốn làm điểm cộng. - Biến thể B có thể bắt đầu từ repo
notes-platformcủa bài trước. Biến thể A thì thêm một Certificate và listener HTTPS cho hostname của bạn (ví dụmyapp.localtest.me) vàoplatform/gateway.yaml.
Yêu cầu
Repo và đóng gói
- Repo có ít nhất:
app/(mã nguồn, Dockerfile),k8s/base,k8s/overlays/dev,k8s/overlays/prod(hoặc một Helm chart vớivalues-dev.yaml,values-prod.yaml), manifest Application của Argo CD vàREADME.md. - Cả hai môi trường render được không lỗi:
kubectl kustomize(hoặchelm template) cho dev và prod. Dev và prod khác nhau ít nhất ở số bản sao và một giá trị cấu hình.
Namespace và bảo mật
- Namespace riêng, gắn Pod Security
enforce: restrictedcó ghimenforce-version, cùngwarnvàaudit. - Mọi Pod (web, worker, database, cache) đạt
restricted:runAsNonRootvớirunAsUserdạng số,seccompProfile: RuntimeDefault,allowPrivilegeEscalation: false,capabilities.drop: ["ALL"]. Container nào không cần gọi API server thìautomountServiceAccountToken: false. Thành phần do bạn viết dùngreadOnlyRootFilesystem: true, chỗ cần ghi làemptyDir.
Workload
- Deployment web có startupProbe, readinessProbe, livenessProbe;
requestsCPU và memory,limitsmemory; rolling update không giảm số Pod sẵn sàng (maxUnavailable: 0);preStop;topologySpreadConstraintstrải Pod qua các node. - Thành phần nền (worker ở biến thể B) có cơ chế kiểm tra sống phù hợp với thứ không nói HTTP, có
resources, dừng êm khi nhận SIGTERM và không có Service. - Cấu hình nằm trong ConfigMap; đổi cấu hình phải tự gây rolling update (hậu tố băm của Kustomize hoặc annotation checksum của Helm).
- Mật khẩu nằm trong Secret không bao giờ xuất hiện trong lịch sử git dưới dạng đọc được (tạo ngoài git, Sealed Secrets hoặc External Secrets). README ghi rõ cách tạo.
- Phụ thuộc có trạng thái lưu dữ liệu bền: StatefulSet +
volumeClaimTemplates. Xóa Pod database, dữ liệu vẫn còn.
Mạng và truy cập
- Service
ClusterIPcho web; HTTPRoute gắn vào listener HTTPS với chứng chỉ do cert-manager cấp; một route riêng chuyển HTTP sang HTTPS (301). - NetworkPolicy: default-deny cả ingress lẫn egress cho namespace, mở DNS, rồi chỉ mở đúng các luồng cần thiết. README liệt kê các luồng đó.
Co giãn và vận hành
- HPA (
autoscaling/v2, theo CPU) cho web vớiminReplicasít nhất 2, và PDB sao cho lúc bình thườngALLOWED DISRUPTIONSít nhất 1. Manifest của Deployment web không ghireplicasở môi trường có HPA. - Argo CD triển khai overlay prod từ git với
automated,prune,selfHeal. Lịch sử git có ít nhất một lần phát hành và một lần rollback bằnggit revert. README.mdlà một runbook: kiến trúc (sơ đồ), dựng từ cluster trống, tạo Secret, phát hành, rollback, xoay mật khẩu, kiểm tra sức khỏe, giới hạn đã biết.
Điểm cộng (không bắt buộc): ServiceMonitor + một alert có ý nghĩa; Redis lưu bền (AOF trên PVC) để hàng đợi không mất khi Pod Redis bị tạo lại; worker co giãn theo độ dài hàng đợi bằng KEDA; pipeline CI build image và sửa tag trong repo.
Bảng tự đánh giá
Mỗi dòng đạt được 1 điểm, tối đa 14. Từ 12 điểm trở lên là hệ thống đủ chín để mang đi phỏng vấn.
| # | Yêu cầu | Cách kiểm | Lệnh |
|---|---|---|---|
| 1 | Cấu trúc repo | Có đủ thư mục và README | ls app k8s/base k8s/overlays/dev k8s/overlays/prod README.md |
| 2 | Hai môi trường | Render không lỗi, có khác biệt | diff <(kubectl kustomize k8s/overlays/dev) <(kubectl kustomize k8s/overlays/prod) | head |
| 3 | Pod Security | Label đúng, dry-run không cảnh báo | kubectl label --dry-run=server --overwrite ns notes pod-security.kubernetes.io/enforce=restricted |
| 4 | securityContext | Không capability, có no_new_privs | kubectl -n notes exec deploy/notes-worker -- grep -E 'CapEff|NoNewPrivs' /proc/1/status |
| 5 | Web Deployment | Có đủ ba probe, preStop, spread | kubectl -n notes describe deploy notes-api | grep -E 'Liveness|Readiness|Startup|PreStop' |
| 6 | Worker | Probe không HTTP, dừng êm | kubectl -n notes delete pod -l app=notes-worker rồi kubectl -n notes logs -l app=notes-worker --previous hoặc xem log trước khi Pod biến mất |
| 7 | Cấu hình gây rollout | Đổi một literal, tên ConfigMap đổi | kubectl kustomize k8s/overlays/prod | grep 'name: notes-config-' trước và sau khi sửa |
| 8 | Secret ngoài git | Mật khẩu thật không có trong bất kỳ commit nào | Lệnh số 8 ở phần Tự kiểm tra |
| 9 | Dữ liệu bền | Xóa Pod database, dữ liệu còn | kubectl -n notes delete pod postgres-0 rồi GET /notes |
| 10 | HTTPS + redirect | 200 qua HTTPS, 301 qua HTTP | curl --cacert hoc-k8s-ca.crt ... |
| 11 | NetworkPolicy | Luồng lạ bị chặn, ứng dụng vẫn chạy | Phép thử từ namespace default |
| 12 | HPA + PDB | TARGETS có số, cho phép 1 gián đoạn | kubectl -n notes get hpa,pdb |
| 13 | GitOps + rollback | Synced Healthy, git có commit Revert | kubectl -n argocd get application, git log --oneline | grep Revert |
| 14 | Runbook | Một người khác dựng lại được | Nhờ bạn bè làm theo README trên cluster mới, ghi lại chỗ họ bị kẹt |
Tự kiểm tra
Lệnh viết cho biến thể B, namespace notes. Kết quả mong đợi ghi trong comment.
# 1. Hai môi trường render được
kubectl kustomize k8s/overlays/dev > /dev/null && kubectl kustomize k8s/overlays/prod > /dev/null && echo "render OK"
# render OK
# 2. Argo CD đồng bộ từ git
kubectl -n argocd get application notes-prod
# notes-prod Synced Healthy
# 3. Mọi workload chạy
kubectl -n notes get deploy,statefulset
# notes-api 3/3, notes-worker 2/2, redis 1/1, statefulset postgres 1/1
# 4. Luồng end-to-end: ghi chú mới → worker đếm từ
export GATEWAY_IP=$(kubectl -n gateway-infra get gateway shared-gateway -o jsonpath='{.status.addresses[0].value}')
curl -s --cacert hoc-k8s-ca.crt --resolve notes.localtest.me:443:${GATEWAY_IP} \
-X POST https://notes.localtest.me/notes -H 'Content-Type: application/json' -d '{"text":"mot hai ba bon"}'
# {"id":N,"text":"mot hai ba bon"}
kubectl -n notes logs -l app=notes-worker --tail=3 --prefix
# [pod/notes-worker-.../worker] note N: 4 tu
kubectl -n notes exec postgres-0 -- psql -U notes -d notes -c 'SELECT * FROM note_stats ORDER BY note_id DESC LIMIT 1;'
# note_id = N, words = 4
# 5. Worker đạt restricted và không có capability
kubectl -n notes exec deploy/notes-worker -- id
# uid=1000(node) gid=1000(node) groups=1000(node)
kubectl -n notes exec deploy/notes-worker -- grep -E 'CapEff|NoNewPrivs' /proc/1/status
# CapEff: 0000000000000000 / NoNewPrivs: 1
# 6. NetworkPolicy: từ namespace khác vào redis bị chặn; worker không ra được Internet
kubectl run nettest -n default --rm -i --restart=Never --image=busybox:1.37 -- sh -c \
'nc -w 3 redis.notes 6379 </dev/null >/dev/null 2>&1 && echo "redis: mo" || echo "redis: bi chan"'
# redis: bi chan
kubectl -n notes exec deploy/notes-worker -- node -e \
"fetch('https://example.com',{signal:AbortSignal.timeout(3000)}).then(()=>console.log('ra duoc')).catch(e=>console.log('bi chan:',e.name))"
# bi chan: TimeoutError
# 7. Worker dừng êm: log có "worker stopped" trước khi Pod biến mất
POD=$(kubectl -n notes get pod -l app=notes-worker -o jsonpath='{.items[0].metadata.name}')
kubectl -n notes logs -f $POD &
kubectl -n notes delete pod $POD
# SIGTERM: dung nhan viec moi
# worker stopped (trong vòng ~5 giây, không phải 30 giây)
# 8. Mật khẩu thật không có trong lịch sử git
PASS=$(kubectl -n notes get secret notes-db -o jsonpath='{.data.POSTGRES_PASSWORD}' | base64 -d)
git grep -c "$PASS" $(git rev-list --all) | wc -l
# 0
# 9. HPA và PDB
kubectl -n notes get hpa,pdb
# TARGETS cpu: x%/70%, MINPODS 3; ALLOWED DISRUPTIONS 1
# 10. Có ít nhất một lần rollback bằng git
git log --oneline | grep -c '^[0-9a-f]* Revert'
# 1 (hoặc hơn)# ===== Cấu trúc repo gợi ý =====
# notes-platform/
# ├── app/ # server.js, worker.js, package.json, Dockerfile
# ├── platform/argocd/notes-prod.yaml
# ├── k8s/base/
# │ ├── kustomization.yaml
# │ ├── namespace.yaml
# │ ├── postgres.yaml
# │ ├── redis.yaml
# │ ├── notes-api.yaml
# │ ├── worker.yaml # mới (biến thể B)
# │ ├── networkpolicies.yaml
# │ └── httproute.yaml
# ├── k8s/overlays/dev/kustomization.yaml
# ├── k8s/overlays/prod/{kustomization.yaml,hpa-pdb.yaml}
# └── README.md # runbook
# ===== k8s/base/kustomization.yaml =====
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- namespace.yaml # TODO: PSA enforce restricted (ghim version), warn/audit, label shared-gateway-access
- postgres.yaml # TODO: headless Service + StatefulSet + volumeClaimTemplates
- redis.yaml
- notes-api.yaml # TODO: Deployment (không ghi replicas) + Service ClusterIP
- worker.yaml # TODO: biến thể B
- networkpolicies.yaml # TODO: default-deny + DNS + từng luồng cần thiết
- httproute.yaml # TODO: route trên listener https + route redirect trên listener http
labels:
- pairs:
app.kubernetes.io/part-of: notes
includeSelectors: false
includeTemplates: true
configMapGenerator:
- name: notes-config
literals:
# TODO: PORT, LOG_LEVEL, REDIS_URL
generatorOptions:
immutable: true
# ===== k8s/base/worker.yaml =====
apiVersion: apps/v1
kind: Deployment
metadata:
name: notes-worker
labels:
app: notes-worker
spec:
replicas: 2
selector:
matchLabels:
app: notes-worker
template:
metadata:
labels:
app: notes-worker
spec:
# TODO: automountServiceAccountToken, enableServiceLinks
# TODO: securityContext cấp Pod đạt restricted (uid 1000)
# TODO: terminationGracePeriodSeconds đủ cho một vòng BLPOP
containers:
- name: worker
image: notes-api:2.0
imagePullPolicy: IfNotPresent
command: ["node", "worker.js"]
# TODO: REDIS_URL từ ConfigMap notes-config (envFrom)
# TODO: POSTGRES_* từ Secret notes-db, DATABASE_URL ghép bằng $(...)
# TODO: startupProbe + livenessProbe kiểu exec dựa trên /tmp/heartbeat
# TODO: resources (requests cpu/memory, limit memory)
# TODO: securityContext cấp container, /tmp là emptyDir
# ===== k8s/base/networkpolicies.yaml (phần cần đổi) =====
# TODO: policy cho notes-worker: không nhận ingress, egress chỉ tới postgres:5432 và redis:6379
# TODO: policy postgres và redis: nhận từ CẢ notes-api lẫn notes-worker
# ===== k8s/overlays/prod/kustomization.yaml =====
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: notes
resources:
- ../../base
# TODO: hpa-pdb.yaml (và monitoring.yaml nếu làm điểm cộng)
images:
- name: notes-api
newTag: "TODO" # một dòng này đổi image cho cả web lẫn worker
# ===== k8s/overlays/dev/kustomization.yaml =====
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: notes
resources:
- ../../base
# TODO: replicas 1 cho notes-api và notes-worker
# TODO: LOG_LEVEL=debug (configMapGenerator, behavior: merge)
# ===== platform/argocd/notes-prod.yaml =====
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: notes-prod
namespace: argocd
spec:
project: default
source:
repoURL: TODO
targetRevision: main
path: k8s/overlays/prod
destination:
server: https://kubernetes.default.svc
namespace: notes
syncPolicy:
# TODO: automated với prune và selfHeal
# ===== README.md (khung runbook, viết bằng markdown) =====
# TODO: 1. Kiến trúc (sơ đồ + các luồng mạng được phép)
# TODO: 2. Dựng từ cluster trống (add-on, Secret, Application)
# TODO: 3. Phát hành phiên bản mới
# TODO: 4. Rollback
# TODO: 5. Xoay mật khẩu database
# TODO: 6. Kiểm tra sức khỏe, đọc cảnh báo
# TODO: 7. Giới hạn đã biết
Comments