DevOps
Kubernetes: Container Orchestration Cho Production
Master Kubernetes - platform orchestration mạnh mẽ để deploy và quản lý containerized applications ở quy mô lớn
12 phút đọc
NhiTuyen Tech Blog Team
Kubernetes: Container Orchestration Cho Production
Kubernetes (K8s) đã trở thành standard cho container orchestration. Từ startups đến enterprises như Google, Netflix, Spotify - tất cả đều tin dùng K8s để deploy và scale applications. Hãy cùng master công nghệ này!
Kubernetes là gì?
Container Orchestration Platform
Kubernetes tự động hóa việc:
- 🚀 Deploy containers
- 📊 Load balancing
- 🔄 Auto-scaling
- 🏥 Self-healing
- 📦 Storage orchestration
- 🔐 Secret management
# Simple K8s deployment - Powerful results!
apiVersion: apps/v1
kind: Deployment
metadata:
name: webapp
spec:
replicas: 3 # 3 instances tự động!
selector:
matchLabels:
app: webapp
template:
metadata:
labels:
app: webapp
spec:
containers:
- name: webapp
image: myapp:v1.0
ports:
- containerPort: 8080
K8s Architecture
Control Plane Components
┌─────────────────────────────────────┐
│ Control Plane │
│ ┌─────────────────────────────┐ │
│ │ API Server │ │ ← Entry point
│ └─────────────────────────────┘ │
│ ┌──────┐ ┌────────┐ ┌─────────┐ │
│ │ etcd │ │Scheduler│ │Controller│ │
│ └──────┘ └────────┘ └─────────┘ │
└─────────────────────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Worker Nodes │
│ ┌────────────────────────────┐ │
│ │ kubelet │ kube-proxy │ │
│ └────────────────────────────┘ │
│ ┌────────────────────────────┐ │
│ │ Containers │ │
│ │ ┌──┐ ┌──┐ ┌──┐ ┌──┐ │ │
│ │ │ │ │ │ │ │ │ │ │ │
│ │ └──┘ └──┘ └──┘ └──┘ │ │
│ └────────────────────────────┘ │
└─────────────────────────────────────┘
Key Components
- API Server: Communication hub
- etcd: Distributed key-value store
- Scheduler: Assigns pods to nodes
- Controller Manager: Maintains desired state
- kubelet: Agent on each node
- kube-proxy: Network proxy
Core Concepts
1. Pods
Smallest deployable unit trong K8s:
apiVersion: v1
kind: Pod
metadata:
name: nginx-pod
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.25
ports:
- containerPort: 80
resources:
requests:
memory: "64Mi"
cpu: "250m"
limits:
memory: "128Mi"
cpu: "500m"
2. Deployments
Manage application lifecycle:
apiVersion: apps/v1
kind: Deployment
metadata:
name: api-deployment
spec:
replicas: 5
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 1
selector:
matchLabels:
app: api
template:
metadata:
labels:
app: api
spec:
containers:
- name: api
image: mycompany/api:v2.0
ports:
- containerPort: 8080
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
3. Services
Expose và load balance pods:
apiVersion: v1
kind: Service
metadata:
name: api-service
spec:
type: LoadBalancer # External access
selector:
app: api
ports:
- protocol: TCP
port: 80
targetPort: 8080
sessionAffinity: ClientIP # Sticky sessions
4. ConfigMaps & Secrets
# ConfigMap - Non-sensitive config
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
database_host: "postgres.default.svc.cluster.local"
log_level: "info"
max_connections: "100"
---
# Secret - Sensitive data
apiVersion: v1
kind: Secret
metadata:
name: db-secret
type: Opaque
data:
username: YWRtaW4= # base64 encoded
password: cGFzc3dvcmQ= # base64 encoded
Use in Deployment
spec:
containers:
- name: app
image: myapp:latest
env:
# From ConfigMap
- name: DATABASE_HOST
valueFrom:
configMapKeyRef:
name: app-config
key: database_host
# From Secret
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: db-secret
key: password
Namespace Organization
# Development namespace
apiVersion: v1
kind: Namespace
metadata:
name: development
labels:
env: dev
---
# Production namespace
apiVersion: v1
kind: Namespace
metadata:
name: production
labels:
env: prod
# Deploy to specific namespace
kubectl apply -f deployment.yaml -n production
# List pods in namespace
kubectl get pods -n development
# Switch default namespace
kubectl config set-context --current --namespace=production
Scaling
Horizontal Pod Autoscaler
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: api-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: api-deployment
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:
scaleUp:
stabilizationWindowSeconds: 60
policies:
- type: Percent
value: 50
periodSeconds: 60
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Pods
value: 1
periodSeconds: 60
# Auto scale based on CPU/memory! 📊
Manual Scaling
# Scale deployment
kubectl scale deployment api-deployment --replicas=10
# Scale specific resource
kubectl scale --replicas=3 -f deployment.yaml
# Current status
kubectl get hpa
Storage
Persistent Volumes
# PersistentVolume
apiVersion: v1
kind: PersistentVolume
metadata:
name: postgres-pv
spec:
capacity:
storage: 10Gi
accessModes:
- ReadWriteOnce
persistentVolumeReclaimPolicy: Retain
storageClassName: fast
hostPath:
path: /data/postgres
---
# PersistentVolumeClaim
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: postgres-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 10Gi
storageClassName: fast
---
# Use in Pod
spec:
containers:
- name: postgres
image: postgres:15
volumeMounts:
- mountPath: /var/lib/postgresql/data
name: postgres-storage
volumes:
- name: postgres-storage
persistentVolumeClaim:
claimName: postgres-pvc
Networking
Ingress
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: app-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
cert-manager.io/cluster-issuer: "letsencrypt-prod"
spec:
ingressClassName: nginx
tls:
- hosts:
- api.mycompany.com
secretName: api-tls
rules:
- host: api.mycompany.com
http:
paths:
- path: /v1
pathType: Prefix
backend:
service:
name: api-v1-service
port:
number: 80
- path: /v2
pathType: Prefix
backend:
service:
name: api-v2-service
port:
number: 80
Network Policies
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: api-network-policy
spec:
podSelector:
matchLabels:
app: api
policyTypes:
- Ingress
- Egress
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
ports:
- protocol: TCP
port: 8080
egress:
- to:
- podSelector:
matchLabels:
app: database
ports:
- protocol: TCP
port: 5432
# Micro-segmentation security! 🔐
Monitoring & Logging
Prometheus & Grafana
# ServiceMonitor for Prometheus
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: api-monitor
spec:
selector:
matchLabels:
app: api
endpoints:
- port: metrics
interval: 30s
path: /metrics
# Install Prometheus stack
helm repo add prometheus-community \
https://prometheus-community.github.io/helm-charts
helm install prometheus prometheus-community/kube-prometheus-stack \
--namespace monitoring --create-namespace
# Access Grafana
kubectl port-forward -n monitoring \
svc/prometheus-grafana 3000:80
Logging with EFK Stack
# Install Elasticsearch, Fluentd, Kibana
kubectl create namespace logging
# Elasticsearch
kubectl apply -f elasticsearch.yaml -n logging
# Fluentd DaemonSet
kubectl apply -f fluentd-daemonset.yaml -n logging
# Kibana
kubectl apply -f kibana.yaml -n logging
# Centralized logging! 📝
CI/CD Integration
GitOps with ArgoCD
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: myapp
namespace: argocd
spec:
project: default
source:
repoURL: https://github.com/mycompany/app
targetRevision: main
path: k8s
destination:
server: https://kubernetes.default.svc
namespace: production
syncPolicy:
automated:
prune: true
selfHeal: true
syncOptions:
- CreateNamespace=true
# Git = Source of truth! 🎯
Jenkins Pipeline
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'docker build -t myapp:${BUILD_NUMBER} .'
sh 'docker push myrepo/myapp:${BUILD_NUMBER}'
}
}
stage('Deploy to K8s') {
steps {
sh '''
kubectl set image deployment/myapp \
myapp=myrepo/myapp:${BUILD_NUMBER} \
-n production
kubectl rollout status deployment/myapp \
-n production
'''
}
}
stage('Verify') {
steps {
sh '''
kubectl get pods -n production
kubectl get svc -n production
'''
}
}
}
}
Security Best Practices
Pod Security Standards
apiVersion: v1
kind: Namespace
metadata:
name: secure-apps
labels:
pod-security.kubernetes.io/enforce: restricted
pod-security.kubernetes.io/audit: restricted
pod-security.kubernetes.io/warn: restricted
RBAC
# Role
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: production
name: developer
rules:
- apiGroups: [""]
resources: ["pods", "services"]
verbs: ["get", "list", "watch"]
- apiGroups: ["apps"]
resources: ["deployments"]
verbs: ["get", "list", "watch", "update"]
---
# RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: developer-binding
namespace: production
subjects:
- kind: User
name: john@company.com
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role
name: developer
apiGroup: rbac.authorization.k8s.io
Helm Charts
Package Manager for K8s
# Create chart
helm create myapp
# Directory structure
myapp/
├── Chart.yaml
├── values.yaml
├── templates/
│ ├── deployment.yaml
│ ├── service.yaml
│ └── ingress.yaml
└── charts/
# values.yaml
replicaCount: 3
image:
repository: mycompany/app
tag: "1.0.0"
pullPolicy: IfNotPresent
service:
type: LoadBalancer
port: 80
ingress:
enabled: true
host: myapp.com
tls:
enabled: true
resources:
limits:
cpu: 500m
memory: 512Mi
requests:
cpu: 250m
memory: 256Mi
# Install chart
helm install myapp ./myapp
# Upgrade
helm upgrade myapp ./myapp --values values-prod.yaml
# Rollback
helm rollback myapp 1
# Templating power! 📦
Debugging & Troubleshooting
Common Commands
# Pod logs
kubectl logs -f pod-name
kubectl logs pod-name --previous # Previous container
# Execute in pod
kubectl exec -it pod-name -- /bin/bash
# Describe resource
kubectl describe pod pod-name
kubectl describe deployment deployment-name
# Events
kubectl get events --sort-by='.lastTimestamp'
# Port forward
kubectl port-forward pod-name 8080:80
# Top resources
kubectl top nodes
kubectl top pods
# Debug pod
kubectl debug pod-name -it --image=busybox
Production Checklist
✅ Must Have
- Resource limits set
- Health checks configured
- Multiple replicas
- HPA enabled
- Monitoring setup
- Logging configured
- Secrets not hardcoded
- Network policies defined
- RBAC configured
- Backup strategy
- Disaster recovery plan
- Security scanning
- Pod disruption budgets
# Pod Disruption Budget
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: api-pdb
spec:
minAvailable: 2
selector:
matchLabels:
app: api
K8s vs Alternatives
| Feature | Kubernetes | Docker Swarm | Nomad |
|---|---|---|---|
| Complexity | High | Low | Medium |
| Ecosystem | Huge | Small | Medium |
| Scalability | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ |
| Community | Massive | Declining | Growing |
| Cloud Support | Excellent | Limited | Good |
| Learning Curve | Steep | Gentle | Moderate |
Managed K8s Services
- GKE (Google): Best integration, autopilot mode
- EKS (AWS): AWS ecosystem, Fargate support
- AKS (Azure): Azure integration, easy setup
- DigitalOcean: Simple, affordable
- Linode: Developer-friendly
Kết Luận
Kubernetes là must-have skill cho:
- 🚀 DevOps Engineers
- ☁️ Cloud Architects
- 👨💻 Backend Developers
- 🔧 Site Reliability Engineers
# Your K8s journey
apiVersion: career/v1
kind: SkillDevelopment
metadata:
name: kubernetes-mastery
spec:
steps:
- Learn basics (pods, services, deployments)
- Deploy real application
- Setup monitoring & logging
- Implement CI/CD
- Master advanced topics
outcome: "Production-ready K8s expert! 🎯"
# Start learning today! 💪
Bạn đang dùng K8s cho dự án nào? Chia sẻ kinh nghiệm! 💬
Tags
#Kubernetes #K8s #DevOps #Docker #CloudNative #Microservices #Container #Orchestration
Tags:
#Kubernetes
#Docker
#DevOps
#Cloud
#Microservices
#Container
Bài viết liên quan
Bài viết liên quan 1
Bài viết liên quan 2
Bài viết liên quan 3