- Renamed auth-service to iam-service across various files for consistency. - Updated Dockerfiles, deployment configurations, and documentation to reflect the service name change. - Enhanced testing commands in documentation to point to the new iam-service. - Removed outdated auth-service files and configurations to streamline the project structure. - Improved bilingual documentation for clarity on the new service structure and usage.
14 KiB
Kubernetes Deployment / Triển Khai Kubernetes
EN: Kubernetes deployment patterns for GoodGo microservices. Use when deploying to staging/production, creating K8s manifests, configuring HPA, setting up ingress, or troubleshooting K8s deployments. VI: Các pattern triển khai Kubernetes cho microservices GoodGo. Sử dụng khi triển khai lên staging/production, tạo K8s manifests, cấu hình HPA, thiết lập ingress, hoặc xử lý sự cố triển khai K8s.
Overview / Tổng Quan
EN: This skill covers Kubernetes deployment patterns and best practices for GoodGo microservices. It includes creating deployment manifests, configuring autoscaling, managing secrets and configmaps, setting up ingress, and implementing health checks.
VI: Skill này bao gồm các pattern triển khai Kubernetes và best practices cho microservices GoodGo. Nó bao gồm tạo deployment manifests, cấu hình autoscaling, quản lý secrets và configmaps, thiết lập ingress, và triển khai health checks.
When to Use / Khi Nào Sử Dụng
EN: Use this skill when:
- Deploying services to staging/production environments
- Creating or updating Kubernetes manifests
- Configuring autoscaling (HPA/VPA)
- Setting up ingress and load balancing
- Managing secrets and configmaps
- Troubleshooting deployment issues
- Implementing health checks and probes
- Setting up monitoring and logging
VI: Sử dụng skill này khi:
- Triển khai services lên môi trường staging/production
- Tạo hoặc cập nhật Kubernetes manifests
- Cấu hình autoscaling (HPA/VPA)
- Thiết lập ingress và load balancing
- Quản lý secrets và configmaps
- Xử lý sự cố triển khai
- Triển khai health checks và probes
- Thiết lập monitoring và logging
Key Concepts / Khái Niệm Chính
Deployment Strategy / Chiến Lược Triển Khai
EN:
- Rolling updates for zero-downtime deployments
- Resource limits and requests for stability
- Health checks (liveness/readiness probes)
- Horizontal Pod Autoscaler (HPA) for auto-scaling
- ConfigMaps for configuration
- Secrets for sensitive data
VI:
- Rolling updates để triển khai không downtime
- Resource limits và requests để đảm bảo ổn định
- Health checks (liveness/readiness probes)
- Horizontal Pod Autoscaler (HPA) để tự động scale
- ConfigMaps cho cấu hình
- Secrets cho dữ liệu nhạy cảm
Common Patterns / Các Pattern Thường Dùng
Service Deployment Manifest / Manifest Triển Khai Service
EN: Standard deployment manifest structure for GoodGo services.
VI: Cấu trúc deployment manifest chuẩn cho các services GoodGo.
Example from codebase: deployments/production/kubernetes/iam-service.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: iam-service
namespace: production
spec:
replicas: 3
selector:
matchLabels:
app: iam-service
template:
metadata:
labels:
app: iam-service
spec:
containers:
- name: iam-service
image: goodgo/iam-service:latest
imagePullPolicy: Always
ports:
- containerPort: 5001
envFrom:
- configMapRef:
name: iam-service-config
- secretRef:
name: iam-service-secrets
resources:
requests:
memory: "512Mi"
cpu: "500m"
limits:
memory: "1Gi"
cpu: "1000m"
livenessProbe:
httpGet:
path: /health/live
port: 5001
initialDelaySeconds: 30
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 3
readinessProbe:
httpGet:
path: /health/ready
port: 5001
initialDelaySeconds: 10
periodSeconds: 5
timeoutSeconds: 3
failureThreshold: 3
---
apiVersion: v1
kind: Service
metadata:
name: iam-service
namespace: production
spec:
selector:
app: iam-service
ports:
- protocol: TCP
port: 5001
targetPort: 5001
type: ClusterIP
Horizontal Pod Autoscaler / Tự Động Scale Pod
EN: Configure HPA to automatically scale pods based on CPU and memory utilization.
VI: Cấu hình HPA để tự động scale pods dựa trên CPU và memory utilization.
Example from codebase: deployments/production/kubernetes/iam-service.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: iam-service-hpa
namespace: production
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: iam-service
minReplicas: 3
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80
ConfigMap & Secrets / ConfigMap và Secrets
EN: Use ConfigMaps for non-sensitive configuration and Secrets for sensitive data.
VI: Sử dụng ConfigMaps cho cấu hình không nhạy cảm và Secrets cho dữ liệu nhạy cảm.
Example from codebase:
- ConfigMap:
deployments/production/kubernetes/iam-service-configmap.yaml - Secrets:
deployments/production/kubernetes/secrets.yaml.example
# ConfigMap
apiVersion: v1
kind: ConfigMap
metadata:
name: iam-service-config
namespace: production
data:
NODE_ENV: "production"
PORT: "5001"
API_VERSION: "v1"
CORS_ORIGIN: "https://goodgo.vn"
LOG_LEVEL: "warn"
SERVICE_NAME: "iam-service"
TRACING_ENABLED: "true"
---
# Secret (example - use sealed-secrets in production)
apiVersion: v1
kind: Secret
metadata:
name: iam-service-secrets
namespace: production
type: Opaque
stringData:
database-url: "postgresql://user:password@ep-xxx.region.neon.tech/dbname?sslmode=require&pgbouncer=true"
jwt-secret: "your-production-jwt-secret-min-32-chars"
jwt-refresh-secret: "your-production-refresh-secret-min-32-chars"
redis-password: ""
Ingress Configuration / Cấu Hình Ingress
EN: Configure ingress for external access with TLS and path-based routing.
VI: Cấu hình ingress để truy cập từ bên ngoài với TLS và path-based routing.
Example from codebase: deployments/production/kubernetes/ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: api-ingress
namespace: production
annotations:
traefik.ingress.kubernetes.io/rule-type: PathPrefix
cert-manager.io/cluster-issuer: "letsencrypt-prod"
spec:
ingressClassName: traefik
tls:
- hosts:
- api.goodgo.vn
secretName: api-tls-cert
rules:
- host: api.goodgo.vn
http:
paths:
- path: /api/v1/auth
pathType: Prefix
backend:
service:
name: iam-service
port:
number: 5001
Best Practices / Thực Hành Tốt Nhất
Resource Management / Quản Lý Tài Nguyên
EN:
- Always set resource requests and limits
- Monitor actual usage and adjust accordingly
- Use HPA for automatic scaling
- Set appropriate CPU and memory based on service requirements
VI:
- Luôn đặt resource requests và limits
- Theo dõi sử dụng thực tế và điều chỉnh phù hợp
- Sử dụng HPA để tự động scale
- Đặt CPU và memory phù hợp dựa trên yêu cầu service
Configuration / Cấu Hình
EN:
- Use ConfigMaps for non-sensitive config
- Use Secrets for sensitive data
- Never hardcode configuration in images
- Use
envFromto load entire ConfigMap/Secret
VI:
- Sử dụng ConfigMaps cho cấu hình không nhạy cảm
- Sử dụng Secrets cho dữ liệu nhạy cảm
- Không bao giờ hardcode cấu hình trong images
- Sử dụng
envFromđể load toàn bộ ConfigMap/Secret
Health Checks / Kiểm Tra Sức Khỏe
EN:
- Implement both liveness and readiness probes
- Set appropriate timeouts and thresholds
- Include dependency checks in readiness probe
- Use HTTP probes for web services
VI:
- Triển khai cả liveness và readiness probes
- Đặt timeouts và thresholds phù hợp
- Bao gồm kiểm tra dependencies trong readiness probe
- Sử dụng HTTP probes cho web services
Example from codebase: services/iam-service/src/modules/health/health.controller.ts
// Liveness probe - is the service alive?
health = async (_req: Request, res: Response): Promise<void> => {
res.json({
success: true,
data: { status: 'ok', timestamp: new Date().toISOString() },
});
};
// Readiness probe - is the service ready to accept traffic?
ready = async (_req: Request, res: Response): Promise<void> => {
try {
// Check database connection
await prisma.$queryRaw`SELECT 1`;
res.json({
success: true,
data: { status: 'ready' },
});
} catch (error) {
res.status(503).json({
success: false,
error: { code: 'HEALTH_001', message: 'Service not ready' },
});
}
};
Deployment / Triển Khai
EN:
- Use rolling updates for zero-downtime
- Set maxSurge and maxUnavailable appropriately
- Test deployments in staging first
- Use image tags instead of
latestin production
VI:
- Sử dụng rolling updates để không downtime
- Đặt maxSurge và maxUnavailable phù hợp
- Test triển khai trong staging trước
- Sử dụng image tags thay vì
latesttrong production
Security / Bảo Mật
EN:
- Run containers as non-root user
- Use network policies to restrict traffic
- Regularly update base images
- Use sealed-secrets or external secret manager
- Never commit secrets to Git
VI:
- Chạy containers với user không phải root
- Sử dụng network policies để hạn chế traffic
- Cập nhật base images thường xuyên
- Sử dụng sealed-secrets hoặc external secret manager
- Không bao giờ commit secrets vào Git
Monitoring / Giám Sát
EN:
- Expose metrics endpoint (
/metrics) - Set up alerts for critical issues
- Monitor resource usage and performance
- Use ServiceMonitor for Prometheus integration
VI:
- Expose metrics endpoint (
/metrics) - Thiết lập alerts cho các vấn đề quan trọng
- Theo dõi sử dụng tài nguyên và hiệu suất
- Sử dụng ServiceMonitor cho tích hợp Prometheus
Examples from Project / Ví Dụ Từ Dự Án
Production Deployment / Triển Khai Production
- IAM Service:
deployments/production/kubernetes/iam-service.yaml - ConfigMap:
deployments/production/kubernetes/iam-service-configmap.yaml - Ingress:
deployments/production/kubernetes/ingress.yaml
Staging Deployment / Triển Khai Staging
- IAM Service:
deployments/staging/kubernetes/iam-service.yaml - ConfigMap:
deployments/staging/kubernetes/iam-service-configmap.yaml
Health Check Implementation / Triển Khai Health Check
- Health Controller:
services/iam-service/src/modules/health/health.controller.ts
Quick Reference / Tham Khảo Nhanh
Common Commands / Lệnh Thường Dùng
# Deploy to production
kubectl apply -f deployments/production/kubernetes/ -n production
# Check deployment status
kubectl get deployments -n production
kubectl get pods -n production
kubectl get svc -n production
# View logs
kubectl logs -f deployment/iam-service -n production
kubectl logs -f pod-name -n production --tail=100
# Scale manually
kubectl scale deployment iam-service --replicas=5 -n production
# Update image
kubectl set image deployment/iam-service iam-service=goodgo/iam-service:v1.2.3 -n production
# Rollback
kubectl rollout undo deployment/iam-service -n production
# Port forward for debugging
kubectl port-forward service/iam-service 5001:5001 -n production
# Execute command in pod
kubectl exec -it pod-name -n production -- /bin/sh
# View HPA status
kubectl get hpa -n production
kubectl describe hpa iam-service-hpa -n production
# View resource usage
kubectl top nodes
kubectl top pods -n production
Troubleshooting / Xử Lý Sự Cố
Pod Not Starting / Pod Không Khởi Động:
# Check pod status
kubectl describe pod pod-name -n production
# Check events
kubectl get events -n production --sort-by='.lastTimestamp'
# Check logs
kubectl logs pod-name -n production --previous
ImagePullBackOff:
# Check image name and tag
kubectl describe pod pod-name -n production | grep -i image
# Check image pull secrets
kubectl get secrets -n production
CrashLoopBackOff:
# Check logs of crashed container
kubectl logs pod-name -n production --previous
# Check resource limits
kubectl describe pod pod-name -n production | grep -A 5 Limits
Related Skills / Skills Liên Quan
- Observability & Monitoring - For monitoring deployed services
- Security - For securing Kubernetes deployments
- Project Rules - For service structure and standards