1. Pengenalan Kubernetes
Kubernetes (sering disingkat K8s) adalah platform open-source untuk container orchestration yang mengotomasikan deployment, scaling, dan manajemen aplikasi container. Dikembangkan oleh Google berdasarkan sistem internal mereka bernama Borg, Kubernetes di-donasi ke Cloud Native Computing Foundation (CNCF) pada tahun 2014 dan sekarang menjadi standar industri untuk menjalankan aplikasi container di production.
Bayangkan Anda memiliki ratusan container Docker yang berjalan — beberapa untuk web server, database, message queue, caching, dan monitoring. Mengelola semua container ini secara manual di banyak server adalah tugas yang sangat kompleks. Kubernetes menyelesaikan masalah ini dengan menyediakan platform yang mengotomasikan seluruh siklus hidup container.
Mengapa Kubernetes?
| Fitur | Penjelasan |
|---|---|
| Auto-Scaling | Menambah/mengurangi container otomatis berdasarkan CPU, memory, atau custom metrics |
| Self-Healing | Container yang crash otomatis di-restart atau di-replace |
| Service Discovery | Container bisa saling menemukan dan berkomunikasi via nama service |
| Rolling Updates | Deploy versi baru tanpa downtime — rollback otomatis jika gagal |
| Load Balancing | Distribusi traffic ke container secara otomatis |
| Storage Orchestration | Mount storage dari cloud provider (EBS, GCE, NFS) secara otomatis |
| Secret Management | Kelola password, API keys, dan certificates dengan aman |
| Batch Execution | Jalankan batch job dan cron job selain long-running services |
| Multi-Cloud | Berjalan di AWS, GCP, Azure, on-premise, atau hybrid |
Kubernetes vs Docker Swarm
| Aspek | Kubernetes | Docker Swarm |
|---|---|---|
| Kompleksitas | 🟡 Tinggi (kurva belajar curam) | 🟢 Rendah (mudah setup) |
| Fitur | 🟢 Sangat lengkap | 🟡 Terbatas |
| Auto-scaling | ✅ Built-in | ❌ Manual |
| Ekosistem | 🟢 Sangat luas (CNCF) | 🟡 Terbatas |
| Community | 🟢 Terbesar di industri | 🟡 Kecil |
| Production Ready | ✅ Di semua cloud provider | ⚠️ Terbatas |
| Monitoring | ✅ Prometheus, Grafana | 🟡 Basic |
Before: [Pod v1] [Pod v1] [Pod v1] ← 3 replicas v1
↓
Step 1: [Pod v1] [Pod v1] [Pod v1] [Pod v2] ← maxSurge: 1
↓
Step 2: [Pod v1] [Pod v1] [Pod v2] ← 1 old pod terminated
↓
Step 3: [Pod v1] [Pod v2] [Pod v2] ← continue...
↓
After: [Pod v2] [Pod v2] [Pod v2] ← 3 replicas v2 ✅
maxUnavailable: 0 → Tidak pernah kurang dari desired count
maxSurge: 1 → Maks 1 pod ekstra di atas desired count
6. Namespaces: Isolasi Resource
Namespace memungkinkan Anda membagi cluster Kubernetes menjadi beberapa virtual cluster. Resource dalam namespace yang berbeda terisolasi satu sama lain — sangat berguna untuk memisahkan environment (dev, staging, prod) atau tim yang berbeda dalam satu cluster.
Namespace Commands
# Lihat semua namespaces
kubectl get namespaces
# Default namespaces di Kubernetes:
# default — Namespace default jika tidak dispesifikasi
# kube-system — Komponen sistem Kubernetes
# kube-public — Resource publik (auto-created)
# kube-node-lease — Heartbeat untuk node
# Buat namespace baru
kubectl create namespace development
kubectl create namespace production
# Atau dari YAML
cat <
7. kubectl: Command-Line Interface
kubectl adalah CLI utama untuk berinteraksi dengan Kubernetes cluster. Semua operasi — dari deployment, debugging, hingga administrasi cluster — dilakukan melalui kubectl. Menguasai kubectl adalah kunci untuk bekerja efektif dengan Kubernetes.
kubectl Cheat Sheet
# === CONTEXT & CLUSTER ===
kubectl config get-contexts # Lihat semua context
kubectl config use-context minikube # Switch context
kubectl cluster-info # Info cluster
# === CREATE & APPLY ===
kubectl apply -f manifest.yaml # Create/Update resource
kubectl create deployment nginx --image=nginx # Imperative
kubectl create secret generic my-secret \
--from-literal=password=abc123 # Create secret
# === GET (list resources) ===
kubectl get pods # Pods di current namespace
kubectl get pods -A # Semua namespace
kubectl get pods -o wide # Detail tambahan (IP, node)
kubectl get pods -o yaml # Output dalam YAML
kubectl get pods -l app=web # Filter label
kubectl get pods --field-selector=status.phase=Running
kubectl get all # Semua resource
# === DESCRIBE (detail + events) ===
kubectl describe pod nginx-pod
kubectl describe service web-svc
kubectl describe node minikube
# === LOGS ===
kubectl logs nginx-pod # Log container
kubectl logs nginx-pod -f # Follow (live)
kubectl logs nginx-pod --tail=100 # 100 baris terakhir
kubectl logs nginx-pod -c my-sidecar # Container spesifik
# === EXEC (masuk container) ===
kubectl exec -it nginx-pod -- /bin/sh
kubectl exec -it nginx-pod -- bash
# === DEBUG ===
kubectl port-forward pod/nginx-pod 8080:80
kubectl port-forward svc/web-svc 3000:80
kubectl top pods # Resource usage
kubectl top nodes # Node resource usage
# === EDIT & PATCH ===
kubectl edit deployment web-app # Edit di editor
kubectl patch deployment web-app \
-p '{"spec":{"replicas":5}}' # Quick patch
# === DELETE ===
kubectl delete pod nginx-pod
kubectl delete -f manifest.yaml
kubectl delete pods --all # Semua pods
kubectl delete pods --all -n dev # Di namespace tertentu
# === DIFF & DRY RUN ===
kubectl diff -f manifest.yaml # Lihat perubahan
kubectl apply -f manifest.yaml --dry-run=client
# === OUTPUT FORMATTING ===
kubectl get pods -o json # JSON
kubectl get pods -o yaml # YAML
kubectl get pods -o custom-columns=\
'NAME:.metadata.name,STATUS:.status.phase'
# === LABELS & ANNOTATIONS ===
kubectl label pod nginx-pod env=prod
kubectl annotate pod nginx-pod note="test"
8. ConfigMap & Secrets
Di Kubernetes, konfigurasi dan data sensitif dipisahkan dari kode aplikasi menggunakan ConfigMap untuk konfigurasi umum dan Secrets untuk data sensitif. Ini memungkinkan Anda mengubah konfigurasi tanpa rebuild image Docker.
ConfigMap
# configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
# Key-value pairs
NODE_ENV: "production"
LOG_LEVEL: "info"
API_URL: "https://api.example.com"
PORT: "3000"
# File content
nginx.conf: |
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://localhost:3000;
}
}
---
# Menggunakan ConfigMap di Pod
apiVersion: v1
kind: Pod
metadata:
name: app-pod
spec:
containers:
- name: app
image: my-app:v1.0
# Method 1: Env vars dari ConfigMap
envFrom:
- configMapRef:
name: app-config
# Method 2: Env var spesifik
env:
- name: NODE_ENV
valueFrom:
configMapKeyRef:
name: app-config
key: NODE_ENV
# Method 3: Mount sebagai file
volumeMounts:
- name: config-volume
mountPath: /etc/nginx/conf.d
volumes:
- name: config-volume
configMap:
name: app-config
items:
- key: nginx.conf
path: default.conf
Secrets
# Membuat Secret
# Method 1: kubectl imperative
kubectl create secret generic app-secrets \
--from-literal=DB_PASSWORD=mysecurepass \
--from-literal=API_KEY=abc123xyz \
--from-literal=JWT_SECRET=myjwtsecret
# Method 2: YAML (nilai harus base64 encoded)
apiVersion: v1
kind: Secret
metadata:
name: app-secrets
type: Opaque
data:
DB_PASSWORD: bXlzZWN1cmVwYXNz # base64 dari "mysecurepass"
API_KEY: YWJjMTIzeHl6 # base64 dari "abc123xyz"
JWT_SECRET: bXlqd3RzZWNyZXQ= # base64 dari "myjwtsecret"
# Encode base64
echo -n "mysecurepass" | base64
# Decode base64
echo "bXlzZWN1cmVwYXNz" | base64 -d
---
# Menggunakan Secret di Pod
apiVersion: v1
kind: Pod
metadata:
name: app-pod
spec:
containers:
- name: app
image: my-app:v1.0
# Method 1: Env vars
env:
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: app-secrets
key: DB_PASSWORD
- name: API_KEY
valueFrom:
secretKeyRef:
name: app-secrets
key: API_KEY
# Method 2: Mount sebagai file
volumeMounts:
- name: secrets-volume
mountPath: /etc/secrets
readOnly: true
volumes:
- name: secrets-volume
secret:
secretName: app-secrets
Secrets di Kubernetes hanya di-encode base64, tidak di-encrypt secara default! Aktifkan Encryption at Rest di etcd untuk keamanan production. Gunakan external secret manager seperti AWS Secrets Manager, HashiCorp Vault, atau Azure Key Vault untuk keamanan ekstra.
9. Auto-Scaling
Salah satu fitur paling powerful Kubernetes adalah auto-scaling — kemampuan untuk secara otomatis menyesuaikan jumlah pod dan resource berdasarkan beban aktual. Ini memastikan aplikasi Anda selalu responsif saat traffic tinggi dan hemat biaya saat traffic rendah.
Horizontal Pod Autoscaler (HPA)
# hpa.yaml — Scale pod berdasarkan CPU utilization
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web-app-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web-app
minReplicas: 2 # Minimum pod
maxReplicas: 10 # Maximum pod
metrics:
# Scale jika CPU usage > 70%
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
# Scale jika Memory usage > 80%
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80
behavior:
scaleUp:
stabilizationWindowSeconds: 60
policies:
- type: Pods
value: 2
periodSeconds: 60
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Pods
value: 1
periodSeconds: 120
Manual & Auto Scaling Commands
# === MANUAL SCALING ===
kubectl scale deployment/web-app --replicas=5
# === HPA (Horizontal Pod Autoscaler) ===
# Buat HPA dari YAML
kubectl apply -f hpa.yaml
# Buat HPA imperatif
kubectl autoscale deployment web-app \
--min=2 --max=10 --cpu-percent=70
# Lihat HPA
kubectl get hpa
kubectl describe hpa web-app-hpa
# Hapus HPA
kubectl delete hpa web-app-hpa
# === VPA (Vertical Pod Autoscaler) ===
# Mengubah resource request/limit secara otomatis
# (Memerlukan instalasi VPA terpisah)
# === Cluster Autoscaler ===
# Menambah/mengurangi node secara otomatis
# (Tersedia di cloud provider: EKS, GKE, AKS)
10. Quiz: Uji Pemahamanmu!
Setelah membaca tutorial di atas, jawablah 5 pertanyaan berikut untuk menguji pemahamanmu tentang Kubernetes: