DevOps & Infrastructure
K8s · CI/CD · Monitoring
Thiết kế hạ tầng vận hành cho hệ thống ERP/MES — Kubernetes cluster, CI/CD pipeline tự động, monitoring stack Prometheus/Grafana, và chiến lược bảo mật.
Kubernetes Architecture
Toàn bộ hệ thống chạy trên Kubernetes với namespace phân tách theo domain. Mỗi module của Modular Monolith được deploy như một Deployment riêng, chia sẻ cùng codebase nhưng có thể scale độc lập.
Resource Quotas per Namespace
| Namespace | CPU Request | CPU Limit | Memory | PVC Storage |
|---|---|---|---|---|
erp-mes-app | 4 cores | 16 cores | 8–32 Gi | 50 Gi |
erp-mes-data | 8 cores | 24 cores | 32–64 Gi | 2 Ti |
monitoring | 2 cores | 4 cores | 4–8 Gi | 200 Gi |
Horizontal Pod Autoscaler (HPA)
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: core-service-hpa
namespace: erp-mes-app
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: core-service
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80
behavior:
scaleDown:
stabilizationWindowSeconds: 300 # Không scale down quá nhanh
scaleUp:
stabilizationWindowSeconds: 30
CI/CD Pipeline — GitHub Actions
Blue-Green Deployment cho Production
# Service trỏ vào active slot (blue hoặc green)
apiVersion: v1
kind: Service
metadata:
name: core-service
namespace: erp-mes-app
spec:
selector:
app: core-service
slot: blue # Đổi thành "green" khi swap
ports:
- port: 8080
targetPort: 8080
---
# Deployment GREEN (mới deploy, chưa live)
apiVersion: apps/v1
kind: Deployment
metadata:
name: core-service-green
namespace: erp-mes-app
spec:
replicas: 3
selector:
matchLabels:
app: core-service
slot: green
template:
metadata:
labels:
app: core-service
slot: green
spec:
containers:
- name: core-service
image: ghcr.io/org/erp-mes-core:v1.2.0
# Sau khi verify green healthy → patch Service selector ke green
# Sau 15 phút → delete blue deployment
Blue-Green đảm bảo zero downtime. Rollback chỉ cần 1 lệnh: patch Service selector từ green về blue. Toàn bộ traffic chuyển ngay lập tức mà không restart pod nào.
Monitoring & Observability Stack
Ba trụ cột của Observability: Metrics (Prometheus + Grafana), Logs (Loki), Traces (Tempo / Jaeger). Tất cả được visualize trên Grafana.
Key Metrics cần monitor
| Metric | Tool | Alert threshold | Dashboard |
|---|---|---|---|
| API latency P99 | Prometheus | > 500ms | API Performance |
| Event Store write latency | Prometheus | > 100ms | Event Store Health |
| Kafka consumer lag | Prometheus (JMX) | > 10,000 messages | Kafka Dashboard |
| Outbox pending count | Prometheus (custom) | > 1,000 rows | Outbox Monitor |
| PostgreSQL connections | Prometheus (pg_exporter) | > 80% pool size | Database Health |
| Redis memory usage | Prometheus (redis_exporter) | > 85% | Cache Dashboard |
| OEE per machine | oee_daily_snapshots → Grafana | < 65% | MES Operations |
| Error rate (5xx) | Prometheus (NGINX) | > 1% | API Performance |
Structured Logging Format
{
"timestamp": "2026-06-29T09:15:00.123Z",
"level": "INFO",
"service": "core-service",
"module": "production",
"traceId": "abc123def456",
"spanId": "789xyz",
"tenantId": "tenant_abc",
"userId": "uuid",
"correlationId":"uuid",
"message": "ProductionOrder started successfully",
"orderId": "uuid",
"machineId": "uuid",
"durationMs": 42
}
Security & Secrets Management
Checklist bảo mật
- TLS everywhere: HTTPS tại Ingress, mTLS giữa các service (Istio hoặc Linkerd)
- JWT + RBAC: Token-based auth, role-based access per module và action
- Secrets không trong code: Vault hoặc AWS Secrets Manager, inject qua K8s Secret
- Container scanning: Trivy quét image mỗi CI build — fail build nếu có CVE critical
- Network Policy: Deny all by default, whitelist theo namespace và pod selector
- Pod Security Standards:
restrictedprofile — no root, no privileged - Audit logging: K8s audit log + application audit trail vào Elasticsearch
- Rate limiting: NGINX Ingress + Redis (sliding window, per user/IP)
Infrastructure as Code
| Layer | Tool | Mô tả |
|---|---|---|
| Cloud infra (VPC, EKS, RDS) | Terraform | Provisioning cloud resources — version controlled, plan/apply workflow |
| K8s manifests | Helm Charts | Package K8s resources, values per environment |
| GitOps / CD | ArgoCD | Sync K8s state từ Git repo — drift detection tự động |
| Config management | ConfigMaps | Non-secret config per environment, mounted vào pods |
| Secret management | Vault + ESO | External Secrets Operator sync Vault secrets → K8s Secrets |
Helm Chart Structure
charts/erp-mes/
├── Chart.yaml
├── values.yaml # default values
├── values-dev.yaml # dev overrides
├── values-staging.yaml # staging overrides
├── values-prod.yaml # prod overrides
└── templates/
├── deployment.yaml
├── service.yaml
├── hpa.yaml
├── ingress.yaml
├── configmap.yaml
├── network-policy.yaml
└── serviceaccount.yaml
# Deploy to prod:
helm upgrade --install erp-mes ./charts/erp-mes \
-f values-prod.yaml \
--namespace erp-mes-app \
--atomic \
--timeout 5m
Environment Strategy
| Environment | Branch | Deploy trigger | DB | Kafka |
|---|---|---|---|---|
| DEV | feature/* → develop |
Auto khi merge to develop | Shared PostgreSQL (dev schema) | Single broker |
| STAGING | develop → main |
Auto khi merge to main | Isolated PostgreSQL (prod-like) | 3-broker cluster |
| PRODUCTION | main |
Manual approval → Blue-Green | PostgreSQL HA (primary + replicas) | 3-broker cluster + replication |
Dùng Flyway hoặc Liquibase cho schema migration. Nguyên tắc: Expand-then-Contract — thêm column mới (nullable) trước, deploy app mới, rồi mới xóa column cũ sau vài deploy cycle. Không bao giờ drop column hay rename trong 1 deploy.
Production Readiness Checklist
Checklist trước mỗi Production deploy
| Hạng mục | Kiểm tra | Owner |
|---|---|---|
| Database migration | Flyway migration scripts đã review, không có destructive change | Tech Lead |
| Event schema compatibility | New events backward-compatible với old consumers | Backend Dev |
| Kafka topic setup | New topics đã tạo với partition count phù hợp | DevOps |
| Feature flags | New features ẩn sau flag, không bật mặc định | Dev |
| Rollback plan | Có documented rollback steps, test trên Staging | Tech Lead |
| Monitoring alerts | Alert rules cho feature mới đã setup | DevOps |
| Load test | Staging đã chạy load test với 2x expected traffic | QA |
| Security scan | Trivy scan pass, không có Critical CVE | DevSecOps |