Kubernetes

Cluster Info & Context

kubectl cluster-info                        # cluster endpoint info
kubectl get events                          # recent cluster events
kubectl get cs                              # control plane component status
kubectl config get-contexts                 # list all contexts
kubectl config current-context             # show active context
kubectl config use-context <context>       # switch context
kubectl config set-context --current --namespace=<ns>  # set default namespace for current context

Basics

kubectl get <resource>                     # list resources
kubectl describe <resource> <name>        # detailed info about a resource
kubectl logs <pod>                         # print logs from a pod
kubectl logs <pod> -c <container>         # logs from specific container in pod
kubectl logs <pod> --previous             # logs from previous (crashed) container
kubectl exec -it <pod> -- bash            # exec into container (bash)
kubectl exec -it <pod> -- sh              # exec into container (sh — use for alpine/busybox)
kubectl exec -it <pod> -c <container> -- bash  # exec into specific container
kubectl delete <resource> <name>          # delete a resource
kubectl apply -f <file.yaml>              # apply manifest
kubectl delete -f <file.yaml>             # delete resources defined in manifest

Namespaces

kubectl get ns                              # list all namespaces
kubectl create ns <namespace>              # create namespace
kubectl delete ns <namespace>              # delete namespace (deletes everything inside)
kubectl get all -n <namespace>             # list all resources in a namespace

Pods

kubectl get pods                           # list pods in default namespace
kubectl get pods -o wide                   # with IP and node info
kubectl get pods -n <namespace>           # pods in specific namespace
kubectl get pods -A                        # pods in all namespaces
kubectl get pods -l app=<label>           # filter pods by label
kubectl get pods -w                        # watch pods (live updates)

kubectl describe pod <pod>                # full pod details — useful for troubleshooting
kubectl delete pod <pod>                  # delete pod
kubectl delete pod <pod> --force --grace-period=0  # force delete stuck pod

kubectl label pods <pod> <key>=<value>    # add/update label on pod

kubectl run <name> --image=nginx --port=80  # run a simple pod
kubectl run <name> --image=nginx --dry-run=client -o yaml  # generate pod YAML without applying

kubectl top pods                           # pod CPU/memory usage (requires metrics-server)
kubectl top pods -n <namespace>

Nodes

kubectl get nodes                          # list all nodes
kubectl get nodes -o wide                  # with IPs, OS, kernel info
kubectl describe node <node>              # detailed node info
kubectl top nodes                          # node CPU/memory usage
kubectl cordon <node>                     # mark node as unschedulable
kubectl uncordon <node>                   # re-enable scheduling on node
kubectl drain <node> --ignore-daemonsets --delete-emptydir-data  # drain node for maintenance

Deployments & ReplicaSets

kubectl get deployments                    # list deployments
kubectl get rs                             # list replica sets
kubectl describe deployment <name>

kubectl apply -f deployment.yaml          # create/update deployment from manifest
kubectl edit deployment <name>            # edit deployment live in editor
kubectl delete deployment <name>

kubectl scale deployment <name> --replicas=4   # scale deployment
kubectl set image deployment/<name> <container>=<image>:<tag>  # rolling update image

kubectl rollout status deployment/<name>  # check rollout progress
kubectl rollout history deployment/<name> # view rollout history
kubectl rollout undo deployment/<name>    # roll back to previous version
kubectl rollout undo deployment/<name> --to-revision=2  # roll back to specific revision
kubectl rollout restart deployment/<name> # restart all pods (picks up new config/secrets)

Services

kubectl get svc                            # list services
kubectl get svc -n <namespace>
kubectl describe svc <name>

kubectl expose deployment/<name> --type=LoadBalancer --port=8080  # expose as LoadBalancer
kubectl expose deployment/<name> --type=ClusterIP --port=80       # expose internally only
kubectl expose deployment/<name> --type=NodePort --port=80

kubectl get endpoints                      # show pod IPs behind services
kubectl delete svc <name>

Ingress

kubectl get ingress                        # list ingress rules
kubectl get ingress -A                     # all namespaces
kubectl describe ingress <name>
kubectl apply -f ingress.yaml
kubectl delete ingress <name>

ConfigMaps & Secrets

kubectl get configmaps
kubectl describe configmap <name>
kubectl get configmap <name> -o yaml       # export to YAML

kubectl create configmap <name> --from-literal=key=value
kubectl create configmap <name> --from-file=config.properties

kubectl get secrets
kubectl describe secret <name>
kubectl get secret <name> -o yaml          # export (values are base64 encoded)

# Decode a secret value
kubectl get secret <name> -o jsonpath='{.data.<key>}' | base64 --decode

PersistentVolumes & PVCs

kubectl get pv                             # list persistent volumes (cluster-scoped)
kubectl get pvc                            # list persistent volume claims (namespace-scoped)
kubectl get pvc -n <namespace>
kubectl describe pvc <name>
kubectl delete pvc <name>

Contexts & Kubeconfig

kubectl config view                        # view kubeconfig
kubectl config get-contexts               # list all contexts
kubectl config current-context
kubectl config use-context <context>
kubectl config set-context --current --namespace=<ns>  # set default namespace

# Merge kubeconfigs
KUBECONFIG=~/.kube/config:~/new-cluster.yaml kubectl config view --flatten > ~/.kube/config

Output & Filtering

# Output formats
kubectl get pods -o wide
kubectl get pods -o yaml
kubectl get pods -o json
kubectl get pod <name> -o jsonpath='{.spec.nodeName}'       # extract specific field
kubectl get pods -o jsonpath='{.items[*].metadata.name}'    # extract all pod names
kubectl get pods --sort-by='.metadata.creationTimestamp'    # sort by creation time

# Labels & selectors
kubectl get pods -l app=nginx
kubectl get pods -l env=prod,tier=frontend

# Dry run — generate YAML without applying
kubectl create deployment nginx --image=nginx --dry-run=client -o yaml
kubectl run mypod --image=busybox --dry-run=client -o yaml

Port Forwarding & Local Access

kubectl port-forward pod/<pod> 8080:80                    # forward local 8080 → pod port 80
kubectl port-forward svc/<service> 8080:80                # forward to service
kubectl port-forward deployment/<name> 8080:80

kubectl proxy                                              # open proxy to cluster API (localhost:8001)

Copy Files To/From Pods

kubectl cp <pod>:/path/in/pod /local/path                  # copy from pod
kubectl cp /local/path <pod>:/path/in/pod                  # copy to pod
kubectl cp -c <container> <pod>:/path /local/path          # specify container

Troubleshooting

# Logs
kubectl logs <pod>
kubectl logs <pod> --previous                              # crashed container logs
kubectl logs <pod> -f                                      # follow (tail -f)
kubectl logs <pod> --tail=100                              # last 100 lines
kubectl logs -l app=nginx                                  # logs from all pods with label

# Events
kubectl get events --sort-by='.lastTimestamp'
kubectl get events -n <namespace>

# Debug pods
kubectl run debug-pod --rm -it --image=busybox --restart=Never -- sh
kubectl run debug-pod --rm -it --image=nicolaka/netshoot --restart=Never -- bash  # network debug

# Describe for OOMKilled / CrashLoopBackOff
kubectl describe pod <pod>                                 # check Events section at bottom

# Check resource usage
kubectl top pods
kubectl top nodes

# Check API server directly
kubectl proxy &
curl http://localhost:8001/api/v1/namespaces/default/pods

Quick Reference: Common Exit Codes / Pod States

StateMeaning
CrashLoopBackOffContainer keeps crashing — check kubectl logs and describe
OOMKilledOut of memory — increase memory limits
PendingCan’t schedule — check node resources, taints, PVC binding
ImagePullBackOffCan’t pull image — check image name, registry credentials
Terminating stuckUse --force --grace-period=0 to delete
ErrorContainer exited non-zero — check logs

Understanding YAML

Every manifest needs these top-level fields:

FieldDescription
apiVersionAPI group and version (e.g. apps/v1, v1)
kindResource type (Deployment, Pod, Service, etc.)
metadataName, namespace, labels, annotations
specDesired state of the resource

Example: Deployment

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  namespace: default
  labels:
    app: nginx
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80
        resources:
          requests:
            memory: "64Mi"
            cpu: "250m"
          limits:
            memory: "128Mi"
            cpu: "500m"

Example: Service (ClusterIP)

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

Example: ConfigMap

apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  APP_ENV: production
  LOG_LEVEL: info

Example: Namespace

apiVersion: v1
kind: Namespace
metadata:
  name: my-namespace