DevOps & Cloud

Kubernetes untuk Pemula: Orchestrate Container

TOKEN

Panduan lengkap belajar Kubernetes dari nol β€” arsitektur K8s, pods, services, deployments, namespaces, kubectl, ConfigMap, Secrets, auto-scaling, dan best practices

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-ScalingMenambah/mengurangi container otomatis berdasarkan CPU, memory, atau custom metrics
Self-HealingContainer yang crash otomatis di-restart atau di-replace
Service DiscoveryContainer bisa saling menemukan dan berkomunikasi via nama service
Rolling UpdatesDeploy versi baru tanpa downtime β€” rollback otomatis jika gagal
Load BalancingDistribusi traffic ke container secara otomatis
Storage OrchestrationMount storage dari cloud provider (EBS, GCE, NFS) secara otomatis
Secret ManagementKelola password, API keys, dan certificates dengan aman
Batch ExecutionJalankan batch job dan cron job selain long-running services
Multi-CloudBerjalan 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
Diagram: Kubernetes High-Level Overview
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    KUBERNETES CLUSTER                            β”‚
β”‚                                                                  β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ CONTROL PLANE ──────────────────────────┐      β”‚
β”‚  β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”          β”‚      β”‚
β”‚  β”‚  β”‚  API     β”‚ β”‚  Scheduler   β”‚ β”‚Controllerβ”‚          β”‚      β”‚
β”‚  β”‚  β”‚  Server  β”‚ β”‚              β”‚ β”‚ Manager  β”‚          β”‚      β”‚
β”‚  β”‚  β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜          β”‚      β”‚
β”‚  β”‚       β”‚         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                      β”‚      β”‚
β”‚  β”‚       └────────►│    etcd      β”‚  (State storage)     β”‚      β”‚
β”‚  β”‚                 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                      β”‚      β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β”‚
β”‚                                                                  β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ NODE 1 ────────┐  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€ NODE 2 ───────┐    β”‚
β”‚  β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”       β”‚  β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”  β”‚    β”‚
β”‚  β”‚  β”‚ Pod A β”‚ β”‚ Pod B β”‚       β”‚  β”‚  β”‚ Pod C β”‚ β”‚ Pod D β”‚  β”‚    β”‚
β”‚  β”‚  β”‚(nginx)β”‚β”‚(app)  β”‚       β”‚  β”‚  β”‚(app)  β”‚β”‚(redis)β”‚  β”‚    β”‚
β”‚  β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”˜       β”‚  β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚    β”‚
β”‚  β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”‚  β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚    β”‚
β”‚  β”‚  β”‚    kubelet       β”‚      β”‚  β”‚  β”‚    kubelet       β”‚  β”‚    β”‚
β”‚  β”‚  β”‚    kube-proxy    β”‚      β”‚  β”‚  β”‚    kube-proxy    β”‚  β”‚    β”‚
β”‚  β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β”‚  β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚    β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

2. Arsitektur Kubernetes

Cluster Kubernetes terdiri dari dua tipe node utama: Control Plane (master node) yang mengelola cluster, dan Worker Nodes yang menjalankan aplikasi container. Pemahaman arsitektur ini sangat penting untuk mengelola cluster dengan efektif.

Control Plane Components

Komponen Fungsi
kube-apiserverFrontend Kubernetes β€” semua komunikasi melewati API server (kubectl, dashboard, internal)
etcdKey-value store yang menyimpan semua data cluster (state, config, secrets). Sangat kritis!
kube-schedulerMemilih node mana yang akan menjalankan pod baru berdasarkan resource, affinity, taints
kube-controller-managerMenjalankan controller loops β€” memastikan state aktual sesuai state yang diinginkan
cloud-controller-managerInterface ke cloud provider (AWS, GCP, Azure) untuk layanan load balancer, storage, dll

Worker Node Components

Komponen Fungsi
kubeletAgent di setiap node yang memastikan container berjalan sesuai pod spec
kube-proxyMengelola jaringan dan iptables rules untuk service networking
Container RuntimeMenjalankan container β€” containerd (default), CRI-O

Setup Local Kubernetes

Bash β€” Install Tools
# === Install kubectl (CLI untuk Kubernetes) ===

# macOS
brew install kubectl

# Linux
curl -LO "https://dl.k8s.io/release/$(curl -L -s \
  https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
chmod +x kubectl && sudo mv kubectl /usr/local/bin/

# Verifikasi
kubectl version --client

# === Install Minikube (local single-node cluster) ===

# macOS
brew install minikube

# Linux
curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64
sudo install minikube-linux-amd64 /usr/local/bin/minikube

# Start cluster
minikube start --driver=docker --cpus=2 --memory=4096

# Cek status
minikube status
kubectl cluster-info
kubectl get nodes

# Alternatif: Docker Desktop sudah include Kubernetes
# (Aktifkan di Settings β†’ Kubernetes β†’ Enable Kubernetes)

# Alternatif: kind (Kubernetes in Docker)
# brew install kind
# kind create cluster

3. Pods: Unit Terkecil Kubernetes

Pod adalah unit terkecil yang bisa di-deploy di Kubernetes. Sebuah pod bisa berisi satu atau beberapa container yang berbagi network namespace (IP address yang sama), storage volumes, dan IPC. Container dalam satu pod bisa saling mengakses melalui localhost.

Pod YAML Definition

YAML β€” Pod Definition
# pod.yaml β€” Pod sederhana dengan satu container
apiVersion: v1
kind: Pod
metadata:
  name: nginx-pod
  labels:
    app: nginx
    environment: development
    version: "1.0"
spec:
  containers:
    - name: nginx
      image: nginx:1.25-alpine
      ports:
        - containerPort: 80
      resources:
        requests:
          memory: "64Mi"
          cpu: "100m"    # 0.1 CPU core
        limits:
          memory: "128Mi"
          cpu: "250m"    # 0.25 CPU core
      livenessProbe:
        httpGet:
          path: /
          port: 80
        initialDelaySeconds: 10
        periodSeconds: 30
      readinessProbe:
        httpGet:
          path: /
          port: 80
        initialDelaySeconds: 5
        periodSeconds: 10

Multi-Container Pod (Sidecar Pattern)

YAML β€” Multi-Container Pod
# multi-container-pod.yaml β€” Sidecar pattern
apiVersion: v1
kind: Pod
metadata:
  name: web-with-logger
  labels:
    app: web
spec:
  containers:
    # Container utama: web app
    - name: web-app
      image: nginx:1.25-alpine
      volumeMounts:
        - name: shared-logs
          mountPath: /var/log/nginx

    # Sidecar container: log collector
    - name: log-collector
      image: busybox
      command: ['sh', '-c', 'tail -f /var/log/nginx/access.log']
      volumeMounts:
        - name: shared-logs
          mountPath: /var/log/nginx

  # Shared volume antara kedua container
  volumes:
    - name: shared-logs
      emptyDir: {}

Perintah Dasar Pod

Bash β€” kubectl Pod Commands
# Buat pod dari YAML
kubectl apply -f pod.yaml

# Buat pod langsung (imperative)
kubectl run nginx-pod --image=nginx:1.25-alpine --port=80

# Lihat semua pods
kubectl get pods
kubectl get pods -o wide         # Lebih detail (IP, node)
kubectl get pods --all-namespaces # Semua namespace

# Lihat detail pod
kubectl describe pod nginx-pod

# Lihat log container
kubectl logs nginx-pod
kubectl logs nginx-pod -f        # Follow (live stream)
kubectl logs nginx-pod -c nginx  # Container spesifik

# Masuk ke dalam container
kubectl exec -it nginx-pod -- /bin/sh

# Port forwarding (akses pod dari localhost)
kubectl port-forward nginx-pod 8080:80
# Buka http://localhost:8080

# Hapus pod
kubectl delete pod nginx-pod
kubectl delete -f pod.yaml

# Force delete pod yang stuck
kubectl delete pod nginx-pod --grace-period=0 --force
πŸ’‘ Tips

Jangan pernah membuat Pod langsung di production! Gunakan Deployment yang akan mengelola pod secara otomatis β€” termasuk restart, scaling, dan rolling updates. Pod langsung hanya untuk debugging dan testing singkat.

4. Services: Networking & Service Discovery

Pod di Kubernetes bersifat ephemeral β€” mereka bisa dihapus, di-restart, atau di-schedule ke node yang berbeda kapan saja. IP address pod pun berubah setiap kali pod di-recreate. Service menyediakan endpoint jaringan yang stabil (ClusterIP) untuk mengakses sekumpulan pod.

Tipe Service

Tipe Fungsi Kapan Digunakan
ClusterIPIP internal cluster (default)Komunikasi antar service di dalam cluster
NodePortExpose port di setiap nodeDevelopment / testing
LoadBalancerCloud load balancer externalProduction β€” expose ke internet
ExternalNameMap service ke DNS externalAkses resource di luar cluster

Service YAML Definitions

YAML β€” Service Definitions
# === ClusterIP Service (default, internal only) ===
apiVersion: v1
kind: Service
metadata:
  name: nginx-service
spec:
  type: ClusterIP  # Default β€” bisa dihilangkan
  selector:
    app: nginx     # Memilih pod dengan label app=nginx
  ports:
    - protocol: TCP
      port: 80           # Port service
      targetPort: 80      # Port container

---
# === NodePort Service (expose di setiap node) ===
apiVersion: v1
kind: Service
metadata:
  name: nginx-nodeport
spec:
  type: NodePort
  selector:
    app: nginx
  ports:
    - protocol: TCP
      port: 80           # Port cluster
      targetPort: 80      # Port container
      nodePort: 30080     # Port di setiap node (30000-32767)

---
# === LoadBalancer Service (cloud provider) ===
apiVersion: v1
kind: Service
metadata:
  name: nginx-lb
spec:
  type: LoadBalancer
  selector:
    app: nginx
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80

Service Discovery

Bash β€” Service Discovery
# Lihat semua services
kubectl get services
kubectl get svc -o wide

# Service bisa diakses dari pod lain via DNS:
# Format: ..svc.cluster.local
#
# Contoh:
# - nginx-service              (same namespace)
# - nginx-service.default      (explicit namespace)
# - nginx-service.default.svc.cluster.local  (FQDN)

# Test dari dalam pod
kubectl exec -it test-pod -- curl http://nginx-service
kubectl exec -it test-pod -- curl http://nginx-service.default.svc.cluster.local

# Cek endpoints yang di-manage oleh service
kubectl get endpoints nginx-service
Diagram: Service Discovery
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Kubernetes Cluster                              β”‚
β”‚                                                  β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”                   β”‚
β”‚  β”‚Pod A β”‚  β”‚Pod B β”‚  β”‚Pod C β”‚  ← labels: app=webβ”‚
β”‚  β”‚:8080 β”‚  β”‚:8080 β”‚  β”‚:8080 β”‚                   β”‚
β”‚  β””β”€β”€β”¬β”€β”€β”€β”˜  β””β”€β”€β”¬β”€β”€β”€β”˜  β””β”€β”€β”¬β”€β”€β”€β”˜                   β”‚
β”‚     β”‚         β”‚         β”‚                        β”‚
β”‚     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                        β”‚
β”‚               β–Ό                                   β”‚
β”‚     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                         β”‚
β”‚     β”‚  Service: web-svc β”‚  ← ClusterIP: 10.96.x β”‚
β”‚     β”‚  port: 80         β”‚     selector: app=web  β”‚
β”‚     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                         β”‚
β”‚               β–²                                   β”‚
β”‚               β”‚                                   β”‚
β”‚     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”                         β”‚
β”‚     β”‚ Pod D: frontend   β”‚                         β”‚
β”‚     β”‚ curl http://web-svcβ”‚  ← DNS: web-svc:80   β”‚
β”‚     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                         β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

5. Deployments: Manajemen Replica

Deployment adalah cara utama untuk menjalankan aplikasi di Kubernetes. Deployment mengelola ReplicaSet, yang pada gilirannya mengelola pod. Deployment menyediakan fitur penting seperti declarative updates, rolling updates, rollback, dan scaling.

Deployment YAML

YAML β€” Deployment
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web-app
  labels:
    app: web
    tier: frontend
spec:
  replicas: 3               # Jumlah pod yang diinginkan
  selector:
    matchLabels:
      app: web               # Harus match dengan pod template labels
  strategy:
    type: RollingUpdate      # Strategi update (default)
    rollingUpdate:
      maxSurge: 1            # Maks 1 pod ekstra saat update
      maxUnavailable: 0      # Semua pod harus tersedia
  template:
    metadata:
      labels:
        app: web
        tier: frontend
    spec:
      containers:
        - name: web-app
          image: my-app:v1.0
          ports:
            - containerPort: 3000
          env:
            - name: NODE_ENV
              value: "production"
            - name: DATABASE_URL
              valueFrom:
                secretKeyRef:
                  name: app-secrets
                  key: database-url
          resources:
            requests:
              memory: "128Mi"
              cpu: "100m"
            limits:
              memory: "256Mi"
              cpu: "500m"
          livenessProbe:
            httpGet:
              path: /health
              port: 3000
            initialDelaySeconds: 15
            periodSeconds: 20
            failureThreshold: 3
          readinessProbe:
            httpGet:
              path: /ready
              port: 3000
            initialDelaySeconds: 5
            periodSeconds: 10

Deployment Commands

Bash β€” Deployment Commands
# Deploy dari file
kubectl apply -f deployment.yaml

# Lihat deployments
kubectl get deployments
kubectl get deploy -o wide

# Lihat replicasets
kubectl get replicasets

# Lihat pods yang di-manage deployment
kubectl get pods -l app=web

# Rolling update (ubah image)
kubectl set image deployment/web-app web-app=my-app:v2.0

# Cek status rollout
kubectl rollout status deployment/web-app

# Lihat history rollout
kubectl rollout history deployment/web-app

# Rollback ke revisi sebelumnya
kubectl rollout undo deployment/web-app

# Rollback ke revisi spesifik
kubectl rollout undo deployment/web-app --to-revision=2

# Scale deployment
kubectl scale deployment/web-app --replicas=5

# Edit deployment langsung
kubectl edit deployment/web-app
Diagram: Rolling Update
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

Bash β€” Namespace Operations
# 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

Bash β€” 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

YAML β€” 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

YAML β€” 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
⚠️ Peringatan Keamanan

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)

YAML β€” 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

Bash β€” 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)
Diagram: Auto-Scaling Layers
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚              KUBERNETES AUTO-SCALING             β”‚
β”‚                                                  β”‚
β”‚  Layer 1: HPA (Horizontal Pod Autoscaler)        β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚ CPU/Memory > threshold?                   β”‚   β”‚
β”‚  β”‚ YES β†’ Add more pods (scale out)           β”‚   β”‚
β”‚  β”‚ NO  β†’ Remove pods (scale in)              β”‚   β”‚
β”‚  β”‚ Range: minReplicas ↔ maxReplicas          β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                                                  β”‚
β”‚  Layer 2: VPA (Vertical Pod Autoscaler)          β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚ Pod butuh lebih banyak CPU/Memory?        β”‚   β”‚
β”‚  β”‚ β†’ Otomatis adjust requests & limits       β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                                                  β”‚
β”‚  Layer 3: Cluster Autoscaler                     β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚ Tidak cukup node untuk pods baru?         β”‚   β”‚
β”‚  β”‚ β†’ Tambah node baru otomatis               β”‚   β”‚
β”‚  β”‚ Node terlalu idle?                        β”‚   β”‚
β”‚  β”‚ β†’ Kurangi node otomatis                   β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

10. Quiz: Uji Pemahamanmu!

Setelah membaca tutorial di atas, jawablah 5 pertanyaan berikut untuk menguji pemahamanmu tentang Kubernetes:

Pertanyaan 1: Apa unit terkecil yang bisa di-deploy di Kubernetes?

a) Container
b) Service
c) Pod
d) Deployment

Pertanyaan 2: Komponen apa yang menyimpan semua data state cluster Kubernetes?

a) kube-apiserver
b) kubelet
c) etcd
d) kube-scheduler

Pertanyaan 3: Tipe Service apa yang menyediakan IP internal cluster saja?

a) NodePort
b) LoadBalancer
c) ExternalName
d) ClusterIP

Pertanyaan 4: Apa fungsi utama Deployment di Kubernetes?

a) Mengelola jaringan antar pod
b) Mengelola replica pod, rolling update, dan rollback
c) Menyimpan konfigurasi aplikasi
d) Mengatur resource quota

Pertanyaan 5: Apa perbedaan antara ConfigMap dan Secret?

a) ConfigMap untuk data besar, Secret untuk data kecil
b) ConfigMap untuk konfigurasi umum, Secret untuk data sensitif (di-encode base64)
c) Tidak ada perbedaan
d) ConfigMap ter-encrypt, Secret tidak
πŸ” Zoom
100%
🎨 Tema