# Kubernetes Quick Reference

> 🚀 **Catatan Cepat**: Panduan praktis untuk daily operations Kubernetes

***

## 🎯 **Essential Commands**

### **📊 Cluster Information**

```bash
# Cluster status dan info
kubectl cluster-info
kubectl get nodes -o wide
kubectl top nodes
kubectl version --short

# Resource usage
kubectl describe node <node-name>
kubectl get nodes -o jsonpath='{.items[*].status.allocatable}'
kubectl get componentstatuses
```

### **🏗️ Workloads Management**

```bash
# Pods - Basic operations
kubectl get pods -A --show-labels
kubectl describe pod <pod-name>
kubectl logs <pod-name> -f
kubectl exec -it <pod-name> -- /bin/bash
kubectl delete pod <pod-name> --force

# Deployments
kubectl get deployments -A
kubectl rollout status deployment/<deployment-name>
kubectl rollout history deployment/<deployment-name>
kubectl scale deployment <deployment-name> --replicas=3
kubectl set image deployment/<deployment-name> app=<new-image>

# Services
kubectl get svc -A
kubectl describe svc <service-name>
kubectl get endpoints <service-name>

# ConfigMaps & Secrets
kubectl get configmaps -A
kubectl describe configmap <configmap-name>
kubectl get secrets -A
kubectl describe secret <secret-name>
```

### **🔍 Troubleshooting Commands**

```bash
# Check pod issues
kubectl get pods --field-selector=status.phase!=Running
kubectl describe pod <pod-name>
kubectl logs <pod-name> --previous
kubectl events --sort-by=.metadata.creationTimestamp

# Check service connectivity
kubectl run test-pod --image=busybox --rm -it -- wget -qO- <service-name>.<namespace>
kubectl port-forward svc/<service-name> 8080:80

# Check network
kubectl get networkpolicies -A
kubectl get ingress -A
kubectl describe ingress <ingress-name>
```

***

## 📋 **Common YAML Templates**

### **🐳 Basic Pod**

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: basic-pod
  labels:
    app: webapp
spec:
  containers:
  - name: nginx
    image: nginx:1.21
    ports:
    - containerPort: 80
    resources:
      requests:
        memory: "64Mi"
        cpu: "250m"
      limits:
        memory: "128Mi"
        cpu: "500m"
```

### **🚀 Deployment**

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: webapp-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: webapp
  template:
    metadata:
      labels:
        app: webapp
    spec:
      containers:
      - name: webapp
        image: nginx:1.21
        ports:
        - containerPort: 80
        livenessProbe:
          httpGet:
            path: /
            port: 80
          initialDelaySeconds: 30
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /
            port: 80
          initialDelaySeconds: 5
          periodSeconds: 5
```

### **🌐 Service**

```yaml
apiVersion: v1
kind: Service
metadata:
  name: webapp-service
spec:
  selector:
    app: webapp
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80
  type: ClusterIP
```

### **🔧 ConfigMap**

```yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  database_url: "postgresql://localhost:5432/mydb"
  cache_size: "100"
  log_level: "info"
  config.json: |
    {
      "environment": "production",
      "debug": false,
      "timeout": 30
    }
```

### **🔐 Secret**

```yaml
apiVersion: v1
kind: Secret
metadata:
  name: app-secrets
type: Opaque
data:
  username: YWRtaW4=  # base64 encoded "admin"
  password: MWYyZDFlMmU2N2Rm  # base64 encoded password
  api-key: bXlfc2VjcmV0X2FwaV9rZXk=
```

### **📦 PersistentVolumeClaim**

```yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: app-storage
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi
  storageClassName: fast-ssd
```

***

## 🔧 **Namespace Operations**

```bash
# Create namespace
kubectl create namespace production

# Switch namespace
kubectl config set-context --current --namespace=production

# List resources in namespace
kubectl get all -n production

# Delete namespace
kubectl delete namespace production
```

### **Namespace with Resource Limits**

```yaml
apiVersion: v1
kind: Namespace
metadata:
  name: production
spec:
  finalizers:
  - kubernetes
---
apiVersion: v1
kind: LimitRange
metadata:
  name: production-limits
  namespace: production
spec:
  limits:
  - default:
      cpu: "500m"
      memory: "512Mi"
    defaultRequest:
      cpu: "100m"
      memory: "256Mi"
    type: Container
```

***

## 🎯 **Label & Selector Operations**

```bash
# Add labels
kubectl label pods <pod-name> environment=production
kubectl label nodes <node-name> storage=ssd

# Filter by labels
kubectl get pods -l environment=production
kubectl get pods -l 'app in (webapp, api)'
kubectl get pods -l 'version notin (v1, v2)'

# Remove labels
kubectl label pods <pod-name> environment-
```

### **Node Selector & Affinity**

```yaml
# Node Selector
apiVersion: v1
kind: Pod
spec:
  nodeSelector:
    disktype: ssd
    environment: production
---
# Node Affinity
apiVersion: v1
kind: Pod
spec:
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
        - matchExpressions:
          - key: kubernetes.io/hostname
            operator: In
            values:
            - node-1
            - node-2
      preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 100
        preference:
          matchExpressions:
          - key: disktype
            operator: In
            values:
            - ssd
```

***

## 🔄 **Rolling Update & Rollback**

```bash
# Rolling update strategy
kubectl patch deployment <deployment-name> -p '{"spec":{"strategy":{"rollingUpdate":{"maxSurge":"25%","maxUnavailable":"25%"},"type":"RollingUpdate"}}}'

# Update with rolling restart
kubectl rollout restart deployment/<deployment-name>

# Check rollout status
kubectl rollout status deployment/<deployment-name>
kubectl rollout history deployment/<deployment-name>

# Rollback to previous version
kubectl rollout undo deployment/<deployment-name>
kubectl rollout undo deployment/<deployment-name> --to-revision=2

# Pause and resume rollout
kubectl rollout pause deployment/<deployment-name>
kubectl rollout resume deployment/<deployment-name>
```

### **Rolling Update Configuration**

```yaml
apiVersion: apps/v1
kind: Deployment
spec:
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 25%        # Can create 25% more pods
      maxUnavailable: 25%   # Can take down 25% of pods
```

***

## 📊 **Resource Management**

### **Resource Requests & Limits**

```yaml
apiVersion: v1
kind: Pod
spec:
  containers:
  - name: app
    image: myapp:1.0
    resources:
      requests:
        memory: "256Mi"
        cpu: "250m"
      limits:
        memory: "512Mi"
        cpu: "500m"
```

### **Resource Quota**

```yaml
apiVersion: v1
kind: ResourceQuota
metadata:
  name: production-quota
  namespace: production
spec:
  hard:
    requests.cpu: "4"
    requests.memory: 8Gi
    limits.cpu: "6"
    limits.memory: 12Gi
    persistentvolumeclaims: "3"
    pods: "10"
    services: "5"
```

### **Limit Range**

```yaml
apiVersion: v1
kind: LimitRange
metadata:
  name: production-limits
  namespace: production
spec:
  limits:
  - default:       # Default limit
      cpu: "500m"
      memory: "512Mi"
    defaultRequest: # Default request
      cpu: "100m"
      memory: "256Mi"
    type: Container
  - max:
      cpu: "2"
      memory: "4Gi"
    min:
      cpu: "50m"
      memory: "128Mi"
    type: Container
```

***

## 🏥 **Health Checks**

### **Liveness & Readiness Probes**

```yaml
apiVersion: v1
kind: Pod
spec:
  containers:
  - name: app
    image: myapp:1.0
    livenessProbe:
      httpGet:
        path: /health
        port: 8080
      initialDelaySeconds: 30
      periodSeconds: 10
      timeoutSeconds: 5
      failureThreshold: 3
    readinessProbe:
      httpGet:
        path: /ready
        port: 8080
      initialDelaySeconds: 5
      periodSeconds: 5
      timeoutSeconds: 3
      failureThreshold: 3
    startupProbe:
      httpGet:
        path: /startup
        port: 8080
      initialDelaySeconds: 10
      periodSeconds: 10
      timeoutSeconds: 5
      failureThreshold: 30
```

### **Probe Types**

```yaml
# HTTP Probe
livenessProbe:
  httpGet:
    path: /health
    port: 8080
    scheme: HTTP
    httpHeaders:
    - name: Custom-Header
      value: Awesome

# TCP Probe
livenessProbe:
  tcpSocket:
    port: 3306
  initialDelaySeconds: 15

# Exec Probe
livenessProbe:
  exec:
    command:
    - cat
    - /tmp/healthy
  initialDelaySeconds: 5
```

***

## 🔐 **Security Quick Tips**

### **Pod Security Context**

```yaml
apiVersion: v1
kind: Pod
spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 1000
    runAsGroup: 3000
    fsGroup: 2000
  containers:
  - name: app
    image: myapp:1.0
    securityContext:
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true
      capabilities:
        drop:
        - ALL
        add:
        - NET_BIND_SERVICE
```

### **Service Account**

```yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: app-service-account
---
apiVersion: v1
kind: Pod
spec:
  serviceAccountName: app-service-account
  containers:
  - name: app
    image: myapp:1.0
```

***

## 🌐 **Network Essentials**

### **Ingress Basic**

```yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: app-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
  - host: app.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: app-service
            port:
              number: 80
```

### **Network Policy**

```yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: app-network-policy
spec:
  podSelector:
    matchLabels:
      app: webapp
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: frontend
    ports:
    - protocol: TCP
      port: 80
  egress:
  - to:
    - podSelector:
        matchLabels:
          app: database
    ports:
    - protocol: TCP
      port: 5432
```

***

## 📊 **Monitoring Commands**

```bash
# Top commands
kubectl top nodes
kubectl top pods -A
kubectl top pods -l app=webapp

# Metrics server check
kubectl get apiservices | grep metrics
kubectl describe apiservice v1beta1.metrics.k8s.io

# Events
kubectl get events --sort-by=.metadata.creationTimestamp
kubectl get events -n <namespace> --field-selector type=Warning
```

***

## 🚨 **Emergency Commands**

```bash
# Force delete pod stuck in terminating state
kubectl delete pod <pod-name> --force --grace-period=0

# Drain node for maintenance
kubectl drain <node-name> --ignore-daemonsets --delete-local-data

# Uncordon node (make it schedulable again)
kubectl uncordon <node-name>

# Evict pod (recommended over drain)
kubectl cordon <node-name>
kubectl evict pod <pod-name> --namespace=<namespace>

# Restart all pods in deployment
kubectl rollout restart deployment/<deployment-name>

# Get pod logs with timestamps
kubectl logs <pod-name> --timestamps=true

# Copy files from pod
kubectl cp <pod-name>:/path/to/file ./local-file

# Port forwarding for debugging
kubectl port-forward pod/<pod-name> 8080:80
kubectl port-forward svc/<service-name> 8080:80

# Execute command in all pods
kubectl get pods -l app=webapp -o name | xargs -I {} kubectl exec {} -- <command>
```

***

## 🔍 **Debugging Tips**

```bash
# Check pod events
kubectl describe pod <pod-name> | grep -A 10 "Events:"

# Check pod YAML
kubectl get pod <pod-name> -o yaml

# Check service endpoints
kubectl get endpoints <service-name>

# Test DNS resolution
kubectl run busybox --rm -it --image=busybox -- nslookup kubernetes.default

# Check network connectivity
kubectl run test-pod --image=nicolaka/netshoot --rm -it -- /bin/bash

# Check resource usage
kubectl exec <pod-name> -- top
kubectl exec <pod-name> -- df -h
kubectl exec <pod-name> -- free -h

# Check container logs
kubectl logs <pod-name> -c <container-name>

# Get pod IP
kubectl get pod <pod-name> -o jsonpath='{.status.podIP}'

# Check node conditions
kubectl describe node <node-name> | grep -A 5 "Conditions:"
```

***

## 📋 **Cheat Sheet Matrix**

| **Task**           | **Command**                                                   | **Use Case**                |
| ------------------ | ------------------------------------------------------------- | --------------------------- |
| **Cluster Info**   | `kubectl cluster-info`                                        | Check cluster connectivity  |
| **Node Status**    | `kubectl get nodes -o wide`                                   | List all nodes with details |
| **Pod Issues**     | `kubectl get pods --field-selector=status.phase!=Running`     | Find problematic pods       |
| **Rolling Update** | `kubectl rollout restart deployment/<name>`                   | Restart deployment          |
| **Scale Up**       | `kubectl scale deployment <name> --replicas=5`                | Increase replicas           |
| **Port Forward**   | `kubectl port-forward svc/<name> 8080:80`                     | Local access to service     |
| **Log Streaming**  | `kubectl logs <pod-name> -f`                                  | Watch logs in real-time     |
| **Resource Usage** | `kubectl top pods -A`                                         | Check resource consumption  |
| **Force Delete**   | `kubectl delete pod <name> --force`                           | Remove stuck pod            |
| **DNS Test**       | `kubectl run busybox --rm -it -- nslookup kubernetes.default` | Test DNS resolution         |

***

## 🎯 **Quick Templates for Common Tasks**

### **Multi-Container Pod**

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: multi-container-pod
spec:
  containers:
  - name: webapp
    image: nginx:1.21
    ports:
    - containerPort: 80
  - name: sidecar
    image: redis:6.2
    ports:
    - containerPort: 6379
```

### **Init Container**

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: init-container-pod
spec:
  initContainers:
  - name: init-db
    image: busybox
    command: ['sh', '-c', 'until nslookup db; do sleep 1; done']
  containers:
  - name: app
    image: myapp:1.0
```

### **Horizontal Pod Autoscaler**

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

***

## 🚀 **One-Liner Commands**

```bash
# Get all resources in namespace
kubectl api-resources --verbs=list --namespaced -o name | xargs -n 1 kubectl get --show-kind --ignore-not-found -n <namespace>

# Delete all resources in namespace
kubectl delete all --all -n <namespace>

# Restart all deployments in namespace
kubectl rollout restart deployment -n <namespace>

# Get pods sorted by restart count
kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'

# Find pods using specific image
kubectl get pods -A -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.containers[0].image}{"\n"}{end}' | grep <image-name>

# Get node memory usage
kubectl top nodes --no-headers | awk '{print $1"\t"$3}' | sort -k2 -hr

# Watch pod creation
kubectl get pods -w

# Get service IPs
kubectl get svc -A -o jsonpath='{range .items[*]}{.metadata.namespace}{"\t"}{.metadata.name}{"\t"}{.spec.clusterIP}{"\n"}{end}'
```

***

## 📖 **Useful Flags & Options**

```bash
# Wide output with more details
kubectl get pods -o wide

# JSON/YAML output
kubectl get pod <name> -o json
kubectl get pod <name> -o yaml

# Custom columns
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,NODE:.spec.nodeName

# Sort by field
kubectl get pods --sort-by=.metadata.creationTimestamp
kubectl get pods --sort-by=.spec.containers[0].resources.requests.cpu

# Show labels
kubectl get pods --show-labels

# Watch for changes
kubectl get pods -w

# Field selector
kubectl get pods --field-selector=status.phase=Running
kubectl get pods --field-selector=metadata.namespace!=kube-system

# All namespaces
kubectl get pods -A
kubectl get all -A
```

***

## 🎯 **This Quick Reference Covers**

* ✅ **Essential Commands** - Daily operations
* ✅ **YAML Templates** - Common configurations
* ✅ **Troubleshooting** - Debugging techniques
* ✅ **Resource Management** - Limits and quotas
* ✅ **Health Checks** - Probes and monitoring
* ✅ **Security Basics** - Context and accounts
* ✅ **Network Essentials** - Services and policies
* ✅ **Emergency Commands** - Critical situations
* ✅ **One-Liners** - Quick tasks
* ✅ **Cheat Sheet Matrix** - Quick lookup

***

\*📌 **Simpan quick reference ini untuk daily operations Kubernetes**
