๐Ÿš€ Kubernetes Essentials

by Konrad Mosoล„

๐Ÿ”ง Basic Commands

  • kubectl get, describe, exec, logs, apply, delete
  • Connecting to a pod for the first time
  • Using kubectl port-forward for debugging
  • Managing contexts and namespaces

๐Ÿง  Contexts & Namespaces

kubectl config get-contexts
kubectl config use-context <context>
kubectl get pods -n <namespace>
  • Crucial for multi-cluster and multi-team environments

๐Ÿงญ kubectl config & use-context

Manage kubeconfig files and switch between clusters.

kubectl config get-contexts
kubectl config use-context <context-name>
kubectl config current-context

Tips:

  • Useful for multi-cluster or dev/stage/prod setups
  • Combine with namespaces:
    kubectl config set-context --current --namespace=my-namespace
    

๐Ÿง  Config from environment variable

Use KUBECONFIG environment variable to load different config.

export KUBECONFIG=~/.kube/config-another
kubectl get pods

๐Ÿ” kubectl get

Used to list and inspect resources quickly.

kubectl get pods
kubectl get svc
kubectl get deployments

Common flags:

  • -n <namespace> โ€“ specify namespace
  • -o wide โ€“ show more info (IP, node, etc.)
  • -o yaml or -o json โ€“ full resource output

๐Ÿ“„ kubectl describe

Detailed info about a resource (events, specs, status).

kubectl describe pod <pod-name>
kubectl describe node <node-name>
kubectl describe pvc <pvc-name>

Tips:

  • Shows events that explain failures (like CrashLoopBackOff)
  • Useful for debugging scheduling issues

๐Ÿš€ kubectl apply

Create or update resources using declarative YAML.

kubectl apply -f deployment.yaml

Tips:

  • Keeps resource history intact (unlike replace)
  • Supports server-side apply (--server-side)
  • Combine with GitOps workflows

โš™๏ธ Client-Side Apply (kubectl apply)

  • Merge happens locally in kubectl
  • Reads live object from cluster, calculates a diff, sends patch
  • Uses last-applied-configuration annotation
  • Good for simple use-cases and quick workflows
  • Can cause conflicts if multiple actors modify the same resource

๐Ÿง  Server-Side Apply (kubectl apply --server-side)

  • Merge happens on the API server
  • Server tracks field ownership (managedFields)
  • Supports fine-grained conflict resolution
  • Better for GitOps and controllers
  • Requires Kubernetes v1.18+ for stability

๐Ÿ” Key Differences

Feature Client-Side Apply Server-Side Apply
Merge location Local (kubectl) API Server
Field ownership Not tracked Tracked (managedFields)
Conflict detection Basic Advanced
Annotation used last-applied-configuration None
Best for Manual ops GitOps, automation

๐Ÿ’ก When to Use What?

  • Use Client-Side for quick, manual changes
  • Use Server-Side for automation, GitOps, and shared control

โŒ kubectl delete

Remove a resource.

kubectl delete pod <name>
kubectl delete -f deployment.yaml

Tips:

  • You can delete by label:
    kubectl delete pod -l app=myapp
    
  • Use with caution โ€” deleting some resources may cascade (like Deployments โ†’ Pods)

๐ŸŒ kubectl port-forward

Expose a pod or service on your local machine.

kubectl port-forward pod/<pod-name> 8080:80

Use cases:

  • Debug web apps or APIs locally
  • Connect to internal tools (e.g., DBs, dashboards)

center

โœ๏ธ Understanding kubectl

kubectl get pods
kubectl describe pod <pod-name>
kubectl exec -it <pod-name> -- /bin/sh
kubectl logs <pod-name>
  • The foundation of working with Kubernetes

๐Ÿ“‚ kubectl get namespaces

Switching and using namespaces effectively:

kubectl get ns
kubectl get pods -n kube-system
  • Always specify namespace when debugging non-default apps
  • Use --all-namespaces to search globally

๐Ÿž Troubleshooting

๐Ÿงช Checking Pod Status

Use kubectl get pods to view pod states at a glance.

kubectl get pods -o wide       # shows node, IP, restarts
kubectl get pods -A            # shows all namespaces

๐Ÿงช Checking Pod Status

Key STATUS values:

  • Running: Pod is up and ready
  • Pending: Waiting to be scheduled
  • CrashLoopBackOff: Container keeps crashing
  • ImagePullBackOff: Can't pull image
  • Terminating: Being deleted

๐Ÿ“„ Describing a Pod in Detail

Use kubectl describe to get details of Pod:

kubectl describe pod <pod-name>

๐Ÿ“„ Describing a Pod in Detail

What youโ€™ll see:

  • Labels & annotations
  • Containers, images, and resource settings
  • Liveness & readiness probes
  • Events: scheduling, image pull, startup issues

๐Ÿ“„ Describing a Pod in Detail

Tip:

Use grep Events or search for the bottom section for helpful logs like:

Failed to pull image...

Back-off restarting failed container

๐Ÿ” Inspecting Cluster Events

Cluster-wide events show real-time Kubernetes problems:

kubectl get events --sort-by=.metadata.creationTimestamp

๐Ÿ” Inspecting Cluster Events

Why itโ€™s useful:

  • See things like:
    • Failed image pulls
    • OOMKills
    • Volume mounting issues
  • Shows exact timestamps and involved objects

๐Ÿ’ฅ Debugging Crashed Pods

If your pod is restarting or failing:

View logs from the previous container:

kubectl logs -p <pod-name>

-p (or --previous) shows logs from the last crashed attempt

๐Ÿ’ฅ Debugging Crashed Pods

Connect to a shell:

kubectl exec -it <pod-name> -- /bin/bash

โš ๏ธ /bin/bash might not be available! You may need to try /bin/sh in that case. If that's not available, try busybox. If that fails, things get more complicated...

  • Check env vars, files, app config
  • May not work if container keeps crashing before you can connect

๐Ÿงฑ Investigating Node Issues

See all cluster nodes:

kubectl get nodes

Inspect a specific node:

kubectl describe node <node-name>

๐Ÿงฑ Investigating Node Issues

What to look for:

  • Allocatable resources (CPU/memory)
  • Conditions (Ready, DiskPressure, PIDPressure)
  • Labels and taints
  • Events at the bottom (failed pods, resource pressure, etc.)

๐Ÿง  Pro Tip: Combine Tools

Use together:

  • kubectl get pods
  • kubectl describe pod
  • kubectl logs / kubectl exec
  • kubectl get events
  • kubectl describe node

This gives you a full view of:

  • Whatโ€™s failing
  • Why it failed
  • Where it failed (node)
  • How to fix it

๐Ÿงฐ Troubleshooting Pod

center

๐Ÿ“Œ Summary

  • kubectl get pods โžก๏ธ quick status
  • kubectl describe pod โžก๏ธ deep dive
  • kubectl logs -p โžก๏ธ debug restarts
  • kubectl exec โžก๏ธ hands-on inspection
  • kubectl get events โžก๏ธ context + root cause
  • kubectl describe node โžก๏ธ host-level issues

๐Ÿ–ฅ๏ธ kubectl exec

Execute a command in a running container (like SSH).

kubectl exec -it <pod-name> -- /bin/sh

Flags & Variants:

  • -c <container-name> for multi-container pods
  • Can also run single commands:
    kubectl exec <pod> -- ls /app
    

๐Ÿ“ฆ kubectl logs

Get logs from a container in a pod.

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

Helpful flags:

  • --previous or -p for logs from crashed container
  • --tail=100 to limit output
  • -f to follow logs (like tail -f)

๐Ÿ’ก Health Checks

๐Ÿ’ก Health Checks

  • Liveness Probe

    Checks if unrecoverable error happened. Will restart container if it fails.

  • Readiness Probe

    Checks if application can receive traffic.

  • Startup Probe

    Checks if application already started.
    Liveness and Readiness do not start until it succeeds.

๐Ÿ’ก Health Checks - HTTP Probe

  • Is executed in context of Pod.
livenessProbe:
  httpGet:
    path: /healthz
    port: 8080
    httpHeaders:
    - name: Custom-Header
      value: Awesome
  initialDelaySeconds: 3
  periodSeconds: 3

๐Ÿ’ก Health Checks - TCP Probe

  • Is executed in context of Node.
readinessProbe:
  tcpSocket:
    port: 8080
  initialDelaySeconds: 15
  periodSeconds: 10

๐Ÿ’ก Health Checks - Command Execution Probe

readinessProbe:
  exec:
    command:
    - cat
    - /tmp/healthy
  initialDelaySeconds: 5
  periodSeconds: 5

๐Ÿ’ก Health Checks - Option initialDelaySeconds

Number of seconds after the container has started before startup, liveness or readiness probes are initiated. If a startup probe is defined, liveness and readiness probe delays do not begin until the startup probe has succeeded. If the value of periodSeconds is greater than initialDelaySeconds then the initialDelaySeconds would be ignored. Defaults to 0 seconds. Minimum value is 0.

๐Ÿ’ก Health Checks - Option periodSeconds

How often (in seconds) to perform the probe. Default to 10 seconds. The minimum value is 1.

๐Ÿ’ก Health Checks - Option timeoutSeconds

Number of seconds after which the probe times out. Defaults to 1 second. Minimum value is 1.

๐Ÿ’ก Health Checks - Option successThreshold

Minimum consecutive successes for the probe to be considered successful after having failed. Defaults to 1. Must be 1 for liveness and startup Probes. Minimum value is 1.

๐Ÿ’ก Health Checks - Option failureThreshold

If a probe fails failureThreshold times in a row, Kubernetes considers the container unhealthy.

  • For startup or liveness probes: the container is restarted.
  • For readiness probes: the container keeps running, but the pod is marked as not ready, and Kubernetes stops sending traffic to it.

๐Ÿ’ก Health Checks - Option terminationGracePeriodSeconds

You can set a grace period for how long the kubelet waits before forcefully stopping a failed container.

By default, it uses the pod's terminationGracePeriodSeconds (30s if not set), and the minimum allowed is 1 second.

You can also set this at the probe level for more control.

๐Ÿšจ Understanding Kubernetes Errors

Error Meaning
CrashLoopBackOff App is crashing repeatedly
OOMKilled Out of memory
ImagePullBackOff Image can't be pulled
RunContainerError Container failed to start

๐Ÿšฆ Resource Requests/Limits

๐Ÿ’ฅ What is OOMKill?

  • Out Of Memory Kill

  • Happens when a container exceeds its memory limit
  • The kernel kills the process to protect the node
  • Pod status shows:
    State: Terminated
    Reason: OOMKilled
    

๐Ÿ’ฅ OOMKill - Common causes

  • Poorly set memory limits
  • Memory leaks or high load spikes

โš™๏ธ Requests vs. Limits

Field What it means Effect on scheduling
requests Guaranteed minimum for the pod Used by scheduler
limits Max allowed usage (enforced by kubelet) Enforced at runtime
  • CPU limits can throttle
  • Memory limits can OOMKill

โš™๏ธ Requests vs. Limits example

resources:
  requests:
    cpu: "250m"
    memory: "128Mi"
  limits:
    cpu: "1"
    memory: "512Mi"

โš–๏ธ Resource Requests vs. Scheduling

center

  • Scheduler only looks at requests, not limits
  • Overcommitting is allowed if requests fit

๐Ÿ› ๏ธ Setting and Changing Resource Limits

Option 1: YAML definition

resources:
  requests:
    memory: "128Mi"
  limits:
    memory: "256Mi"

Option 2: kubectl set resources

kubectl set resources deployment myapp \
  --limits=cpu=500m,memory=512Mi \
  --requests=cpu=250m,memory=256Mi

๐Ÿšฆ Best Practices for Resource Limits

  • Start with requests based on baseline usage
  • Set memory limits to prevent total crash
  • Set CPU limits only if you need to prevent resource hogging
  • Use monitoring tools (Prometheus, VPA) to adjust over time
  • Use memory requests = limits for predictable performance

๐Ÿงช Want to Simulate an OOM?

Try this pod to trigger OOMKilled:

apiVersion: v1
kind: Pod
metadata:
  name: oom-demo
spec:
  containers:
  - name: hog
    image: polinux/stress
    command: ["stress", "--vm", "1", "--vm-bytes", "512M", "--vm-hang", "1"]
    resources:
      limits:
        memory: "200Mi"
  • Check result with:
    kubectl describe pod oom-demo
    

๐Ÿ“ฆ Persistent Volume Claims

๐Ÿ“ฆ Persistent Volume Claims (PVCs)

  • What PVCs are and how they work
  • Check status:
    kubectl get pvc
    kubectl describe pvc <pvc-name>
    
  • Resize/edit PVCs (with StorageClass support)
  • Delete PVCs safely without breaking running pods
  • When and why PVCs are needed

๐Ÿ“ฆ What Are Persistent Volume Claims (PVCs)?

  • A PVC is a request for storage by a pod
  • It abstracts:
    • Storage size
    • Access mode (e.g., ReadWriteOnce, ReadOnlyMany)
    • Storage class (e.g., fast SSD vs. slow HDD)
  • Binds to a PersistentVolume (PV) in the cluster

๐Ÿ“ฆ Pod example with PVC

spec:
  containers:
  - image: nginx:latest
    volumeMounts:
    - name: data
      mountPath: /usr/share/nginx/html
  volumes:
  - name: data
    persistentVolumeClaim:
      claimName: my-pvc

๐Ÿ” PVC with StatefulSet lifecycle

center

๐Ÿ” Checking PVC Status

Use kubectl to inspect PVCs:

kubectl get pvc
kubectl describe pvc <pvc-name>

Key statuses:

  • Bound: Successfully linked to a PV
  • Pending: Waiting for a suitable PV
  • Lost: Underlying PV missing or deleted

๐Ÿ” Checking PVC Status

Tips:

  • Use kubectl get pv to cross-check binding
  • kubectl describe shows capacity, access mode, and events
  • kubectl get volumeattachments -A show all attachments (useful when debugging multi-attach errors)

โœ๏ธ Editing and Resizing PVCs

kubectl edit pvc <pvc-name>

Change:

resources:
  requests:
    storage: 5Gi

Or patch directly:

kubectl patch pvc <pvc-name> \
  -p '{"spec":{"resources":{"requests":{"storage":"5Gi"}}}}'

โš ๏ธ Deleting PVCs Safely

  • Always check if a pod is using the PVC:

    kubectl get pod -o yaml | grep -A 5 volumeMounts
    
  • Delete with:

    kubectl delete pvc <pvc-name>
    

โš ๏ธ Deleting PVCs Safely

PVC Deletion Impact

  • If reclaimPolicy is:
    • Delete: Volume gets removed
    • Retain: Volume stays in place (manual cleanup needed)

โ“ When and Why Are PVCs Needed?

  • Apps that need stateful storage:

    • Databases (PostgreSQL, MySQL, MongoDB)
    • Volume-based caches (Redis w/ persistence)
    • Logging (e.g. Elasticsearch)
  • Used by:

    • StatefulSets (most common)
    • Some Deployments with shared storage needs
    • Helm charts for apps with volume templates

โœ… Best Practices with PVCs

  • Choose StorageClass that fits workload (SSD vs HDD)
  • Set appropriate access mode (RWO, RWX, ROX)
  • Use PVC templates with StatefulSets:
volumeClaimTemplates:
- metadata:
    name: data
  spec:
    accessModes: [ReadWriteOnce]
    resources:
      requests:
        storage: 5Gi
  • Monitor PVC usage to avoid filling up volumes
  • Set resource quotas to prevent abuse

๐Ÿ™Œ Thanks!

Questions?

_note: These commands form the backbone of most Kubernetes operations. Great to demo live if possible.

_note: Great starting point when checking the state of any resource. Combine with `watch` for live updates. Show selecotr by node: --field-selector spec.nodeName=dhc-03

_note: Encouraged over imperative commands for production use.

_note: Super helpful for testing without exposing services externally.

_note: Logs, describe, and events usually reveal 80% of what you need.

_note: Use it to poke around inside a container: check logs, config, or run diagnostic commands.

_note: Mention `kubectl describe pod` and `kubectl get events` as sources of this info.

_note: Emphasize that pods don't request storage directly โ€” they use PVCs, which Kubernetes then matches to an appropriate PV.

_note: Useful to show the interaction between PVC, PV, and actual storage backend like Ceph, AWS EBS, etc.

_note: Resizing is often only allowed when volume is not mounted, or may require restarting the pod.