BÀI 1: GIỚI THIỆU KUBERNETES VÀ CONTAINER ORCHESTRATION
Bài học đầu tiên giới thiệu về Container Orchestration và Kubernetes - nền tảng để hiểu tại sao K8s trở thành tiêu chuẩn công nghiệp. Tìm hiểu lịch sử, kiến trúc cơ bản, và so sánh với các công nghệ tương tự.
BÀI 1: GIỚI THIỆU KUBERNETES VÀ CONTAINER ORCHESTRATION
🎯 MỤC TIÊU BÀI HỌC
Sau khi hoàn thành bài học này, bạn sẽ:
- ✅ Hiểu được Container Orchestration là gì và tại sao cần nó
- ✅ Nắm được vai trò và tầm quan trọng của Kubernetes
- ✅ So sánh được Kubernetes với các công cụ khác
- ✅ Hiểu kiến trúc tổng quan của Kubernetes
- ✅ Biết về Kubernetes ecosystem và cộng đồng
PHẦN 1: CONTAINER ORCHESTRATION LÀ GÌ?
1.1. Vấn đề với Containers khi Scale
Hãy tưởng tượng bạn có một ứng dụng web đơn giản chạy trong Docker container:
docker run -d -p 8080:80 my-web-app
Mọi thứ hoạt động tốt... cho đến khi:
❌ Vấn đề 1: Traffic tăng đột biến
- 1 container không đủ xử lý
- Cần scale lên 10, 20, 100 containers
- Làm thế nào để phân phối traffic?
❌ Vấn đề 2: Container bị crash
- Ai sẽ phát hiện và restart?
- Làm sao đảm bảo uptime 99.9%?
❌ Vấn đề 3: Nhiều servers
- Làm sao deploy containers lên nhiều máy chủ?
- Làm sao quản lý tài nguyên (CPU, RAM) hiệu quả?
❌ Vấn đề 4: Update ứng dụng
- Làm sao rolling update không downtime?
- Rollback nếu có lỗi?
❌ Vấn đề 5: Service Discovery
- Containers có IP động
- Làm sao các services tìm và gọi nhau?
❌ Vấn đề 6: Configuration Management
- Quản lý secrets, configs cho hàng trăm containers
- Môi trường dev, staging, production khác nhau
1.2. Container Orchestration là giải pháp
Container Orchestration là việc tự động hóa deployment, management, scaling, và networking của containers.
Orchestrator làm gì:
┌─────────────────────────────────────────────────────────┐
│ CONTAINER ORCHESTRATION PLATFORM │
├─────────────────────────────────────────────────────────┤
│ ✓ Scheduling - Chọn node phù hợp cho container│
│ ✓ Scaling - Auto scale up/down │
│ ✓ Self-healing - Restart containers failed │
│ ✓ Load Balancing - Phân phối traffic đều │
│ ✓ Service Discovery - Tìm và kết nối services │
│ ✓ Rolling Updates - Update không downtime │
│ ✓ Rollback - Quay lại version cũ │
│ ✓ Secret Management - Quản lý credentials an toàn │
│ ✓ Resource Management- Tối ưu CPU, RAM, Storage │
└─────────────────────────────────────────────────────────┘
1.3. Ví dụ thực tế
Trước khi có Orchestration:
# Trên server 1
ssh server1
docker run -d app:v1
docker run -d app:v1
docker run -d app:v1
# Trên server 2
ssh server2
docker run -d app:v1
docker run -d app:v1
# Manual monitoring
while true; do
docker ps | grep app
# Nếu container die -> manual restart
done
Với Container Orchestration:
# Khai báo mong muốn
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 5 # Muốn 5 containers
template:
spec:
containers:
- name: app
image: app:v1
Orchestrator tự động:
- Deploy 5 containers lên các servers khác nhau
- Monitor và restart nếu crash
- Load balance traffic
- Scale khi cần
PHẦN 2: TẠI SAO CẦN KUBERNETES?
2.1. Bối cảnh ra đời
Google's Borg (2003-2015)
- Google chạy hàng tỷ containers mỗi tuần
- Borg: hệ thống internal để quản lý containers
- Kinh nghiệm 15+ năm vận hành large-scale systems
Kubernetes ra đời (2014)
- Google open-source Kubernetes (K8s)
- Dựa trên kinh nghiệm từ Borg và Omega
- Được thiết kế cho cloud-native applications
- Donate cho CNCF (Cloud Native Computing Foundation)
2.2. Tại sao Kubernetes thắng thế?
1. Production-Proven
Google → 15+ năm kinh nghiệm
↓
Kubernetes → Battle-tested tại Google
↓
Cộng đồng → Hàng nghìn companies đóng góp
2. Vendor Agnostic
- Chạy được ở mọi nơi: on-premise, cloud, hybrid
- Không bị lock-in với 1 cloud provider
- Portable giữa AWS, GCP, Azure, bare metal
3. Extensible và Flexible
- Plugin architecture
- Custom Resource Definitions (CRDs)
- Operator pattern
- Rich ecosystem
4. Large Community
- 100,000+ contributors
- Hàng triệu users
- Mature tooling và documentation
- Active development
5. Industry Standard
CNCF Graduated Project
↓
Được tích hợp bởi:
- AWS (EKS)
- Google (GKE)
- Azure (AKS)
- IBM (IKS)
- DigitalOcean
- và nhiều vendor khác
2.3. Con số ấn tượng
📊 Kubernetes Adoption (2024)
- 96% organizations đang dùng hoặc đánh giá K8s
- 5.6 triệu developers sử dụng K8s
- Top 2 most wanted platform (Stack Overflow)
- 89% containers chạy trên K8s
🚀 Use Cases
- Microservices architecture
- CI/CD pipelines
- Machine Learning workloads
- Big Data processing
- Hybrid/Multi-cloud deployments
PHẦN 3: SO SÁNH KUBERNETES VỚI CÁC CÔNG CỤ KHÁC
3.1. Kubernetes vs Docker Swarm
| Tiêu chí | Kubernetes | Docker Swarm |
|---|---|---|
| Độ phức tạp | Cao, nhiều concepts | Đơn giản, dễ học |
| Setup | Phức tạp hơn | Rất đơn giản |
| Scalability | Rất tốt (1000+ nodes) | Tốt (100+ nodes) |
| Ecosystem | Rất rộng | Hạn chế |
| Auto-scaling | Native HPA, VPA | Limited |
| Load Balancing | Advanced (Ingress) | Basic |
| Community | Rất lớn | Nhỏ hơn nhiều |
| Enterprise Support | Tất cả cloud providers | Limited |
| Learning Curve | Steep | Gentle |
| Production Ready | Yes | Yes (nhưng ít dùng) |
Kết luận: Docker Swarm dễ hơn nhưng K8s mạnh hơn và là industry standard.
3.2. Kubernetes vs Apache Mesos
| Tiêu chí | Kubernetes | Apache Mesos |
|---|---|---|
| Focus | Container orchestration | General purpose cluster manager |
| Architecture | Monolithic | Two-level (Mesos + Marathon) |
| Adoption | Rất cao | Trung bình |
| Use Cases | Containers, microservices | Containers, Big Data, analytics |
| Complexity | Cao | Rất cao |
| Container Support | Native | Via Marathon/DC/OS |
Kết luận: Mesos linh hoạt hơn nhưng phức tạp hơn. K8s tập trung vào containers.
3.3. Kubernetes vs Nomad
| Tiêu chí | Kubernetes | HashiCorp Nomad |
|---|---|---|
| Simplicity | Complex | Simple |
| Workload Types | Containers | Containers, VMs, binaries |
| Ecosystem | Huge | Growing |
| Multi-cloud | Excellent | Excellent |
| Adoption | Very high | Moderate |
| HashiCorp Integration | Limited | Native (Vault, Consul) |
Kết luận: Nomad đơn giản hơn và đa dạng workloads, nhưng ecosystem nhỏ hơn.
3.4. Khi nào dùng gì?
Chọn Kubernetes khi:
- ✅ Production workloads quan trọng
- ✅ Cần scale lớn (100+ services)
- ✅ Team có kinh nghiệm DevOps
- ✅ Cần ecosystem phong phú
- ✅ Multi-cloud strategy
Chọn Docker Swarm khi:
- ✅ Team nhỏ, dự án đơn giản
- ✅ Cần deploy nhanh
- ✅ Đã quen với Docker CLI
- ✅ Không cần scale quá lớn
Chọn Nomad khi:
- ✅ Workloads đa dạng (không chỉ containers)
- ✅ Đã dùng HashiCorp stack
- ✅ Cần simplicity
- ✅ Edge computing
PHẦN 4: KIẾN TRÚC KUBERNETES TỔNG QUAN
4.1. Kubernetes Cluster
┌────────────────────────────────────────────────────────────┐
│ KUBERNETES CLUSTER │
├────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────────────┐ ┌────────────────────────┐│
│ │ CONTROL PLANE │ │ WORKER NODES ││
│ │ (Master Nodes) │ │ ││
│ │ │ │ ┌──────────────────┐ ││
│ │ ┌────────────────┐ │ │ │ Node 1 │ ││
│ │ │ API Server │ │◄────►│ │ - kubelet │ ││
│ │ └────────────────┘ │ │ │ - kube-proxy │ ││
│ │ │ │ │ - Container │ ││
│ │ ┌────────────────┐ │ │ │ Runtime │ ││
│ │ │ etcd │ │ │ │ - Pods │ ││
│ │ │ (Database) │ │ │ └──────────────────┘ ││
│ │ └────────────────┘ │ │ ││
│ │ │ │ ┌──────────────────┐ ││
│ │ ┌────────────────┐ │ │ │ Node 2 │ ││
│ │ │ Scheduler │ │ │ │ - kubelet │ ││
│ │ └────────────────┘ │ │ │ - kube-proxy │ ││
│ │ │ │ │ - Container │ ││
│ │ ┌────────────────┐ │ │ │ Runtime │ ││
│ │ │ Controller │ │ │ │ - Pods │ ││
│ │ │ Manager │ │ │ └──────────────────┘ ││
│ │ └────────────────┘ │ │ ││
│ └──────────────────────┘ │ ┌──────────────────┐ ││
│ │ │ Node N │ ││
│ │ │ ... │ ││
│ │ └──────────────────┘ ││
│ └────────────────────────┘│
└────────────────────────────────────────────────────────────┘
4.2. Control Plane Components (Master)
1. API Server 🚪
- "Cổng vào" của Kubernetes
- Xử lý tất cả REST requests
- Authentication & Authorization
- Validate và process requests
- Frontend cho etcd
kubectl → API Server → etcd
↑ ↓
└──── Response
2. etcd 💾
- Key-value database
- Lưu trữ toàn bộ cluster state
- Source of truth
- Highly available (HA setup)
- Only API Server talks to etcd
3. Scheduler 📅
- Quyết định Pod chạy trên Node nào
- Xem xét: resources, constraints, affinity
- Không thực hiện deploy (kubelet làm)
Flow:
1. User tạo Pod
2. Scheduler xem Pods chưa assign
3. Chọn Node tốt nhất
4. Update Pod spec với nodeName
4. Controller Manager 🎮
- Chạy nhiều controllers
- Monitor cluster state
- Thực hiện changes để đạt desired state
Các controllers quan trọng:
- Node Controller: Monitor nodes health
- Replication Controller: Đảm bảo số Pods đúng
- Endpoints Controller: Populate Endpoints objects
- ServiceAccount Controller: Tạo default ServiceAccounts
4.3. Worker Node Components
1. kubelet 👷
- Agent chạy trên mỗi node
- Nhận Pod specs từ API Server
- Đảm bảo containers đang chạy
- Report node/pod status về API Server
- Execute liveness/readiness probes
2. kube-proxy 🔀
- Network proxy trên mỗi node
- Maintain network rules
- Implement Kubernetes Service abstraction
- Load balancing cho Services
- Modes: iptables, IPVS, userspace
3. Container Runtime 🐳
- Software chạy containers
- Implement Kubernetes CRI (Container Runtime Interface)
- Phổ biến:
- containerd (recommended)
- CRI-O
- Docker (deprecated in K8s 1.24+)
4.4. Add-ons (Optional but Important)
DNS (CoreDNS)
- Service discovery
- Resolve service names to IPs
- Mỗi Service có DNS name
Dashboard
- Web UI để quản lý cluster
- Visualize resources
Monitoring (Metrics Server)
- Collect resource metrics
- CPU, Memory usage
- Enable HPA (Horizontal Pod Autoscaler)
Logging
- EFK Stack (Elasticsearch, Fluentd, Kibana)
- Centralized logging
PHẦN 5: KUBERNETES ECOSYSTEM
5.1. CNCF Landscape
Kubernetes là một phần của CNCF ecosystem:
┌─────────────────────────────────────────────┐
│ CNCF CLOUD NATIVE LANDSCAPE │
├─────────────────────────────────────────────┤
│ Container Orchestration │
│ └─ Kubernetes ⭐ │
│ │
│ Container Runtime │
│ └─ containerd, CRI-O │
│ │
│ Service Mesh │
│ └─ Istio, Linkerd, Consul │
│ │
│ Monitoring │
│ └─ Prometheus, Grafana │
│ │
│ Logging │
│ └─ Fluentd, Loki │
│ │
│ CI/CD │
│ └─ Argo, Flux, Tekton │
│ │
│ Security │
│ └─ Falco, OPA, Trivy │
└─────────────────────────────────────────────┘
5.2. Core Tools
Package Management
- Helm: Package manager for K8s
- Kustomize: Configuration management
GitOps
- ArgoCD: Declarative GitOps CD
- Flux: GitOps toolkit
Service Mesh
- Istio: Complete service mesh
- Linkerd: Simple, lightweight
Monitoring & Observability
- Prometheus: Metrics collection
- Grafana: Visualization
- Jaeger: Distributed tracing
Security
- Falco: Runtime security
- OPA: Policy engine
- Trivy: Vulnerability scanner
5.3. Managed Kubernetes Services
Major Cloud Providers:
- AWS: EKS (Elastic Kubernetes Service)
- Google Cloud: GKE (Google Kubernetes Engine)
- Azure: AKS (Azure Kubernetes Service)
- IBM Cloud: IKS
- DigitalOcean: DOKS
- Linode: LKE
Lợi ích:
- Control plane được managed
- Automatic upgrades
- Integrated với cloud services
- Easy setup
- Cost: chỉ trả tiền worker nodes
PHẦN 6: KUBERNETES CONCEPTS QUAN TRỌNG
6.1. Declarative vs Imperative
Imperative (Cách cũ):
# Nói K8s phải làm GÌ và NHƯ THẾ NÀO
kubectl run nginx --image=nginx
kubectl expose deployment nginx --port=80
kubectl scale deployment nginx --replicas=3
Declarative (Cách K8s):
# Nói K8s muốn KẾT QUẢ gì
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
spec:
replicas: 3
template:
spec:
containers:
- name: nginx
image: nginx
---
apiVersion: v1
kind: Service
metadata:
name: nginx
spec:
ports:
- port: 80
kubectl apply -f nginx.yaml
Tại sao Declarative tốt hơn:
- ✅ Infrastructure as Code
- ✅ Version control friendly
- ✅ Idempotent (chạy nhiều lần = kết quả giống nhau)
- ✅ Self-healing
- ✅ Easy rollback
6.2. Desired State vs Current State
┌──────────────────────────────────────────────┐
│ KUBERNETES RECONCILIATION LOOP │
├──────────────────────────────────────────────┤
│ │
│ ┌────────────────┐ ┌────────────────┐│
│ │ DESIRED STATE │ │ CURRENT STATE ││
│ │ │ │ ││
│ │ replicas: 3 │ VS │ replicas: 2 ││
│ │ image: v2 │ │ image: v1 ││
│ └────────────────┘ └────────────────┘│
│ │ │ │
│ └───────────┬───────────┘ │
│ ↓ │
│ ┌──────────────────┐ │
│ │ CONTROLLER │ │
│ │ Takes Action │ │
│ └──────────────────┘ │
│ ↓ │
│ ┌──────────────────┐ │
│ │ Start 1 Pod │ │
│ │ Update 2 Pods │ │
│ └──────────────────┘ │
└──────────────────────────────────────────────┘
Controllers liên tục:
- Watch current state
- Compare với desired state
- Take actions để match
- Repeat (reconciliation loop)
6.3. Labels và Selectors
Labels = Key-value pairs để organize objects
metadata:
labels:
app: nginx
tier: frontend
environment: production
version: v1.0
Selectors = Query để tìm objects
selector:
matchLabels:
app: nginx
tier: frontend
Use cases:
- Services tìm Pods
- Deployments quản lý Pods
- NetworkPolicies áp dụng rules
- Queries và filtering
PHẦN 7: KUBERNETES IN ACTION - VÍ DỤ THỰC TẾ
Scenario: E-commerce Website
Requirements:
- Frontend: React app (3 replicas)
- Backend API: Node.js (5 replicas, auto-scale)
- Database: PostgreSQL (1 instance, persistent)
- Cache: Redis (3 replicas)
- High availability
- Zero-downtime updates
- Auto-scaling based on traffic
Kubernetes giải quyết như thế nào:
# Frontend Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: frontend
spec:
replicas: 3
selector:
matchLabels:
app: frontend
template:
metadata:
labels:
app: frontend
spec:
containers:
- name: react-app
image: myapp/frontend:v1.0
ports:
- containerPort: 3000
resources:
requests:
memory: "128Mi"
cpu: "100m"
limits:
memory: "256Mi"
cpu: "200m"
---
# Backend API with Auto-scaling
apiVersion: apps/v1
kind: Deployment
metadata:
name: backend
spec:
replicas: 5
selector:
matchLabels:
app: backend
template:
metadata:
labels:
app: backend
spec:
containers:
- name: api
image: myapp/backend:v1.0
ports:
- containerPort: 8080
---
# Auto-scaler
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: backend-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: backend
minReplicas: 5
maxReplicas: 20
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
---
# Database with Persistent Storage
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgres
spec:
serviceName: postgres
replicas: 1
selector:
matchLabels:
app: postgres
template:
metadata:
labels:
app: postgres
spec:
containers:
- name: postgres
image: postgres:14
ports:
- containerPort: 5432
volumeMounts:
- name: postgres-storage
mountPath: /var/lib/postgresql/data
volumeClaimTemplates:
- metadata:
name: postgres-storage
spec:
accessModes: [ "ReadWriteOnce" ]
resources:
requests:
storage: 20Gi
---
# Load Balancer Service
apiVersion: v1
kind: Service
metadata:
name: frontend-lb
spec:
type: LoadBalancer
selector:
app: frontend
ports:
- port: 80
targetPort: 3000
Kubernetes tự động:
- ✅ Deploy 3 frontend + 5 backend + 1 DB
- ✅ Distribute across nodes
- ✅ Restart nếu crash
- ✅ Scale backend từ 5→20 khi traffic tăng
- ✅ Load balance requests
- ✅ Persistent data cho database
- ✅ Rolling update không downtime
💡 KEY TAKEAWAYS
Điểm quan trọng cần nhớ:
- Container Orchestration giải quyết vấn đề scale và manage containers
- Auto-scaling, self-healing, load balancing
- Service discovery, rolling updates
- Kubernetes là industry standard
- Production-proven từ Google
- Largest community
- Vendor agnostic
- K8s Architecture có 2 phần chính:
- Control Plane: API Server, etcd, Scheduler, Controllers
- Worker Nodes: kubelet, kube-proxy, Container Runtime
- Declarative > Imperative
- Khai báo desired state
- K8s tự động reconcile
- Rich Ecosystem
- CNCF landscape
- Tools cho mọi needs
- Managed services available
🎯 BÀI TẬP
Bài tập 1: Research và So sánh
Tìm hiểu và viết so sánh chi tiết (200-300 từ) giữa:
- Kubernetes
- Docker Swarm
- Amazon ECS
Tập trung vào: ease of use, scalability, ecosystem, cost.
Bài tập 2: Mindmap
Vẽ mindmap (có thể dùng tool hoặc tay) về:
- Kubernetes Architecture
- Bao gồm tất cả components
- Mô tả vai trò mỗi component
Bài tập 3: Use Case Analysis
Chọn 1 application bạn đang làm việc hoặc biết:
- Mô tả architecture hiện tại
- Vẽ diagram nếu deploy lên K8s
- List benefits và challenges
Bài tập 4: Video Learning
Xem video "Kubernetes in 100 seconds" và "Kubernetes Explained in 15 minutes"
- Tóm tắt 5 điểm chính
- Note những điểm chưa hiểu để tìm hiểu thêm
📖 TÀI LIỆU THAM KHẢO
Bài viết
- Kubernetes Official Docs - Concepts
- CNCF Kubernetes Overview
- The Illustrated Children's Guide to Kubernetes
Videos
Interactive
⏭️ BÀI TIẾP THEO
Bài 2: Cài đặt và Cấu hình Kubernetes
Trong bài tiếp theo, chúng ta sẽ:
- Cài đặt Minikube và kubectl
- Khởi động cluster đầu tiên
- Explore Kubernetes dashboard
- Chạy các lệnh kubectl cơ bản
- Hiểu về kubeconfig
Chuẩn bị:
- Máy tính với ít nhất 4GB RAM
- Cài đặt Docker
- Cài đặt VirtualBox hoặc VMware