# Cheatsheets

> Complete collection of Kubernetes cheatsheets for daily operations, troubleshooting, and quick reference.

## 📋 Table of Contents

* [🔧 kubectl Cheatsheet](#kubectl-cheatsheet)
* [📝 YAML Templates](#yaml-templates)
* [🚨 Troubleshooting Cheatsheet](#troubleshooting-cheatsheet)
* [⚡ Common Commands Quick Reference](#common-commands-quick-reference)

***

## 🔧 kubectl Cheatsheet

### 🔍 **Basic Commands**

#### **Cluster Information**

```bash
kubectl cluster-info                    # Show cluster info
kubectl version                         # Show kubectl & cluster version
kubectl config view                      # Show kubeconfig
kubectl config current-context          # Show current context
kubectl config get-contexts             # List all contexts
kubectl config use-context <context>    # Switch context
```

#### **Namespace Operations**

```bash
kubectl get namespaces                  # List namespaces
kubectl create namespace <name>         # Create namespace
kubectl delete namespace <name>         # Delete namespace
kubectl get pods -n <namespace>         # Get pods in namespace
kubectl get all -n <namespace>          # Get all resources in namespace
```

#### **Resource Listing**

```bash
kubectl get all                          # List all resources
kubectl get pods                         # List pods
kubectl get services                     # List services
kubectl get deployments                  # List deployments
kubectl get nodes                        # List nodes
kubectl get events --sort-by=.metadata.creationTimestamp  # Recent events

# Wide output for more details
kubectl get pods -o wide                 # Show pod IPs and nodes
kubectl get nodes -o wide                # Show node details
kubectl get services -o wide             # Show service cluster IPs
```

### 📝 **Resource Management**

#### **Create Resources**

```bash
# Apply from file
kubectl apply -f manifest.yaml           # Apply manifest
kubectl apply -f ./directory/             # Apply all manifests in directory
kubectl apply -f https://example.com/manifest.yaml  # Apply from URL

# Quick create commands
kubectl create deployment <name> --image=<image>  # Quick deployment
kubectl run <pod-name> --image=<image>  # Run pod
kubectl expose deployment <name> --port=80 --target-port=8080  # Expose service
kubectl create service clusterip <name> --tcp=80:8080  # Create service
```

#### **Update Resources**

```bash
# Update deployment image
kubectl set image deployment/<name> <container>=<new-image>     # Update image
kubectl set env deployment/<name> <key>=<value>                # Set environment variable
kubectl edit deployment <name>          # Edit deployment in editor

# Scale resources
kubectl scale deployment <name> --replicas=3                     # Scale replicas
kubectl scale rs <replicaset-name> --replicas=5                   # Scale replica set

# Patch resources
kubectl patch deployment <name> -p '{"spec":{"replicas":3}}'     # Patch resource
kubectl patch pod <pod-name> -p '{"metadata":{"labels":{"env":"prod"}}}'  # Add label
```

#### **Delete Resources**

```bash
# Delete from file
kubectl delete -f manifest.yaml          # Delete from manifest
kubectl delete -f ./directory/            # Delete all in directory

# Delete by name
kubectl delete pod <pod-name>            # Delete pod
kubectl delete deployment <name>         # Delete deployment
kubectl delete service <name>            # Delete service
kubectl delete all --all                 # Delete everything in namespace
kubectl delete namespace <namespace>     # Delete namespace (and all resources)
```

### 🔍 **Resource Inspection**

#### **Describe Resources**

```bash
kubectl describe pod <pod-name>          # Pod details
kubectl describe service <svc-name>      # Service details
kubectl describe node <node-name>        # Node details
kubectl describe deployment <name>       # Deployment details
kubectl describe ingress <ingress-name>  # Ingress details
```

#### **Logs & Debug**

```bash
# Container logs
kubectl logs <pod-name>                  # Show logs
kubectl logs <pod-name> -f               # Follow logs
kubectl logs <pod-name> --previous       # Previous container logs
kubectl logs deployment/<name>           # Deployment logs
kubectl logs <pod-name> -c <container>  # Specific container logs

# Tail multiple pods
kubectl logs -f -l app=<label>           # Follow logs for all pods with label
```

#### **Exec & Port Forward**

```bash
# Interactive shell
kubectl exec -it <pod-name> -- bash      # Interactive shell
kubectl exec -it <pod-name> -- sh       # Interactive shell (alpine)
kubectl exec <pod-name> -- ls /app       # Run command

# Port forwarding
kubectl port-forward <pod-name> 8080:80  # Port forward to pod
kubectl port-forward service/<svc-name> 8080:80  # Port forward to service
kubectl port-forward <pod-name> 3000-3010:3000-3010  # Port range
```

### 📊 **Resource Status**

#### **Resource Usage**

```bash
# Resource monitoring
kubectl top nodes                        # Node resource usage
kubectl top pods                         # Pod resource usage
kubectl top pods --containers            # Container resource usage
kubectl top pods -n <namespace>          # Pods in namespace
```

#### **Rollout Status**

```bash
kubectl rollout status deployment/<name> # Check rollout status
kubectl rollout history deployment/<name> # Show rollout history
kubectl rollout undo deployment/<name>   # Undo last rollout
kubectl rollout restart deployment/<name> # Restart deployment
kubectl rollout pause deployment/<name>  # Pause rollout
kubectl rollout resume deployment/<name> # Resume rollout
```

### 🔧 **Advanced Operations**

#### **Label & Annotation**

```bash
# Labels
kubectl label pods <pod-name> env=prod   # Add label
kubectl label pods <pod-name> env-        # Remove label
kubectl label pods <pod-name> env=dev --overwrite  # Overwrite label
kubectl get pods --show-labels           # Show labels
kubectl get pods -l env=prod             # Filter by label

# Annotations
kubectl annotate pods <pod-name> description="Production pod"  # Add annotation
kubectl annotate deployment <name> key=value  # Add annotation
```

#### **Copy & CP**

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

#### **Node Operations**

```bash
# Drain & Cordon
kubectl drain <node-name>                 # Drain node (remove pods)
kubectl drain <node-name> --ignore-daemonsets     # Drain ignoring daemonsets
kubectl drain <node-name> --delete-local-data     # Drain with local data deletion
kubectl uncordon <node-name>              # Uncordon node
kubectl cordon <node-name>                # Cordon node (unschedulable)

# Taint & Tolerate
kubectl taint nodes <node-name> key=value:NoSchedule  # Add taint
kubectl taint nodes <node-name> key-                     # Remove taint
kubectl taint nodes <node-name> key=value:NoExecute     # Add NoExecute taint
```

### 🎯 **Output Formats**

#### **JSON & YAML**

```bash
kubectl get pod <pod-name> -o json       # JSON format
kubectl get pod <pod-name> -o yaml       # YAML format
kubectl get pod <pod-name> -o jsonpath='{.spec.containers[*].name}'  # JSONPath
kubectl get pods -o jsonpath='{.items[*].metadata.name}'  # All pod names
```

#### **Custom Columns**

```bash
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,IP:.status.podIP
kubectl get nodes -o custom-columns=NAME:.metadata.name,CPU:.status.capacity.cpu,MEMORY:.status.capacity.memory
kubectl get services -o custom-columns=NAME:.metadata.name,TYPE:.spec.type,CLUSTER-IP:.spec.clusterIP
```

#### **Template Output**

```bash
kubectl get pods -o go-template='{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'
kubectl get pods -o go-template --template='{{range .items}}{{.metadata.name}}: {{.status.phase}}{{"\n"}}{{end}}'
```

***

## 📝 YAML Templates

### 📦 **Pod Templates**

#### **Basic Pod**

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: my-pod
  labels:
    app: my-app
    version: v1.0.0
spec:
  containers:
  - name: app
    image: nginx:1.21
    ports:
    - containerPort: 80
      name: http
    resources:
      requests:
        cpu: 100m
        memory: 128Mi
      limits:
        cpu: 500m
        memory: 512Mi
    livenessProbe:
      httpGet:
        path: /
        port: 80
      initialDelaySeconds: 30
      periodSeconds: 10
    readinessProbe:
      httpGet:
        path: /
        port: 80
      initialDelaySeconds: 5
      periodSeconds: 5
  restartPolicy: Always
```

#### **Multi-Container Pod**

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: multi-container
  labels:
    app: multi-app
spec:
  containers:
  - name: web
    image: nginx:1.21
    ports:
    - containerPort: 80
    volumeMounts:
    - name: shared-data
      mountPath: /usr/share/nginx/html
    resources:
      requests:
        cpu: 100m
        memory: 64Mi
      limits:
        cpu: 200m
        memory: 128Mi

  - name: content-generator
    image: busybox:1.35
    command: ["/bin/sh"]
    args:
      - -c
      - >
        while true; do
          echo "Time: $(date)" > /shared/index.html;
          echo "Pod: $(hostname)" >> /shared/index.html;
          sleep 30;
        done
    volumeMounts:
    - name: shared-data
      mountPath: /shared
    resources:
      requests:
        cpu: 50m
        memory: 32Mi
      limits:
        cpu: 100m
        memory: 64Mi

  volumes:
  - name: shared-data
    emptyDir: {}
  restartPolicy: Always
```

#### **Pod with Environment Variables**

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: app-with-env
spec:
  containers:
  - name: app
    image: myapp:latest
    env:
    - name: DATABASE_URL
      value: "postgresql://localhost:5432/mydb"
    - name: LOG_LEVEL
      value: "INFO"
    - name: PORT
      value: "8080"
    - name: API_KEY
      valueFrom:
        secretKeyRef:
          name: app-secrets
          key: api-key
    - name: CONFIG_FILE
      valueFrom:
        configMapKeyRef:
          name: app-config
          key: config.yaml
    resources:
      requests:
        cpu: 200m
        memory: 256Mi
      limits:
        cpu: 500m
        memory: 512Mi
```

### 🚀 **Deployment Templates**

#### **Basic Deployment**

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web-app
  labels:
    app: web-app
    version: v1.0.0
spec:
  replicas: 3
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 1
  selector:
    matchLabels:
      app: web-app
  template:
    metadata:
      labels:
        app: web-app
        version: v1.0.0
    spec:
      containers:
      - name: web
        image: nginx:1.21
        ports:
        - containerPort: 80
          name: http
        livenessProbe:
          httpGet:
            path: /
            port: 80
          initialDelaySeconds: 30
          periodSeconds: 10
          timeoutSeconds: 5
          failureThreshold: 3
        readinessProbe:
          httpGet:
            path: /
            port: 80
          initialDelaySeconds: 5
          periodSeconds: 5
          timeoutSeconds: 3
          failureThreshold: 3
        resources:
          requests:
            cpu: 100m
            memory: 128Mi
          limits:
            cpu: 500m
            memory: 512Mi
      restartPolicy: Always
      terminationGracePeriodSeconds: 30
```

#### **Deployment with Environment Variables**

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: app-with-env
  labels:
    app: app-with-env
spec:
  replicas: 2
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
  selector:
    matchLabels:
      app: app-with-env
  template:
    metadata:
      labels:
        app: app-with-env
    spec:
      containers:
      - name: app
        image: myapp:latest
        env:
        - name: DATABASE_URL
          value: "postgresql://localhost:5432/mydb"
        - name: API_KEY
          valueFrom:
            secretKeyRef:
              name: app-secrets
              key: api-key
        - name: LOG_LEVEL
          valueFrom:
            configMapKeyRef:
              name: app-config
              key: log-level
        - name: APP_ENV
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: POD_IP
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        resources:
          requests:
            cpu: 200m
            memory: 256Mi
          limits:
            cpu: 500m
            memory: 512Mi
        ports:
        - containerPort: 8080
          name: http
```

#### **StatefulSet Template**

```yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: database-statefulset
spec:
  serviceName: "database"
  replicas: 3
  selector:
    matchLabels:
      app: database
  template:
    metadata:
      labels:
        app: database
    spec:
      containers:
      - name: database
        image: postgres:13
        env:
        - name: POSTGRES_DB
          value: "mydatabase"
        - name: POSTGRES_USER
          valueFrom:
            secretKeyRef:
              name: db-secret
              key: username
        - name: POSTGRES_PASSWORD
          valueFrom:
            secretKeyRef:
              name: db-secret
              key: password
        - name: PGDATA
          value: /var/lib/postgresql/data/pgdata
        ports:
        - containerPort: 5432
          name: postgres
        volumeMounts:
        - name: postgres-storage
          mountPath: /var/lib/postgresql/data
        resources:
          requests:
            cpu: 200m
            memory: 256Mi
          limits:
            cpu: 500m
            memory: 1Gi
  volumeClaimTemplates:
  - metadata:
      name: postgres-storage
    spec:
      accessModes: ["ReadWriteOnce"]
      storageClassName: "fast-ssd"
      resources:
        requests:
          storage: 10Gi
```

### 🌐 **Service Templates**

#### **ClusterIP Service**

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

#### **NodePort Service**

```yaml
apiVersion: v1
kind: Service
metadata:
  name: web-nodeport
  labels:
    app: web-app
spec:
  type: NodePort
  ports:
  - port: 80
    targetPort: 80
    nodePort: 30080
    protocol: TCP
    name: http
  selector:
    app: web-app
```

#### **LoadBalancer Service**

```yaml
apiVersion: v1
kind: Service
metadata:
  name: web-loadbalancer
  labels:
    app: web-app
  annotations:
    service.beta.kubernetes.io/aws-load-balancer-type: "nlb"
    service.beta.kubernetes.io/aws-load-balancer-backend-protocol: "tcp"
spec:
  type: LoadBalancer
  ports:
  - port: 80
    targetPort: 80
    protocol: TCP
    name: http
  selector:
    app: web-app
  externalTrafficPolicy: Local
```

#### **Headless Service**

```yaml
apiVersion: v1
kind: Service
metadata:
  name: database-headless
  labels:
    app: database
spec:
  type: ClusterIP
  clusterIP: None
  ports:
  - port: 5432
    targetPort: 5432
    protocol: TCP
    name: postgres
  selector:
    app: database
```

### ⚙️ **ConfigMap & Secret Templates**

#### **ConfigMap**

```yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
  labels:
    app: my-app
data:
  database_url: "postgresql://localhost:5432/mydb"
  debug_mode: "true"
  log_level: "INFO"
  app_port: "8080"
  config.yaml: |
    app:
      name: my-app
      version: 1.0.0
      environment: production
    database:
      host: localhost
      port: 5432
      name: mydb
      pool_size: 10
    logging:
      level: INFO
      format: json
      output: stdout
  nginx.conf: |
    server {
        listen 80;
        server_name localhost;

        location / {
            proxy_pass http://backend:8080;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }
```

#### **Secret**

```yaml
apiVersion: v1
kind: Secret
metadata:
  name: app-secrets
  labels:
    app: my-app
type: Opaque
data:
  database_password: c2VjcmV0cGFzc3dvcmQ=  # base64 encoded: "secretpassword"
  api_key: YXBpa2V5dmFsdWU=              # base64 encoded: "apikeyvalue"
  jwt_secret: bXlKd1RTZWNyZXRLZXk=        # base64 encoded: "myJWTSecretKey"
  tls_cert: LS0tLS1CRUdJTi...             # base64 encoded certificate
  tls_key: LS0tLS1CRUdJTi...              # base64 encoded private key
stringData:
  jwt_secret_plain: "my-jwt-secret-key"
  database_username: "dbuser"
  app_env: "production"
```

### 📁 **Volume Templates**

#### **PersistentVolume**

```yaml
apiVersion: v1
kind: PersistentVolume
metadata:
  name: app-pv
  labels:
    type: local
    app: my-app
spec:
  storageClassName: manual
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteOnce
  persistentVolumeReclaimPolicy: Retain
  hostPath:
    path: /mnt/data/app
  nodeAffinity:
    required:
      nodeSelectorTerms:
      - matchExpressions:
        - key: kubernetes.io/hostname
          operator: In
          values:
          - worker-node-1
```

#### **PersistentVolumeClaim**

```yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: app-pvc
  labels:
    app: my-app
spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: fast-ssd
  resources:
    requests:
      storage: 5Gi
  selector:
    matchLabels:
      type: local
```

#### **Pod with Volume**

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: app-with-volume
  labels:
    app: my-app
spec:
  containers:
  - name: app
    image: myapp:latest
    ports:
    - containerPort: 8080
    volumeMounts:
    - name: data-volume
      mountPath: /app/data
    - name: config-volume
      mountPath: /app/config
      readOnly: true
    - name: secret-volume
      mountPath: /app/secrets
      readOnly: true
    resources:
      requests:
        cpu: 200m
        memory: 256Mi
      limits:
        cpu: 500m
        memory: 512Mi
  volumes:
  - name: data-volume
    persistentVolumeClaim:
      claimName: app-pvc
  - name: config-volume
    configMap:
      name: app-config
  - name: secret-volume
    secret:
      secretName: app-secrets
```

***

## 🚨 Troubleshooting Cheatsheet

### **🚨 Common Issues & Solutions**

| Issue                    | Symptoms                       | Diagnosis Commands                                                                                                                                                                      | Solutions                                        |
| ------------------------ | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ |
| **Pod Pending**          | Pod stuck in Pending state     | <p><code>kubectl describe pod \<pod-name></code><br><code>kubectl get nodes</code><br><code>kubectl get pv,pvc</code></p>                                                               | Check resources, taints, PVCs, node selectors    |
| **Image Pull Error**     | ImagePullBackOff, ErrImagePull | <p><code>kubectl describe pod \<pod-name></code><br><code>docker pull \<image></code><br><code>kubectl get secret \<secret-name></code></p>                                             | Check image name, registry, credentials, network |
| **CrashLoopBackOff**     | Restarting repeatedly          | <p><code>kubectl logs \<pod-name></code><br><code>kubectl logs \<pod-name> --previous</code><br><code>kubectl describe pod \<pod-name></code></p>                                       | Fix app issues, resource limits, health checks   |
| **DNS Resolution**       | Can't resolve service names    | <p><code>kubectl exec -it \<pod> -- nslookup kubernetes.default</code><br><code>kubectl get pods -n kube-system</code><br><code>kubectl get configmap coredns -n kube-system</code></p> | Check CoreDNS, network policies, service DNS     |
| **Network Connectivity** | Can't reach services           | <p><code>kubectl exec -it \<pod> -- curl <http://service-name></code><br><code>kubectl get endpoints \<svc-name></code><br><code>kubectl get svc \<svc-name></code></p>                 | Check service, endpoints, network policies       |
| **Resource Exhaustion**  | OOMKilled, throttling          | <p><code>kubectl top nodes</code><br><code>kubectl top pods</code><br><code>kubectl describe pod \<pod-name></code></p>                                                                 | Adjust limits/requests, add nodes, optimize app  |
| **Volume Issues**        | VolumeMount/Attach errors      | <p><code>kubectl describe pod \<pod-name></code><br><code>kubectl get pv,pvc</code><br><code>kubectl get events</code></p>                                                              | Check PVC status, storage class, node affinity   |

### 🔍 **Debug Commands**

#### **Pod Issues**

```bash
# Basic pod debugging
kubectl describe pod <pod-name>                    # Detailed pod info
kubectl get pod <pod-name> -o yaml                # Full pod YAML
kubectl logs <pod-name>                           # Container logs
kubectl logs <pod-name> -f                        # Follow logs
kubectl logs <pod-name> --previous                # Previous container logs
kubectl logs <pod-name> -c <container>            # Specific container logs

# Interactive debugging
kubectl exec -it <pod-name> -- /bin/bash          # Interactive shell
kubectl exec -it <pod-name> -- /bin/sh           # Interactive shell (alpine)
kubectl exec <pod-name> -- ps aux                # Running processes
kubectl exec <pod-name> -- netstat -tulpn        # Network connections

# Pod status and events
kubectl get pods --field-selector=status.phase=Failed
kubectl get pods --field-selector=status.phase=Pending
kubectl get events --sort-by=.metadata.creationTimestamp | tail -20
kubectl get events -n <namespace> --field-selector type=Warning
```

#### **Node Issues**

```bash
# Node debugging
kubectl describe node <node-name>                 # Node details
kubectl get nodes -o wide                         # Node details with IP
kubectl top node <node-name>                      # Resource usage
kubectl get pods -o wide --field-selector spec.nodeName=<node>  # Pods on node

# Node conditions
kubectl get nodes -o jsonpath='{.items[*].status.conditions[*]}'
kubectl describe node <node-name> | grep -A 10 "Conditions:"
kubectl cordon <node-name>                        # Mark as unschedulable
kubectl uncordon <node-name>                      # Mark as schedulable
```

#### **Service Issues**

```bash
# Service debugging
kubectl describe service <svc-name>               # Service details
kubectl get endpoints <svc-name>                  # Service endpoints
kubectl get service <svc-name> -o yaml           # Full service YAML
kubectl get svc --show-labels                     # Services with labels

# Service connectivity
kubectl exec -it <pod> -- nslookup <svc-name>.<namespace>.svc.cluster.local
kubectl exec -it <pod> -- curl -I http://<svc-name>.<namespace>.svc.cluster.local
kubectl exec -it <pod> -- telnet <svc-name> 80
kubectl port-forward service/<svc-name> 8080:80   # Port forward test
```

#### **Network Issues**

```bash
# Network debugging
kubectl get networkpolicies -n <namespace>        # Network policies
kubectl get pods -o wide                          # Pod IPs
kubectl get services -o wide                      # Service cluster IPs
kubectl get endpoints                             # Service endpoints

# DNS testing
kubectl exec -it <pod> -- nslookup kubernetes.default
kubectl exec -it <pod> -- nslookup google.com
kubectl exec -it <pod> -- cat /etc/resolv.conf

# Network connectivity
kubectl exec -it <pod> -- ping 8.8.8.8
kubectl exec -it <pod> -- curl -I https://kubernetes.io
kubectl exec -it <pod> -- netstat -i
kubectl exec -it <pod> -- ss -tuln
```

#### **Storage Issues**

```bash
# Storage debugging
kubectl get pv,pvc                               # Persistent volumes and claims
kubectl describe pv <pv-name>                    # PV details
kubectl describe pvc <pvc-name>                  # PVC details
kubectl get storageclass                         # Storage classes

# Volume mount issues
kubectl describe pod <pod-name> | grep -A 10 "Volumes:"
kubectl exec -it <pod> -- df -h                  # Mounted filesystems
kubectl exec -it <pod> -- ls -la /mount/path     # Check mount point
```

### 🛠️ **Quick Fixes**

#### **Restart Pod**

```bash
kubectl delete pod <pod-name>                     # Let deployment recreate
kubectl rollout restart deployment/<name>         # Restart deployment
kubectl rollout restart statefulset/<name>        # Restart statefulset
kubectl rollout restart daemonset/<name>          # Restart daemonset
```

#### **Scale Resources**

```bash
kubectl scale deployment <name> --replicas=0      # Stop deployment
kubectl scale deployment <name> --replicas=3      # Start with new pods
kubectl scale statefulset <name> --replicas=2     # Scale statefulset
kubectl scale daemonset <name> --replicas=3       # Scale daemonset
```

#### **Clear Issues**

```bash
kubectl delete pod <pod-name> --force             # Force delete stuck pod
kubectl delete pod <pod-name> --force --grace-period=0  # Immediate force delete
kubectl drain <node-name> --ignore-daemonsets     # Drain node for maintenance
kubectl uncordon <node-name>                     # Make node schedulable again
```

#### **Resource Adjustments**

```bash
# Update resource limits
kubectl patch deployment <name> -p '{"spec":{"template":{"spec":{"containers":[{"name":"app","resources":{"limits":{"memory":"1Gi"}}}]}}}}'

# Update environment variables
kubectl set env deployment/<name> NEW_VAR=new_value

# Update image
kubectl set image deployment/<name> app=<new-image>
```

#### **Emergency Debug Pod**

```bash
# Create debug pod with networking tools
kubectl run debug-pod --image=nicolaka/netshoot -it --rm -- /bin/bash

# Create debug pod with same node/pod affinity
kubectl run debug-pod --image=busybox --rm -it --restart=Never --overrides='{"spec":{"nodeSelector":{"kubernetes.io/hostname":"<node-name>"}}}' -- /bin/sh
```

#### **Cluster Issues**

```bash
# Check cluster health
kubectl get componentstatuses
kubectl get cs
kubectl get endpoints --namespace=kube-system

# Check system pods
kubectl get pods -n kube-system
kubectl logs -n kube-system -l k8s-app=kube-dns
kubectl logs -n kube-system -l component=etcd

# Check API server connectivity
kubectl get namespaces
kubectl cluster-info dump
```

***

## ⚡ Common Commands Quick Reference

### 📋 **One-Liners**

#### **Pod Management**

```bash
kubectl get pods --all-namespaces                           # All pods in all namespaces
kubectl get pods -o wide                                    # Pods with node info
kubectl get pods -l app=nginx                               # Pods with specific label
kubectl get pods --field-selector=status.phase=Running     # Running pods only
kubectl delete pod <pod-name> --force --grace-period=0     # Force delete stuck pod
kubectl get pods --show-labels                              # Pods with labels
```

#### **Resource Overview**

```bash
kubectl get all -n <namespace>                              # All resources in namespace
kubectl get all                                              # All resources in default namespace
kubectl get events --sort-by=.metadata.creationTimestamp  # Recent events sorted by time
kubectl top nodes                                           # Node resource usage
kubectl top pods --all-namespaces                          # Pod resource usage all namespaces
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,IP:.status.podIP
```

#### **Services & Networking**

```bash
kubectl get services -o wide                               # Services with cluster IPs
kubectl get ingress --all-namespaces                       # All ingress resources
kubectl get endpoints                                       # All service endpoints
kubectl get networkpolicies --all-namespaces              # All network policies
kubectl port-forward service/<svc-name> 8080:80           # Port forward to service
```

#### **Deployment Management**

```bash
kubectl rollout status deployment/<name>                   # Check rollout status
kubectl rollout history deployment/<name>                  # Show rollout history
kubectl rollout undo deployment/<name>                    # Undo last rollout
kubectl rollout restart deployment --all                  # Restart all deployments
kubectl get deployments -o wide                           # Deployments with details
```

#### **Logs & Debugging**

```bash
kubectl logs deployment/<name> -f                         # Follow deployment logs
kubectl logs -f -l app=<label>                            # Follow logs for all pods with label
kubectl get events -n <namespace> --sort-by=.lastTimestamp | tail -10  # Recent 10 events
kubectl describe pod <pod-name> | grep -A 10 "Events:"    # Show pod events
kubectl get pods -o jsonpath='{.items[*].spec.containers[*].image}'  # All container images
```

### 🎯 **Common Patterns**

#### **Application Deployment**

```bash
# Create deployment from image
kubectl create deployment <name> --image=<image> --replicas=3

# Expose deployment as service
kubectl expose deployment <name> --port=80 --target-port=8080 --type=LoadBalancer

# Update deployment image
kubectl set image deployment/<name> <container>=<new-image>

# Scale deployment
kubectl scale deployment <name> --replicas=5

# Check deployment status
kubectl rollout status deployment/<name>
```

#### **Multi-Container Debugging**

```bash
# Get logs for specific container
kubectl logs <pod-name> -c <container-name>

# Exec into specific container
kubectl exec -it <pod-name> -c <container-name> -- bash

# Port forward specific container
kubectl port-forward <pod-name> 8080:8080 -c <container-name>
```

#### **Configuration Management**

```bash
# Create configmap from file
kubectl create configmap <name> --from-file=config.yaml

# Create secret from literal
kubectl create secret generic <name> --from-literal=key=value

# Create secret from file
kubectl create secret generic <name> --from-file=cert.pem

# Get configmap as YAML
kubectl get configmap <name> -o yaml
```

#### **Volume Management**

```bash
# Get persistent volumes and claims
kubectl get pv,pvc

# Describe storage class
kubectl describe storageclass <storage-class-name>

# Check volume mount issues
kubectl describe pod <pod-name> | grep -A 20 "Mounts:"
```

#### **Namespace Operations**

```bash
# Create namespace
kubectl create namespace <namespace-name>

# Switch namespace context
kubectl config set-context --current --namespace=<namespace-name>

# Get resources in specific namespace
kubectl get all -n <namespace-name>

# Delete namespace and all resources
kubectl delete namespace <namespace-name>
```

### ⚡ **Emergency Commands**

#### **Cluster Recovery**

```bash
# Delete all pods in namespace
kubectl delete pods --all -n <namespace>

# Restart namespace (delete all resources)
kubectl delete all --all -n <namespace>

# Force delete namespace stuck in terminating
kubectl patch namespace <namespace> -p '{"metadata":{"finalizers":null}}'

# Restart all system pods
kubectl delete pods -n kube-system --all
```

#### **Node Maintenance**

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

# Uncordon node after maintenance
kubectl uncordon <node-name>

# Mark node unschedulable
kubectl cordon <node-name>

# Get node details
kubectl describe node <node-name>
```

#### **Resource Cleanup**

```bash
# Delete failed pods
kubectl delete pods --field-selector=status.phase=Failed

# Delete evicted pods
kubectl delete pods --field-selector=status.phase=Evicted

# Delete completed jobs
kubectl delete jobs --field-selector=status.successful=1

# Clean up old replica sets
kubectl delete replicaset --all
```

#### **Health Checks**

```bash
# Check cluster health
kubectl get componentstatuses
kubectl get cs

# Check system components
kubectl get pods -n kube-system
kubectl get events -n kube-system --sort-by=.lastTimestamp

# Check API server
kubectl get --raw /healthz
kubectl get --raw /readyz

# Check certificates
kubectl get certificates -n cert-manager
kubectl describe certificate <cert-name> -n cert-manager
```

#### **Performance Debugging**

```bash
# Get resource usage
kubectl top nodes
kubectl top pods --containers

# Check resource quotas
kubectl describe namespace <namespace-name>

# Check limit ranges
kubectl describe limitrange -n <namespace-name>

# Get node capacity
kubectl describe nodes | grep -A 10 "Allocated resources:"
```

### 🔍 **Advanced Queries**

#### **JSONPath Queries**

```bash
# Get all pod names
kubectl get pods -o jsonpath='{.items[*].metadata.name}'

# Get pods with restarts
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.containerStatuses[0].restartCount}{"\n"}{end}' | awk '$2 > 0'

# Get pod IPs
kubectl get pods -o jsonpath='{.items[*].status.podIP}'

# Get service cluster IPs
kubectl get svc -o jsonpath='{.items[*].spec.clusterIP}'

# Get node names
kubectl get nodes -o jsonpath='{.items[*].metadata.name}'
```

#### **Custom Output Formats**

```bash
# Pods with resource usage
kubectl get pods -o custom-columns=NAME:.metadata.name,CPU:.spec.containers[*].resources.requests.cpu,MEMORY:.spec.containers[*].resources.requests.memory

# Nodes with capacity info
kubectl get nodes -o custom-columns=NAME:.metadata.name,CPU:.status.capacity.cpu,MEMORY:.status.capacity.memory,PODS:.status.capacity.pods

# Services with type and cluster IP
kubectl get svc -o custom-columns=NAME:.metadata.name,TYPE:.spec.type,CLUSTER-IP:.spec.clusterIP,EXTERNAL-IP:.spec.loadBalancerIP
```

#### **Filtering and Selection**

```bash
# Get resources by label
kubectl get pods -l app=nginx
kubectl get services -l tier=frontend
kubectl get deployments -l environment=production

# Get resources by field selector
kubectl get pods --field-selector=status.phase=Running
kubectl get nodes --field-selector=node-role.kubernetes.io/master=true
kubectl get pods --field-selector=spec.restartPolicy=Always

# Combine filters
kubectl get pods -l app=nginx --field-selector=status.phase=Running
```

***

*📅 **Last Updated**: November 2024* *🔗 **Related**:* [*Kubernetes Fundamentals*](https://mahbubzulkarnain.gitbook.io/catatan-seekor-the-series/catatan-seekor-devops/kubernetes/fundamentals) *|* [*Application Deployment*](https://mahbubzulkarnain.gitbook.io/catatan-seekor-the-series/catatan-seekor-devops/kubernetes/application-deployment) *|* [*Troubleshooting*](https://mahbubzulkarnain.gitbook.io/catatan-seekor-the-series/catatan-seekor-devops/kubernetes/troubleshooting)
