Blue/Green Deployment trên Kubernetes
🎯 Mục tiêu: Triển khai 2 version app song song (blue = v1, green = v2) và switch traffic không downtime bằng cách thay đổi Service selector.
🧰 Công cụ / nền tảng: kubectl, kind (Kubernetes in Docker), curl. Yêu cầu: Docker Desktop hoặc Docker Engine đã chạy.
📦 Chuẩn bị:
# Cài kind nếu chưa có
curl -Lo ./kind https://kind.sigs.k8s.io/dl/v0.22.0/kind-linux-amd64
chmod +x ./kind && sudo mv ./kind /usr/local/bin/kind
# Tạo cluster
kind create cluster --name bluegreen
kubectl cluster-info --context kind-bluegreen
▶️ Các bước:
# Bước 1: Deploy phiên bản BLUE (v1)
cat <<EOF | kubectl apply -f -
apiVersion: apps/v1
kind: Deployment
metadata:
name: app-blue
spec:
replicas: 3
selector:
matchLabels:
app: webapp
version: blue
template:
metadata:
labels:
app: webapp
version: blue
spec:
containers:
- name: webapp
image: nginx:1.24
ports:
- containerPort: 80
# Mô phỏng v1: ghi version vào response
lifecycle:
postStart:
exec:
command: ["/bin/sh","-c","echo 'v1-blue' > /usr/share/nginx/html/index.html"]
EOF
# Bước 2: Tạo Service trỏ vào BLUE
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Service
metadata:
name: webapp-svc
spec:
selector:
app: webapp
version: blue # <-- đây là switch
ports:
- port: 80
targetPort: 80
type: ClusterIP
EOF
# Bước 3: Xác nhận service đang trỏ blue
kubectl get endpoints webapp-svc
# Bước 4: Deploy phiên bản GREEN (v2) — KHÔNG ảnh hưởng production
cat <<EOF | kubectl apply -f -
apiVersion: apps/v1
kind: Deployment
metadata:
name: app-green
spec:
replicas: 3
selector:
matchLabels:
app: webapp
version: green
template:
metadata:
labels:
app: webapp
version: green
spec:
containers:
- name: webapp
image: nginx:1.25
ports:
- containerPort: 80
lifecycle:
postStart:
exec:
command: ["/bin/sh","-c","echo 'v2-green' > /usr/share/nginx/html/index.html"]
EOF
# Bước 5: Kiểm tra green sẵn sàng
kubectl rollout status deployment/app-green
# Bước 6: Switch traffic sang GREEN (1 lệnh, 0 downtime)
kubectl patch service webapp-svc -p '{"spec":{"selector":{"version":"green"}}}'
# Bước 7: Xác nhận
kubectl get endpoints webapp-svc
# Port-forward để test
kubectl port-forward svc/webapp-svc 8080:80 &
curl http://localhost:8080 # kết quả phải là "v2-green"
# Bước 8: Rollback tức thì (nếu green có vấn đề)
kubectl patch service webapp-svc -p '{"spec":{"selector":{"version":"blue"}}}'
curl http://localhost:8080 # trả về "v1-blue"
✅ Kết quả mong đợi: Service chuyển từ blue sang green trong <1 giây; curl trả đúng version tương ứng; rollback cũng <1 giây. kubectl get deployments hiển thị cả app-blue và app-green Running song song.
🧹 Cleanup:
kill %1 # dừng port-forward
kubectl delete deployment app-blue app-green
kubectl delete service webapp-svc
# Hoặc xóa toàn bộ cluster
kind delete cluster --name bluegreen