Bài tập: Cấu hình notes-api bằng ConfigMap và Secret
Bạn sẽ tự viết lại toàn bộ phần cấu hình của stack notes trong namespace notes: cấu hình thường vào ConfigMap, thông tin đăng nhập Postgres vào Secret, một file JSON gắn vào container, và một quy trình áp dụng cấu hình khiến notes-api nhận giá trị mới chỉ khi cấu hình thật sự đổi. Đâ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đang chạy, imagenotes-api:1.0đã nạp bằngkind load docker-image notes-api:1.0 --name hoc-k8s. - Namespace
notescó những gì chương 4 để lại:deps-dev.yaml(Deployment + Servicepostgresvàredis, mật khẩu viết thẳng trongenv) và Deploymentnotes-api(3 bản sao, probe/health,envviết thẳngPORT,DATABASE_URL,REDIS_URL). - Nếu đã làm theo phần thực hành của hai bài trước, xóa đi để làm lại từ đầu:
kubectl -n notes delete configmap notes-config --ignore-not-foundvàkubectl -n notes delete secret notes-db --ignore-not-found.
notes-api 1.0 chỉ đọc PORT, DATABASE_URL, REDIS_URL. LOG_LEVEL và app-config.json chưa được ứng dụng dùng; chúng có mặt để chuẩn bị cho phiên bản sau và để bạn quan sát cơ chế cập nhật.
Kết quả cần có, trong một thư mục k8s/:
k8s/
├── .gitignore # chứa notes-db.yaml
├── notes-config.yaml # ConfigMap notes-config và notes-app-config
├── notes-db.example.yaml # mẫu Secret với giá trị giả, ĐƯỢC commit
├── notes-db.yaml # Secret thật, KHÔNG commit
├── deps.yaml # thay cho deps-dev.yaml
├── notes-api-deployment.yaml
└── apply-config.sh # quy trình áp dụng cấu hìnhYêu cầu
ConfigMap
- ConfigMap
notes-configtrong namespacenotescó đúng ba key:PORT=3000,LOG_LEVEL=info,REDIS_URL=redis://redis:6379. - Một file cấu hình JSON hợp lệ (nội dung tùy bạn, ví dụ
pageSize,maxLength) nằm ở keyapp-config.jsoncủa một ConfigMap riêng tênnotes-app-config.
Secret
- Secret
notes-dbloạiOpaque, viết bằngstringData, có ba keyPOSTGRES_USER=notes,POSTGRES_PASSWORD,POSTGRES_DB=notes. Trong lab dùng mật khẩunotes-dev-password; mật khẩu chỉ được chứa ký tự an toàn cho URL. notes-db.yamlnằm trong.gitignore.notes-db.example.yamlcó cùng cấu trúc nhưng giá trị giả.
Postgres và Redis
deps.yamlthay chodeps-dev.yaml: containerpostgresnhận cả ba biến từ Secretnotes-dbbằngenvFrom; trong file không còn chuỗi mật khẩu nào. Redis giữ nguyên.
notes-api
- Nhận mọi key của
notes-configbằngenvFrom. - Nhận
POSTGRES_USER,POSTGRES_PASSWORD,POSTGRES_DBbằngsecretKeyRef, rồi ghépDATABASE_URL(hostpostgres, cổng 5432) bằng cú pháp$(…). Manifest không chứa mật khẩu. - File
app-config.jsonxuất hiện tại/etc/notes/app-config.json, chỉ đọc, và tự cập nhật khi ConfigMap đổi (không dùngsubPath). - Giữ image
notes-api:1.0,imagePullPolicy: IfNotPresent, 3 bản sao và hai probe như chương 4.
Vận hành
apply-config.sháp dụng Secret và ConfigMap, rồi làm notes-api rolling update khi và chỉ khi nội dungnotes-config.yamlhoặcnotes-db.yamlthay đổi. Chạy script hai lần liên tiếp mà không sửa gì thì lần thứ hai không tạo Pod mới.- Đầu file
notes-config.yamlcó 2–4 dòng comment trả lời: trong cách làm của bạn, có nên bậtimmutable: truechonotes-configvànotes-dbkhông, vì sao?
Điểm cộng (không bắt buộc): notes-api không nhận token ServiceAccount (automountServiceAccountToken: false) và không nhận các biến môi trường tự sinh cho Service (enableServiceLinks: false).
WARNING
Đừng kubectl delete -f deps-dev.yaml để "dọn" trước khi chuyển: file đó chứa cả Namespace notes, xóa nó là xóa sạch namespace. Chỉ cần kubectl apply -f deps.yaml: các Deployment cùng tên được cập nhật tại chỗ, và env cũ bị gỡ vì không còn trong manifest.
Tự kiểm tra
Chạy trong thư mục k8s/. Kết quả mong đợi ghi trong comment.
# 1. Áp dụng theo thứ tự: cấu hình trước, workload sau
kubectl apply -f notes-db.yaml -f notes-config.yaml
kubectl apply -f deps.yaml && kubectl -n notes rollout status deploy/postgres
kubectl apply -f notes-api-deployment.yaml && kubectl -n notes rollout status deploy/notes-api
# deployment "notes-api" successfully rolled out
# 2. Secret mang đúng giá trị
kubectl get secret notes-db -n notes -o jsonpath='{.data.POSTGRES_PASSWORD}' | base64 -d; echo
# notes-dev-password
# 3. Mật khẩu không còn trong các file được commit, cũng không trong Deployment
grep -l 'notes-dev-password' deps.yaml notes-api-deployment.yaml notes-config.yaml notes-db.example.yaml || echo "sach"
# sach
kubectl -n notes get deploy -o yaml | grep -c notes-dev-password
# 0
# 4. Biến môi trường bên trong notes-api (thứ tự dòng có thể khác)
kubectl exec deploy/notes-api -n notes -- printenv | grep -E '^(PORT|LOG_LEVEL|REDIS_URL|DATABASE_URL)='
# PORT=3000
# LOG_LEVEL=info
# REDIS_URL=redis://redis:6379
# DATABASE_URL=postgres://notes:notes-dev-password@postgres:5432/notes (không còn "$(")
# 5. File cấu hình có mặt và chỉ đọc
kubectl exec deploy/notes-api -n notes -- cat /etc/notes/app-config.json
# nội dung JSON của bạn
kubectl exec deploy/notes-api -n notes -- sh -c 'echo x > /etc/notes/thu.txt'
# sh: 1: cannot create /etc/notes/thu.txt: Read-only file system
# 6. Ứng dụng hoạt động
kubectl -n notes port-forward deploy/notes-api 8080:3000 >/dev/null &
sleep 2
curl -s localhost:8080/health # {"status":"ok"}
curl -s -X POST localhost:8080/notes -H 'Content-Type: application/json' -d '{"text":"cau hinh xong"}'
curl -s localhost:8080/notes # [{"id":1,"text":"cau hinh xong"}]
kill %1
# 7. Hành vi khi cấu hình đổi
# 7a. Sửa LOG_LEVEL thành debug VÀ đổi một giá trị trong app-config.json, rồi CHỈ apply ConfigMap
kubectl apply -f notes-config.yaml
kubectl exec deploy/notes-api -n notes -- printenv LOG_LEVEL # vẫn info
sleep 90
kubectl exec deploy/notes-api -n notes -- cat /etc/notes/app-config.json # đã thấy giá trị mới
kubectl -n notes get pods -l app=notes-api # AGE không đổi, RESTARTS 0: không Pod nào bị tạo lại
# 7b. Chạy quy trình chính thức
./apply-config.sh # notes-api patched, rolling update
kubectl exec deploy/notes-api -n notes -- printenv LOG_LEVEL # debug
./apply-config.sh # lần hai: "patched (no change)", không có Pod mớiBước 6 trả về id 1 vì Postgres trong deps.yaml vẫn chưa lưu bền: Pod Postgres được tạo lại ở bước 1 với database trống. Chương 8 sẽ giải quyết việc này.
# ===== notes-config.yaml =====
# TODO (yêu cầu 11): 2-4 dòng comment: có nên bật immutable cho notes-config và notes-db không, vì sao?
apiVersion: v1
kind: ConfigMap
metadata:
name: notes-config
namespace: notes
data:
# TODO: PORT, LOG_LEVEL, REDIS_URL (mọi giá trị là chuỗi)
---
apiVersion: v1
kind: ConfigMap
metadata:
name: notes-app-config
namespace: notes
data:
# TODO: key app-config.json chứa một file JSON hợp lệ (dùng khối |)
# ===== notes-db.example.yaml (được commit; bản thật notes-db.yaml nằm trong .gitignore) =====
apiVersion: v1
kind: Secret
metadata:
name: notes-db
namespace: notes
type: Opaque
# TODO: stringData với POSTGRES_USER, POSTGRES_PASSWORD (giá trị giả), POSTGRES_DB
# ===== deps.yaml (thay cho deps-dev.yaml) =====
# Giữ nguyên Namespace, Service postgres, Deployment + Service redis như deps-dev.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: postgres
namespace: notes
labels:
app: postgres
spec:
replicas: 1
selector:
matchLabels:
app: postgres
template:
metadata:
labels:
app: postgres
spec:
containers:
- name: postgres
image: postgres:18
ports:
- containerPort: 5432
# TODO: nhận cả Secret notes-db bằng envFrom (không còn env viết thẳng)
# ===== notes-api-deployment.yaml =====
apiVersion: apps/v1
kind: Deployment
metadata:
name: notes-api
namespace: notes
labels:
app: notes-api
spec:
replicas: 3
selector:
matchLabels:
app: notes-api
template:
metadata:
labels:
app: notes-api
spec:
containers:
- name: notes-api
image: notes-api:1.0
imagePullPolicy: IfNotPresent
ports:
- containerPort: 3000
# TODO: envFrom từ ConfigMap notes-config
# TODO: POSTGRES_USER / POSTGRES_PASSWORD / POSTGRES_DB từ secretKeyRef
# TODO: DATABASE_URL ghép bằng $(...), chú ý thứ tự
# TODO: gắn app-config.json chỉ đọc vào /etc/notes (không dùng subPath)
readinessProbe:
httpGet:
path: /health
port: 3000
periodSeconds: 5
livenessProbe:
httpGet:
path: /health
port: 3000
initialDelaySeconds: 10
periodSeconds: 10
failureThreshold: 3
# TODO: volumes
# ===== apply-config.sh =====
# TODO: apply Secret và ConfigMap, rồi rolling update notes-api CHỈ KHI nội dung
# notes-config.yaml hoặc notes-db.yaml thay đổi (gợi ý: mã băm + annotation)
Comments