Kubernetes untuk Pemula — Panduan Lengkap Container Orchestration

Kubernetes untuk Pemula — Panduan Lengkap Container Orchestration

13/10/2025 DevOps By Tech Writers
KubernetesDockerDevOpsContainersOrchestration

Pengenalan: Container Orchestration di Era Cloud-Native

Kubernetes telah menjadi de facto standard untuk orchestration containerized applications di production environment. Dengan pertumbuhan eksplosif microservices architecture dan cloud-native development, pemahaman tentang Kubernetes bukan lagi optional skill tetapi necessity bagi setiap infrastructure engineer dan DevOps professional.

Kubernetes menyederhanakan deployment, scaling, dan management dari containerized applications di cluster servers. Ini menangani complex tasks seperti load balancing, automatic scaling, rolling updates, self-healing, dan resource management — memungkinkan teams untuk fokus pada business logic daripada infrastructure management. Dalam panduan comprehensive ini, kita akan menjelajahi Kubernetes dari fundamental concepts hingga production-ready deployments.

Daftar Isi

Kubernetes Architecture

Kubernetes menggunakan master-worker (control plane-worker) architecture. Memahami komponen-komponen ini adalah essential untuk deployment dan troubleshooting.

Control Plane Components

┌─────────────────────────────────────────┐
│         CONTROL PLANE (MASTER)          │
├─────────────────────────────────────────┤
│ API Server     - REST API untuk K8s     │
│ Scheduler      - Assign pods ke nodes   │
│ Controller Mgr - Jalankan controllers   │
│ etcd           - Key-value datastore    │
│ Cloud Ctrl Mgr - Integrate cloud API    │
└─────────────────────────────────────────┘

┌──────────────────────────────────────────────────┐
│            WORKER NODES (MULTIPLE)               │
├──────────────────────────────────────────────────┤
│ Node 1: Kubelet + Container Runtime + kube-proxy│
│ Node 2: Kubelet + Container Runtime + kube-proxy│
│ Node 3: Kubelet + Container Runtime + kube-proxy│
└──────────────────────────────────────────────────┘

API Server: Entry point untuk semua Kubernetes operations. Menerima REST requests dan meng-update etcd.

Scheduler: Menentukan node mana untuk menjalankan pod berdasarkan resource requirements dan constraints.

Controller Manager: Menjalankan controller loops yang manage resources (Deployment Controller, StatefulSet Controller, dll).

etcd: Distributed key-value store yang menyimpan semua cluster state dan configuration.

Core Concepts: Pods, Deployments, Services

Tiga konsep fundamental ini membentuk building blocks dari Kubernetes applications.

Pods

Pod adalah smallest deployable unit di Kubernetes — minimal bisa 1 container, biasanya 1 container per pod.

# pod.yaml - Minimal Pod definition
apiVersion: v1
kind: Pod
metadata:
  name: simple-pod
  namespace: default
  labels:
    app: web
spec:
  containers:
  - name: nginx
    image: nginx:1.21
    ports:
    - containerPort: 80
  restartPolicy: Always
# Deploy pod
kubectl apply -f pod.yaml

# Check pod status
kubectl get pods
kubectl describe pod simple-pod
kubectl logs simple-pod

# Execute command inside pod
kubectl exec -it simple-pod -- /bin/bash

# Delete pod
kubectl delete pod simple-pod

Deployments

Deployments manage pod replicas dengan automatic rollout dan rollback capabilities. Ini adalah primary way untuk manage stateless applications.

# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3  # 3 pod instances
  selector:
    matchLabels:
      app: nginx
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1        # 1 pod lebih dari desired
      maxUnavailable: 0  # 0 pod unavailable
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.21
        ports:
        - containerPort: 80
        resources:
          requests:
            memory: "64Mi"
            cpu: "100m"
          limits:
            memory: "128Mi"
            cpu: "200m"
# Deploy
kubectl apply -f deployment.yaml

# Check rollout status
kubectl rollout status deployment/nginx-deployment

# Update image (trigger rolling update)
kubectl set image deployment/nginx-deployment \
  nginx=nginx:1.22 --record

# View rollout history
kubectl rollout history deployment/nginx-deployment

# Rollback ke version sebelumnya
kubectl rollout undo deployment/nginx-deployment

Services

Service adalah abstraction yang expose aplikasi running di pods dengan static IP dan DNS name. Ini enable stable networking untuk applications.

# service.yaml
apiVersion: v1
kind: Service
metadata:
  name: nginx-service
spec:
  type: LoadBalancer  # atau ClusterIP, NodePort
  selector:
    app: nginx
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80
    nodePort: 30000  # hanya untuk NodePort

Service Types:

  • ClusterIP: Internal service, accessible hanya dari dalam cluster
  • NodePort: Expose service pada port node, accessible externally
  • LoadBalancer: Cloud provider load balancer yang distribute traffic
  • ExternalName: Map service ke external DNS name
# Create service
kubectl apply -f service.yaml

# Get service info
kubectl get service
kubectl describe service nginx-service

# Port forward untuk local testing
kubectl port-forward service/nginx-service 8080:80
# Sekarang accessible di http://localhost:8080

StatefulSets dan DaemonSets

Selain Deployments, ada specialized workload types untuk specific use cases.

StatefulSets

StatefulSets manage stateful applications dengan stable network identity dan persistent storage.

# statefulset.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: mysql
spec:
  serviceName: mysql  # Headless service
  replicas: 3
  selector:
    matchLabels:
      app: mysql
  template:
    metadata:
      labels:
        app: mysql
    spec:
      containers:
      - name: mysql
        image: mysql:8.0
        ports:
        - containerPort: 3306
        volumeMounts:
        - name: data
          mountPath: /var/lib/mysql
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: [ "ReadWriteOnce" ]
      storageClassName: fast-ssd
      resources:
        requests:
          storage: 10Gi

Pods akan named sebagai: mysql-0, mysql-1, mysql-2 (stable identities)

DaemonSets

DaemonSet memastikan setiap node menjalankan copy dari pod (untuk logging, monitoring, dll).

# daemonset.yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: fluentd
  namespace: kube-system
spec:
  selector:
    matchLabels:
      name: fluentd
  template:
    metadata:
      labels:
        name: fluentd
    spec:
      containers:
      - name: fluentd
        image: fluent/fluentd:v1.14
        volumeMounts:
        - name: varlog
          mountPath: /var/log
      volumes:
      - name: varlog
        hostPath:
          path: /var/log

ConfigMaps dan Secrets

ConfigMaps

ConfigMaps untuk menyimpan non-sensitive configuration data.

# configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  APP_ENV: production
  LOG_LEVEL: info
  config.yaml: |
    database:
      host: db.example.com
      port: 5432
# Menggunakan ConfigMap di pod
apiVersion: v1
kind: Pod
metadata:
  name: app-pod
spec:
  containers:
  - name: app
    image: myapp:1.0
    env:
    - name: APP_ENV
      valueFrom:
        configMapKeyRef:
          name: app-config
          key: APP_ENV
    volumeMounts:
    - name: config
      mountPath: /etc/config
  volumes:
  - name: config
    configMap:
      name: app-config

Secrets

Secrets untuk sensitive data seperti passwords, API keys, credentials.

# secret.yaml
apiVersion: v1
kind: Secret
metadata:
  name: db-credentials
type: Opaque
stringData:
  username: admin
  password: secretpassword123
  # Atau base64 encoded:
  # data:
  #   username: YWRtaW4=
  #   password: c2VjcmV0cGFzc3dvcmQxMjM=
# Menggunakan Secret
apiVersion: v1
kind: Pod
metadata:
  name: app-pod
spec:
  containers:
  - name: app
    image: myapp:1.0
    env:
    - name: DB_USER
      valueFrom:
        secretKeyRef:
          name: db-credentials
          key: username
    - name: DB_PASS
      valueFrom:
        secretKeyRef:
          name: db-credentials
          key: password

Storage dan Persistence

PersistentVolume (PV) dan PersistentVolumeClaim (PVC)

# persistent-volume.yaml
apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv-local
spec:
  capacity:
    storage: 20Gi
  accessModes:
    - ReadWriteOnce
  storageClassName: local-storage
  hostPath:
    path: /mnt/data

---
# persistent-volume-claim.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: pvc-local
spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: local-storage
  resources:
    requests:
      storage: 10Gi

---
# Pod menggunakan PVC
apiVersion: v1
kind: Pod
metadata:
  name: app-with-storage
spec:
  containers:
  - name: app
    image: myapp:1.0
    volumeMounts:
    - name: data
      mountPath: /data
  volumes:
  - name: data
    persistentVolumeClaim:
      claimName: pvc-local

Networking dan Ingress

Network Policies

# network-policy.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: deny-all
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  - Egress

---
# Allow traffic from specific pods
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-frontend-to-backend
spec:
  podSelector:
    matchLabels:
      app: backend
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: frontend
    ports:
    - protocol: TCP
      port: 8080

Ingress

Ingress manage external HTTP(S) access ke services dalam cluster.

# ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: app-ingress
  annotations:
    cert-manager.io/cluster-issuer: letsencrypt-prod
spec:
  ingressClassName: nginx
  tls:
  - hosts:
    - app.example.com
    secretName: app-tls
  rules:
  - host: app.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: app-service
            port:
              number: 80
      - path: /api
        pathType: Prefix
        backend:
          service:
            name: api-service
            port:
              number: 3000

Resource Management dan Limits

# resource-limits.yaml
apiVersion: v1
kind: Pod
metadata:
  name: resource-managed-pod
spec:
  containers:
  - name: app
    image: myapp:1.0
    resources:
      # Minimum resources yang dijamin
      requests:
        memory: "128Mi"
        cpu: "100m"
      # Maximum resources yang allowed
      limits:
        memory: "256Mi"
        cpu: "500m"
# namespace-quota.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: production

---
apiVersion: v1
kind: ResourceQuota
metadata:
  name: compute-quota
  namespace: production
spec:
  hard:
    requests.cpu: "10"
    requests.memory: 20Gi
    limits.cpu: "20"
    limits.memory: 40Gi
    pods: "100"

Health Checks dan Auto-Healing

# health-checks.yaml
apiVersion: v1
kind: Pod
metadata:
  name: app-with-health-checks
spec:
  containers:
  - name: app
    image: myapp:1.0
    livenessProbe:
      httpGet:
        path: /health
        port: 8080
      initialDelaySeconds: 10
      periodSeconds: 10
      failureThreshold: 3
    readinessProbe:
      httpGet:
        path: /ready
        port: 8080
      initialDelaySeconds: 5
      periodSeconds: 5
    startupProbe:
      tcpSocket:
        port: 8080
      failureThreshold: 30
      periodSeconds: 10

Scaling dan Auto-Scaling

Manual Scaling

# Scale deployment ke 5 replicas
kubectl scale deployment nginx-deployment --replicas=5

Horizontal Pod Autoscaler (HPA)

# hpa.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: app-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: myapp
  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

Security Best Practices

# secure-pod.yaml
apiVersion: v1
kind: Pod
metadata:
  name: secure-pod
spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 1000
  containers:
  - name: app
    image: myapp:1.0
    securityContext:
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true
      capabilities:
        drop:
        - ALL
    volumeMounts:
    - name: tmp
      mountPath: /tmp
  volumes:
  - name: tmp
    emptyDir: {}

Monitoring dan Logging

# monitoring setup dengan Prometheus
apiVersion: v1
kind: Service
metadata:
  name: prometheus
  labels:
    app: prometheus
spec:
  ports:
  - port: 9090
  selector:
    app: prometheus

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: prometheus
spec:
  replicas: 1
  selector:
    matchLabels:
      app: prometheus
  template:
    metadata:
      labels:
        app: prometheus
    spec:
      containers:
      - name: prometheus
        image: prom/prometheus:latest
        ports:
        - containerPort: 9090

Kesimpulan

Kubernetes adalah powerful platform untuk orchestration containerized applications dalam production environments. Dengan memahami core concepts seperti Pods, Deployments, Services, StatefulSets, ConfigMaps, Secrets, dan networking, Kamu memiliki foundation yang solid untuk building scalable dan resilient applications.

Checklist untuk Production Kubernetes Deployment:

  • ✓ Implementasikan resource requests dan limits
  • ✓ Setup health checks (liveness, readiness, startup probes)
  • ✓ Configure HPA untuk automatic scaling
  • ✓ Implementasikan Network Policies untuk security
  • ✓ Setup monitoring dengan Prometheus dan Grafana
  • ✓ Configure logging dengan ELK atau Loki
  • ✓ Backup etcd regularly
  • ✓ Implement security policies dan RBAC
  • ✓ Regular cluster updates dan patching
  • ✓ Disaster recovery planning

### Deployment
Manage Pods dan ReplicaSets

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
      - name: app
        image: my-app:latest

Services

Expose Pods ke network

apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  ports:
  - port: 80
    targetPort: 8080
  selector:
    app: my-app

Kubernetes adalah future of cloud deployment!