Monday, August 11, 2025

kube

Here’s a 50-point crisp checklist of Kubernetes production support best practices you can use in interviews — short, sharp, and easy to remember.


---

Kubernetes Production Support – 50 Best Practices

A. Cluster & Node Management

1. Keep Kubernetes version up to date with LTS and security patches.
2. Use multiple master nodes for HA (High Availability)
3. Label and taint nodes for workload segregation.
4. Use autoscaling for nodes (Cluster Autoscaler).


5. Reserve system resources on nodes using --system-reserved.


6. Regularly monitor node health via kubectl get nodes.


7. Spread workloads across zones/regions for resilience.


8. Avoid overcommitting node resources beyond safe limits.


9. Ensure OS and kernel are tuned for container workloads.


10. Apply OS-level security updates on nodes regularly.




---

B. Pod & Workload Management

11. Use resource requests and limits for all pods.


12. Configure PodDisruptionBudgets to avoid downtime during maintenance.


13. Use Readiness and Liveness probes for health checks.


14. Implement pod anti-affinity to avoid co-locating critical workloads.


15. Use init containers for dependency checks before main app starts.


16. Deploy workloads via Deployment, StatefulSet, or DaemonSet as per use case.


17. Keep images lightweight and scan for vulnerabilities.


18. Avoid running pods as root.


19. Use imagePullPolicy=IfNotPresent for stable deployments.


20. Tag images with version, not latest.




---

C. Networking & Service Management

21. Use ClusterIP for internal services, LoadBalancer/Ingress for external.


22. Secure Ingress with TLS (Let’s Encrypt or custom certs).


23. Use NetworkPolicies to control pod-to-pod communication.


24. Avoid exposing the API server publicly.


25. Keep DNS resolution stable via CoreDNS monitoring.


26. Use headless services for Stateful workloads.


27. Implement connection timeouts and retries in services.


28. Configure externalTrafficPolicy=Local for preserving client IP.


29. Limit public access to services via firewalls or security groups.


30. Load-test services before going live.




---

D. Observability & Troubleshooting

31. Integrate Prometheus & Grafana for metrics monitoring.


32. Centralize logs via ELK or Loki.


33. Enable Kubernetes audit logging for API server.


34. Set up alerts for pod restarts, CPU/memory saturation.


35. Use kubectl describe and kubectl logs for quick debugging.


36. Maintain runbooks for common incident scenarios.


37. Use kubectl top to identify resource bottlenecks.


38. Set up traceability with OpenTelemetry/Jaeger.


39. Store historical metrics for capacity planning.


40. Regularly test disaster recovery (DR) playbooks.




---

E. Security & Compliance

41. Enable Role-Based Access Control (RBAC).


42. Use namespaces for workload isolation.


43. Scan container images before deployment.


44. Use secrets in Kubernetes Secret objects, not plain env variables.


45. Rotate secrets and credentials periodically.


46. Enable API authentication and authorization.


47. Restrict kubectl exec access in production.


48. Use CIS Kubernetes Benchmark for compliance checks.


49. Enable admission controllers (PodSecurity, ValidatingWebhook).


50. Perform periodic security audits with tools like Kube-bench/Kubescape.




---

If you want, I can also convert these 50 points into an interview-ready “cheatsheet” in .docx format so you can print and revise quickly.

Do you want me to prepare that formatted docx for you now?


Sunday, August 10, 2025

50 best practices in kubernetes



---

Kubernetes Production Support – 50 Best Practices (Interview Edition)


---

A. Cluster & Node Management

1. Keep Kubernetes version up to date
❌ Old versions miss security patches → vulnerable cluster.
✅ Upgrade using kubeadm upgrade and plan downtime in stages.

kubectl version --short
kubeadm upgrade plan


2. Use multiple master nodes (HA)
❌ Single master = control plane outage if node fails.
✅ Deploy at least 3 masters in HA setup.
(YAML: kubeadm config with stacked etcd)


3. Label & taint nodes
❌ Workloads run on wrong nodes → performance/security risk.
✅ Use labels for scheduling, taints to block unwanted pods.

kubectl label node node1 role=db
kubectl taint nodes node1 dedicated=db:NoSchedule


4. Enable Cluster Autoscaler
❌ Manual scaling → delays & outages under load.
✅ Deploy autoscaler with cloud provider integration.

kubectl apply -f cluster-autoscaler.yaml


5. Reserve system resources
❌ Kubelet starved → node unstable.
✅ Add --system-reserved in kubelet config.
(kubelet config YAML)


6. Monitor node health
❌ Node failures unnoticed → pod downtime.
✅ Use kubectl get nodes + Prometheus alerts.

kubectl get nodes -o wide


7. Spread workloads across zones
❌ Zone outage takes all workloads down.
✅ Use topology spread constraints or node labels.

topologySpreadConstraints:
  - maxSkew: 1


8. Avoid overcommitting resources
❌ Pods evicted due to memory pressure.
✅ Monitor requests/limits ratio in Grafana.

kubectl top nodes


9. Tune OS/kernel for containers
❌ Network & disk latency issues.
✅ Enable cgroupv2, adjust sysctl params.

sysctl -w net.ipv4.ip_forward=1


10. Apply OS security updates
❌ Vulnerable kernel exploited.
✅ Automate patching with maintenance windows.

apt update && apt upgrade -y




---

B. Pod & Workload Management

11. Set resource requests/limits
❌ Pods hog resources → others throttled.
✅ Define CPU/memory in manifests.

resources:
  requests:
    cpu: 200m
    memory: 256Mi
  limits:
    cpu: 500m
    memory: 512Mi


12. Configure PodDisruptionBudgets
❌ All pods evicted during maintenance.
✅ Set minAvailable or maxUnavailable.

minAvailable: 2


13. Readiness/Liveness probes
❌ Unhealthy pods still receive traffic.
✅ HTTP/TCP probes in manifest.

livenessProbe:
  httpGet:
    path: /health
    port: 8080


14. Pod anti-affinity for critical apps
❌ Critical pods on same node → single point failure.
✅ Set requiredDuringSchedulingIgnoredDuringExecution.

podAntiAffinity: ...


15. Init containers for dependencies
❌ Main app starts before DB ready.
✅ Init container checks service availability.

initContainers: ...


16. Use correct controller type
❌ Stateful apps lose data with Deployments.
✅ Use StatefulSet for stateful workloads.


17. Lightweight, scanned images
❌ Large images slow deploy, vulnerabilities possible.
✅ Use trivy/grype for scans.


18. No root containers
❌ Privilege escalation risk.
✅ securityContext.runAsNonRoot: true.


19. Use imagePullPolicy=IfNotPresent
❌ Unnecessary image pulls → deploy delays.
✅ Set in manifests.


20. Version-tag images
❌ Latest tag causes inconsistent rollouts.
✅ Use semantic version tags.




---

C. Networking & Service Management

21. Right service type
❌ Exposing internal services publicly.
✅ ClusterIP internal, LoadBalancer/Ingress for external.


22. Secure Ingress with TLS
❌ Plaintext traffic vulnerable to sniffing.
✅ TLS cert in Ingress manifest.


23. NetworkPolicies
❌ Pods can talk to everything.
✅ Allow only required traffic.


24. No public API server
❌ Cluster takeover risk.
✅ Restrict via firewall/security groups.


25. Stable DNS via CoreDNS monitoring
❌ Service resolution failures.
✅ Alerts on CoreDNS pod health.


26. Headless services for Stateful workloads
❌ Stateful pods fail to discover peers.
✅ clusterIP: None in Service.


27. Connection timeouts/retries
❌ Hanging requests block clients.
✅ App-level configs + Istio retries.


28. externalTrafficPolicy=Local
❌ Client IP lost for logging.
✅ Set in Service manifest.


29. Limit public access
❌ Attackers exploit open services.
✅ Security groups + firewall rules.


30. Load-test before go-live
❌ Crashes under real traffic.
✅ Use k6/locust.




---

D. Observability & Troubleshooting

31. Prometheus + Grafana
❌ No performance visibility.
✅ Deploy kube-prometheus-stack.


32. Centralized logs (ELK/Loki)
❌ No log correlation during incidents.
✅ Fluentd/FluentBit collectors.


33. Enable audit logging
❌ No trace of API actions.
✅ API server --audit-log-path.


34. Alerts for restarts/resource issues
❌ Issues unnoticed until outage.
✅ Prometheus rules.


35. kubectl describe/logs
❌ Slow troubleshooting.
✅ Standard first step.


36. Runbooks
❌ Inconsistent incident handling.
✅ Confluence/Docs with steps.


37. kubectl top for bottlenecks
❌ Capacity issues unidentified.
✅ Resource tuning.


38. Distributed tracing
❌ Slow services hard to debug.
✅ Jaeger/OpenTelemetry.


39. Historical metrics
❌ No capacity planning data.
✅ Long-term storage in Thanos.


40. DR playbook testing
❌ Failover fails during disaster.
✅ Quarterly drills.




---

E. Security & Compliance

41. RBAC
❌ Users have excessive permissions.
✅ Role/RoleBinding per namespace.


42. Namespaces for isolation
❌ Cross-application interference.
✅ One namespace per app/team.


43. Image scanning
❌ Deploying vulnerable images.
✅ trivy CI scan.


44. Secrets management
❌ Credentials exposed in plain text.
✅ kubectl create secret.


45. Rotate secrets
❌ Stolen creds remain valid.
✅ Automate with Vault/KMS.


46. API auth & authorization
❌ Unauthorized cluster actions.
✅ Certs, tokens, OIDC.


47. Restrict kubectl exec
❌ Attackers run commands inside pods.
✅ PSP or RBAC deny.


48. CIS Benchmark
❌ Non-compliant cluster.
✅ kube-bench checks.


49. Admission controllers
❌ Bad manifests deployed.
✅ PodSecurity/ValidatingWebhook.


50. Periodic security audits
❌ Vulnerabilities stay unnoticed.
✅ kubescape scans.




---

If you want, I can now convert this into a single-page “Kubernetes Production Support Interview Cheatsheet” PDF so you can print and use before interviews.
Do you want me to prepare that?


kuber



---

1) Keep Kubernetes versions up to date

What will happen if you don’t: Security vulnerabilities, incompatibilities, unsupported behavior and lack of bug fixes.

How: Follow Kubernetes upgrade policy; test upgrades in staging; upgrade control plane first, then worker nodes.

Key commands:

kubectl version --short
kubeadm upgrade plan
kubeadm upgrade apply v1.27.6

Example: (upgrade plan is CLI-driven; no YAML)



---

2) Use multiple master/control-plane nodes for HA

What will happen if you don’t: Single control-plane node becomes a single point of failure; cluster control operations may stop.

How: Deploy at least 3 control-plane nodes with etcd quorum; use external load balancer in front of API servers.

Key commands: (control plane bootstrap via kubeadm / cloud provider)

# Example: check control plane endpoints
kubectl get endpoints -n default

YAML/snippet: (LB config is infra-specific; example kubeadm init with control-plane endpoint)

kubeadm init --control-plane-endpoint "api.mycluster.example:6443" --upload-certs



---

3) Label and taint nodes for workload segregation

What will happen if you don’t: Critical pods may co-locate with noisy or untrusted workloads; scheduling may place wrong apps on wrong hardware.

How: Use kubectl label and kubectl taint to dedicate nodes (e.g., GPU, high-memory).

Key commands:

kubectl label node node01 node-role.kubernetes.io/highmem=true
kubectl taint nodes node01 dedicated=highmem:NoSchedule

YAML (Pod using nodeSelector / toleration):

spec:
  nodeSelector:
    node-role.kubernetes.io/highmem: "true"
  tolerations:
  - key: "dedicated"
    operator: "Equal"
    value: "highmem"
    effect: "NoSchedule"



---

4) Use Cluster Autoscaler (node autoscaling)

What will happen if you don’t: Under-provisioning during spikes causes pending pods; over-provisioning wastes cost.

How: Install Cluster Autoscaler configured per cloud provider; tune scale-up/down policies and node groups.

Key commands:

# check CA deployment
kubectl get deployment cluster-autoscaler -n kube-system
kubectl logs -f deploy/cluster-autoscaler -n kube-system

YAML (typical Deployment args excerpt):

spec:
  containers:
  - name: cluster-autoscaler
    args:
    - --cloud-provider=aws
    - --nodes=1:10:node-group-name



---

5) Reserve system resources on nodes (system-reserved/kube-reserved)

What will happen if you don’t: Kubelet and system daemons can be starved of CPU/memory causing node instability.

How: Configure kubelet flags or kubelet config to reserve CPU/memory for system and kube components.

Key commands: (edit kubelet config or systemd args, then restart kubelet)

# example check
kubectl describe node node01 | grep -i reserved

kubelet config snippet:

kind: KubeletConfiguration
apiVersion: kubelet.config.k8s.io/v1beta1
systemReserved:
  cpu: "500m"
  memory: "512Mi"
kubeReserved:
  cpu: "500m"
  memory: "512Mi"



---

6) Monitor node health continuously

What will happen if you don’t: Node failures go unnoticed until apps fail; slow detection prolongs incidents.

How: Integrate Prometheus node exporters, alert on node:node_cpu:, node_memory_ and kube_node_status_condition.

Key commands:

kubectl get nodes
kubectl describe node <node>

PromQL example alert:

kube_node_status_condition{condition="Ready",status="true"} == 0



---

7) Spread workloads across zones/regions

What will happen if you don’t: AZ failure brings down many pods; reduced resilience and higher blast radius.

How: Use topologySpreadConstraints, pod anti-affinity, and multiple node pools across AZs.

Key commands: (inspect topology)

kubectl get nodes -o wide
kubectl get pods -o wide --field-selector=status.phase=Running

YAML (topologySpreadConstraints sample):

spec:
  topologySpreadConstraints:
  - maxSkew: 1
    topologyKey: topology.kubernetes.io/zone
    whenUnsatisfiable: DoNotSchedule
    labelSelector:
      matchLabels:
        app: myapp



---

8) Avoid overcommitting node resources

What will happen if you don’t: Nodes become CPU/memory-saturated causing OOMKill, node pressure, eviction cascades.

How: Enforce resource requests/limits, and use ResourceQuotas & LimitRanges in namespaces.

Key commands:

kubectl get resourcequota -n <ns>
kubectl describe limitrange -n <ns>

YAML (limitrange example):

apiVersion: v1
kind: LimitRange
metadata: { name: limits }
spec:
  limits:
  - default:
      cpu: "500m"
      memory: "512Mi"
    defaultRequest:
      cpu: "200m"
      memory: "256Mi"
    type: Container



---

9) Tune OS & kernel for container workloads

What will happen if you don’t: Suboptimal networking, CPU scheduling, and disk performance; noisy neighbor issues.

How: Set sysctl parameters, enable overlayfs options, tune ephemeral storage and file descriptors, set net.ipv4.ip_forward=1, etc.

Key commands: (example sysctl inspect/apply)

sysctl net.ipv4.ip_forward
sudo sysctl -w net.ipv4.ip_forward=1

Example (sysctl in Pod via securityContext / sysctls):

securityContext:
  sysctls:
  - name: net.ipv4.ip_forward
    value: "1"



---

10) Apply OS-level security updates regularly

What will happen if you don’t: Nodes become vulnerable to exploits; container runtimes and kernel exploits risk cluster compromise.

How: Patch OS in a rolling manner (cordon → drain → update → uncordon), use immutable images for hosts or managed node pools.

Key commands:

kubectl cordon node01
kubectl drain node01 --ignore-daemonsets --delete-local-data
# perform OS update on node
kubectl uncordon node01

YAML: (no YAML — operational workflow)


Alright — let’s go deep into Scenario 1 and Scenario 2, covering:

What will happen (impact & symptoms)

Why it happens (root cause)

How to fix it (step-by-step)

Commands to diagnose & resolve

YAML examples if applicable



---

Scenario 1 – Pods Stuck in CrashLoopBackOff

What will happen

Pod keeps restarting in a loop instead of running normally.

Status shows CrashLoopBackOff in kubectl get pods.

Application inside the container starts, fails quickly, and Kubernetes retries indefinitely (with backoff delay increasing each time).


Example:

$ kubectl get pods
NAME READY STATUS RESTARTS AGE
app-pod-1 0/1 CrashLoopBackOff 5 2m


---

Why it happens

Common causes:

1. Application code crashes (exception, missing file, bad config).


2. Wrong environment variables (DB host, credentials missing).


3. Port conflict (two processes binding same port).


4. Readiness/Liveness probes failing → Kubernetes kills and restarts container.




---

How to fix it

Step 1 – Check pod logs:

kubectl logs <pod-name> -n <namespace>
kubectl logs <pod-name> -n <namespace> --previous # previous container run

Step 2 – Describe pod for events:

kubectl describe pod <pod-name> -n <namespace>

Look for:

Probe failures

ImagePullBackOff

OutOfMemoryKilled


Step 3 – If it’s a config/env issue:

Update ConfigMap or Secret.


kubectl edit configmap <configmap-name> -n <namespace>
kubectl rollout restart deployment <deployment-name> -n <namespace>

Step 4 – If probe is too aggressive:

Relax initialDelaySeconds or timeoutSeconds.



---

YAML Example – Fixing a Liveness Probe Failure

apiVersion: apps/v1
kind: Deployment
metadata:
  name: sample-app
  namespace: demo
spec:
  replicas: 1
  selector:
    matchLabels:
      app: sample
  template:
    metadata:
      labels:
        app: sample
    spec:
      containers:
      - name: sample-container
        image: myregistry.com/sample:1.0
        ports:
        - containerPort: 8080
        envFrom:
        - configMapRef:
            name: app-config
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 30
          timeoutSeconds: 5
          failureThreshold: 5


---

✅ Quick Tip: If you just want to debug without probe restarts:

kubectl edit deployment sample-app -n demo
# Remove the livenessProbe temporarily


---

Scenario 2 – Pods Stuck in Pending

What will happen

Pods stay in Pending state, never starting containers.

Seen in:


$ kubectl get pods
NAME READY STATUS RESTARTS AGE
app-pod-2 0/1 Pending 0 5m


---

Why it happens

1. No matching nodes (NodeSelector, Affinity, Taints prevent scheduling).


2. Insufficient resources (CPU/memory requests too high).


3. Storage issues (PVC cannot be bound to a PV).


4. Cluster Autoscaler not scaling up nodes.




---

How to fix it

Step 1 – Describe pod:

kubectl describe pod <pod-name> -n <namespace>

Look for:

0/3 nodes are available: insufficient memory

0/3 nodes are available: node(s) didn't match node selector

persistentvolumeclaim is not bound


Step 2 – If resource request is too high:

kubectl edit deployment <deployment-name> -n <namespace>
# Reduce requests under spec.containers.resources.requests

Step 3 – If PVC not bound:

Check:

kubectl get pvc -n <namespace>
kubectl describe pvc <pvc-name> -n <namespace>

Create matching PV if needed:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv1
spec:
  capacity:
    storage: 1Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: /data/pv1

Step 4 – If affinity/taint issue:

Remove or adjust affinity/taint rules in YAML.



---

YAML Example – Adjusting NodeSelector

apiVersion: apps/v1
kind: Deployment
metadata:
  name: sample-app
spec:
  replicas: 1
  selector:
    matchLabels:
      app: sample
  template:
    metadata:
      labels:
        app: sample
    spec:
      nodeSelector:
        kubernetes.io/hostname: worker-1 # Remove if blocking scheduling
      containers:
      - name: sample-container
        image: myregistry.com/sample:1.0
        resources:
          requests:
            cpu: "100m"
            memory: "128Mi"


---

Alright, let’s go deep into Scenario 1 and Scenario 2 with:

What will happen (Impact)

How it happens (Root cause)

Troubleshooting & Fix steps

Commands (for diagnosis and fix)

YAML examples (where applicable)



---

Scenario 1 – Pods Stuck in CrashLoopBackOff

What Will Happen

Pod continuously restarts after failing to start successfully.

Application downtime until the issue is fixed.

CPU/memory usage spikes due to repeated container restarts.

In production, this may cause cascading failures if dependent services rely on this pod.



---

How It Happens

Application process exits with a non-zero status code.

Missing or incorrect environment variables.

Dependencies (DB, API) not reachable.

Readiness/liveness probes failing repeatedly.

ConfigMap/Secret values missing or wrong.



---

Troubleshooting Steps

1. Check pod status and events



kubectl get pods -n <namespace>
kubectl describe pod <pod-name> -n <namespace>

2. Check logs of the container



kubectl logs <pod-name> -n <namespace> --previous

3. Verify configuration files and environment variables



kubectl exec -it <pod-name> -n <namespace> -- env

4. Check readiness/liveness probes



kubectl get pod <pod-name> -n <namespace> -o yaml | grep -A 10 readinessProbe

5. Check dependent services



kubectl run tmp-shell --rm -it --image=busybox -- sh
# ping DB, API, etc.


---

Example Fix YAML

If liveness/readiness probes are too strict:

livenessProbe:
  httpGet:
    path: /health
    port: 8080
  initialDelaySeconds: 30
  periodSeconds: 10

readinessProbe:
  httpGet:
    path: /ready
    port: 8080
  initialDelaySeconds: 30
  periodSeconds: 10


---

Production Tip

If issue persists but you need to stop restart loops temporarily:

kubectl scale deployment <deployment-name> --replicas=0 -n <namespace>


---

Scenario 2 – ImagePullBackOff / ErrImagePull

What Will Happen

Pod never starts because the container image cannot be pulled.

Affected application remains unavailable.

If multiple pods use the same image, a large part of the service might be down.



---

How It Happens

Wrong image name, tag, or registry URL.

Image deleted or tag changed in registry.

Private registry requires credentials but none provided.

Network/DNS issues blocking access to registry.



---

Troubleshooting Steps

1. Check events for detailed pull error



kubectl describe pod <pod-name> -n <namespace>

2. Verify image name and tag



kubectl get pod <pod-name> -n <namespace> -o yaml | grep image:

3. Test registry access from inside the cluster



kubectl run tmp-shell --rm -it --image=busybox -- sh
# Inside shell
wget <registry-url>

4. Check imagePullSecrets



kubectl get secrets -n <namespace>
kubectl describe secret <secret-name> -n <namespace>


---

Example Fix YAML

If using a private registry:

apiVersion: v1
kind: Pod
metadata:
  name: my-private-pod
spec:
  containers:
    - name: my-app
      image: myprivateregistry.com/app:1.0
  imagePullSecrets:
    - name: myregistry-secret

Create secret:

kubectl create secret docker-registry myregistry-secret \
  --docker-server=myprivateregistry.com \
  --docker-username=myuser \
  --docker-password=mypass \
  --docker-email=myemail@example.com \
  -n <namespace>


---

If you want, I can now do Scenario 3 (Pods stuck in Pending) and Scenario 4 (OOMKilled) in the same style so you’ll have a continuous production playbook. That will make it easier to compile into one printable PDF.

Great — continuing with the same deep-dive style. Here are Scenario 3 (Pending) and Scenario 4 (OOMKilled) with impact, causes, step-by-step troubleshooting, commands, YAML snippets, and quick production tips.


---

Scenario 3 – Pod Stuck in Pending

What will happen

Pod remains in Pending and never transitions to Running.

No containers start; the workload is unavailable.

Often a sign of scheduling/resource or storage problems.


How it happens (common root causes)

Insufficient cluster resources (CPU / memory) to satisfy requests.

NodeSelector / NodeAffinity / taints block scheduling.

PVC is not bound (no matching PV).

Pod topology constraints or quota limits preventing placement.

Cluster Autoscaler not configured or unable to scale.


Troubleshooting & Fix Steps

1. Describe the pod to see scheduler events



kubectl describe pod <pod-name> -n <ns>
# Look for messages like: "0/5 nodes are available: insufficient memory" or "node(s) didn't match node selector"

2. Check node capacity and available resources



kubectl get nodes -o wide
kubectl top nodes
kubectl describe node <node-name>

3. Check resource requests/limits of the pod



kubectl get pod <pod-name> -n <ns> -o yaml | yq '.spec.containers[].resources'
# or
kubectl describe pod <pod-name> -n <ns> | grep -A5 "Requests"

If requests too high → edit Deployment to lower requests.


4. Check node selectors / affinity / taints



kubectl get pod <pod-name> -n <ns> -o yaml | yq '.spec | {nodeSelector: .nodeSelector, affinity: .affinity, tolerations: .tolerations}'
kubectl get nodes --show-labels
kubectl describe node <node> | grep Taints -A2

Remove or relax overly strict selectors/affinities or add matching node labels.


5. If PVC is pending, inspect PVC/PV



kubectl get pvc -n <ns>
kubectl describe pvc <pvc-name> -n <ns>
kubectl get pv

Create a matching PV or adjust StorageClass.


6. If cluster autoscaler should add nodes, check CA logs



kubectl logs deploy/cluster-autoscaler -n kube-system

Adjust CA node-group min/max or node group configuration.


Commands to remediate (examples)

Reduce resource requests:


kubectl set resources deployment/<deploy> -n <ns> --requests=cpu=200m,memory=256Mi

Remove a nodeSelector (edit deployment):


kubectl edit deploy <deploy> -n <ns>
# remove spec.template.spec.nodeSelector section

Create a simple PV for PVC binding:


apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv-small
spec:
  capacity:
    storage: 5Gi
  accessModes:
    - ReadWriteOnce
  persistentVolumeReclaimPolicy: Retain
  hostPath:
    path: /mnt/data/pv-small

kubectl apply -f pv-small.yaml

Quick Production Tip

Enforce default requests via LimitRange and use ResourceQuotas to prevent runaway requests that keep pods pending.



---

Scenario 4 – OOMKilled (Container Killed Due to Out Of Memory)

What will happen

Container process is killed by the kernel (OOM Killer).

Pod restarts; repeated OOMs lead to CrashLoopBackOff or degraded service.

Memory pressure can affect co-located pods and node stability.


How it happens (common root causes)

Container memory limit too low for the workload.

Memory leak in the application.

Bursty workload without proper resource provisioning.

No limits set → node exhaustion leading to multiple pod evictions.


Troubleshooting & Fix Steps

1. Describe the pod to confirm OOMKilled



kubectl describe pod <pod-name> -n <ns> | grep -i -A5 "State" 
# Look for 'Reason: OOMKilled' in container status

2. Check container logs & previous logs



kubectl logs <pod-name> -n <ns>
kubectl logs <pod-name> -n <ns> --previous

3. Check resource usage



kubectl top pod <pod-name> -n <ns>
kubectl top node <node-name>

4. Inspect kubelet and syslogs on the node (if you have node access)



journalctl -u kubelet -n 200
dmesg | grep -i -E "oom|killed process"

5. If memory leak suspected: attach profiler, heap dump, or increase logging to capture allocations.



Commands & Remediations

Increase memory limit (imperative)


kubectl set resources deployment/<deploy> -n <ns> --limits=memory=1Gi --requests=memory=512Mi

Edit deployment (declarative)


spec:
  containers:
  - name: app
    image: myapp:1.2
    resources:
      requests:
        memory: "512Mi"
        cpu: "250m"
      limits:
        memory: "1Gi"
        cpu: "1"

Temporarily reduce load by scaling down replicas or rate-limiting traffic via Ingress:


kubectl scale deploy <deploy> --replicas=1 -n <ns>

If node OOM is observed: cordon & drain node, investigate other pods:


kubectl cordon <node>
kubectl drain <node> --ignore-daemonsets --delete-local-data

Quick Production Tip

Set both requests and limits. Requests ensure scheduler places the pod properly; limits prevent a single pod from starving others. Use monitoring (Prometheus) to create alerting on memory RSS close to limit (e.g., >80%).



---

Would you like me to continue with Scenario 5 (Service Not Accessible) and Scenario 6 (DNS/CoreDNS issues) next in the same format?




kuber



---

1) Keep Kubernetes versions up to date

What will happen if you don’t: Security vulnerabilities, incompatibilities, unsupported behavior and lack of bug fixes.

How: Follow Kubernetes upgrade policy; test upgrades in staging; upgrade control plane first, then worker nodes.

Key commands:

kubectl version --short
kubeadm upgrade plan
kubeadm upgrade apply v1.27.6

Example: (upgrade plan is CLI-driven; no YAML)



---

2) Use multiple master/control-plane nodes for HA

What will happen if you don’t: Single control-plane node becomes a single point of failure; cluster control operations may stop.

How: Deploy at least 3 control-plane nodes with etcd quorum; use external load balancer in front of API servers.

Key commands: (control plane bootstrap via kubeadm / cloud provider)

# Example: check control plane endpoints
kubectl get endpoints -n default

YAML/snippet: (LB config is infra-specific; example kubeadm init with control-plane endpoint)

kubeadm init --control-plane-endpoint "api.mycluster.example:6443" --upload-certs



---

3) Label and taint nodes for workload segregation

What will happen if you don’t: Critical pods may co-locate with noisy or untrusted workloads; scheduling may place wrong apps on wrong hardware.

How: Use kubectl label and kubectl taint to dedicate nodes (e.g., GPU, high-memory).

Key commands:

kubectl label node node01 node-role.kubernetes.io/highmem=true
kubectl taint nodes node01 dedicated=highmem:NoSchedule

YAML (Pod using nodeSelector / toleration):

spec:
  nodeSelector:
    node-role.kubernetes.io/highmem: "true"
  tolerations:
  - key: "dedicated"
    operator: "Equal"
    value: "highmem"
    effect: "NoSchedule"



---

4) Use Cluster Autoscaler (node autoscaling)

What will happen if you don’t: Under-provisioning during spikes causes pending pods; over-provisioning wastes cost.

How: Install Cluster Autoscaler configured per cloud provider; tune scale-up/down policies and node groups.

Key commands:

# check CA deployment
kubectl get deployment cluster-autoscaler -n kube-system
kubectl logs -f deploy/cluster-autoscaler -n kube-system

YAML (typical Deployment args excerpt):

spec:
  containers:
  - name: cluster-autoscaler
    args:
    - --cloud-provider=aws
    - --nodes=1:10:node-group-name



---

5) Reserve system resources on nodes (system-reserved/kube-reserved)

What will happen if you don’t: Kubelet and system daemons can be starved of CPU/memory causing node instability.

How: Configure kubelet flags or kubelet config to reserve CPU/memory for system and kube components.

Key commands: (edit kubelet config or systemd args, then restart kubelet)

# example check
kubectl describe node node01 | grep -i reserved

kubelet config snippet:

kind: KubeletConfiguration
apiVersion: kubelet.config.k8s.io/v1beta1
systemReserved:
  cpu: "500m"
  memory: "512Mi"
kubeReserved:
  cpu: "500m"
  memory: "512Mi"



---

6) Monitor node health continuously

What will happen if you don’t: Node failures go unnoticed until apps fail; slow detection prolongs incidents.

How: Integrate Prometheus node exporters, alert on node:node_cpu:, node_memory_ and kube_node_status_condition.

Key commands:

kubectl get nodes
kubectl describe node <node>

PromQL example alert:

kube_node_status_condition{condition="Ready",status="true"} == 0



---

7) Spread workloads across zones/regions

What will happen if you don’t: AZ failure brings down many pods; reduced resilience and higher blast radius.

How: Use topologySpreadConstraints, pod anti-affinity, and multiple node pools across AZs.

Key commands: (inspect topology)

kubectl get nodes -o wide
kubectl get pods -o wide --field-selector=status.phase=Running

YAML (topologySpreadConstraints sample):

spec:
  topologySpreadConstraints:
  - maxSkew: 1
    topologyKey: topology.kubernetes.io/zone
    whenUnsatisfiable: DoNotSchedule
    labelSelector:
      matchLabels:
        app: myapp



---

8) Avoid overcommitting node resources

What will happen if you don’t: Nodes become CPU/memory-saturated causing OOMKill, node pressure, eviction cascades.

How: Enforce resource requests/limits, and use ResourceQuotas & LimitRanges in namespaces.

Key commands:

kubectl get resourcequota -n <ns>
kubectl describe limitrange -n <ns>

YAML (limitrange example):

apiVersion: v1
kind: LimitRange
metadata: { name: limits }
spec:
  limits:
  - default:
      cpu: "500m"
      memory: "512Mi"
    defaultRequest:
      cpu: "200m"
      memory: "256Mi"
    type: Container



---

9) Tune OS & kernel for container workloads

What will happen if you don’t: Suboptimal networking, CPU scheduling, and disk performance; noisy neighbor issues.

How: Set sysctl parameters, enable overlayfs options, tune ephemeral storage and file descriptors, set net.ipv4.ip_forward=1, etc.

Key commands: (example sysctl inspect/apply)

sysctl net.ipv4.ip_forward
sudo sysctl -w net.ipv4.ip_forward=1

Example (sysctl in Pod via securityContext / sysctls):

securityContext:
  sysctls:
  - name: net.ipv4.ip_forward
    value: "1"



---

10) Apply OS-level security updates regularly

What will happen if you don’t: Nodes become vulnerable to exploits; container runtimes and kernel exploits risk cluster compromise.

How: Patch OS in a rolling manner (cordon → drain → update → uncordon), use immutable images for hosts or managed node pools.

Key commands:

kubectl cordon node01
kubectl drain node01 --ignore-daemonsets --delete-local-data
# perform OS update on node
kubectl uncordon node01

YAML: (no YAML — operational workflow)


Alright — let’s go deep into Scenario 1 and Scenario 2, covering:

What will happen (impact & symptoms)

Why it happens (root cause)

How to fix it (step-by-step)

Commands to diagnose & resolve

YAML examples if applicable



---

Scenario 1 – Pods Stuck in CrashLoopBackOff

What will happen

Pod keeps restarting in a loop instead of running normally.

Status shows CrashLoopBackOff in kubectl get pods.

Application inside the container starts, fails quickly, and Kubernetes retries indefinitely (with backoff delay increasing each time).


Example:

$ kubectl get pods
NAME READY STATUS RESTARTS AGE
app-pod-1 0/1 CrashLoopBackOff 5 2m


---

Why it happens

Common causes:

1. Application code crashes (exception, missing file, bad config).


2. Wrong environment variables (DB host, credentials missing).


3. Port conflict (two processes binding same port).


4. Readiness/Liveness probes failing → Kubernetes kills and restarts container.




---

How to fix it

Step 1 – Check pod logs:

kubectl logs <pod-name> -n <namespace>
kubectl logs <pod-name> -n <namespace> --previous # previous container run

Step 2 – Describe pod for events:

kubectl describe pod <pod-name> -n <namespace>

Look for:

Probe failures

ImagePullBackOff

OutOfMemoryKilled


Step 3 – If it’s a config/env issue:

Update ConfigMap or Secret.


kubectl edit configmap <configmap-name> -n <namespace>
kubectl rollout restart deployment <deployment-name> -n <namespace>

Step 4 – If probe is too aggressive:

Relax initialDelaySeconds or timeoutSeconds.



---

YAML Example – Fixing a Liveness Probe Failure

apiVersion: apps/v1
kind: Deployment
metadata:
  name: sample-app
  namespace: demo
spec:
  replicas: 1
  selector:
    matchLabels:
      app: sample
  template:
    metadata:
      labels:
        app: sample
    spec:
      containers:
      - name: sample-container
        image: myregistry.com/sample:1.0
        ports:
        - containerPort: 8080
        envFrom:
        - configMapRef:
            name: app-config
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 30
          timeoutSeconds: 5
          failureThreshold: 5


---

✅ Quick Tip: If you just want to debug without probe restarts:

kubectl edit deployment sample-app -n demo
# Remove the livenessProbe temporarily


---

Scenario 2 – Pods Stuck in Pending

What will happen

Pods stay in Pending state, never starting containers.

Seen in:


$ kubectl get pods
NAME READY STATUS RESTARTS AGE
app-pod-2 0/1 Pending 0 5m


---

Why it happens

1. No matching nodes (NodeSelector, Affinity, Taints prevent scheduling).


2. Insufficient resources (CPU/memory requests too high).


3. Storage issues (PVC cannot be bound to a PV).


4. Cluster Autoscaler not scaling up nodes.




---

How to fix it

Step 1 – Describe pod:

kubectl describe pod <pod-name> -n <namespace>

Look for:

0/3 nodes are available: insufficient memory

0/3 nodes are available: node(s) didn't match node selector

persistentvolumeclaim is not bound


Step 2 – If resource request is too high:

kubectl edit deployment <deployment-name> -n <namespace>
# Reduce requests under spec.containers.resources.requests

Step 3 – If PVC not bound:

Check:

kubectl get pvc -n <namespace>
kubectl describe pvc <pvc-name> -n <namespace>

Create matching PV if needed:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv1
spec:
  capacity:
    storage: 1Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: /data/pv1

Step 4 – If affinity/taint issue:

Remove or adjust affinity/taint rules in YAML.



---

YAML Example – Adjusting NodeSelector

apiVersion: apps/v1
kind: Deployment
metadata:
  name: sample-app
spec:
  replicas: 1
  selector:
    matchLabels:
      app: sample
  template:
    metadata:
      labels:
        app: sample
    spec:
      nodeSelector:
        kubernetes.io/hostname: worker-1 # Remove if blocking scheduling
      containers:
      - name: sample-container
        image: myregistry.com/sample:1.0
        resources:
          requests:
            cpu: "100m"
            memory: "128Mi"


---

Alright, let’s go deep into Scenario 1 and Scenario 2 with:

What will happen (Impact)

How it happens (Root cause)

Troubleshooting & Fix steps

Commands (for diagnosis and fix)

YAML examples (where applicable)



---

Scenario 1 – Pods Stuck in CrashLoopBackOff

What Will Happen

Pod continuously restarts after failing to start successfully.

Application downtime until the issue is fixed.

CPU/memory usage spikes due to repeated container restarts.

In production, this may cause cascading failures if dependent services rely on this pod.



---

How It Happens

Application process exits with a non-zero status code.

Missing or incorrect environment variables.

Dependencies (DB, API) not reachable.

Readiness/liveness probes failing repeatedly.

ConfigMap/Secret values missing or wrong.



---

Troubleshooting Steps

1. Check pod status and events



kubectl get pods -n <namespace>
kubectl describe pod <pod-name> -n <namespace>

2. Check logs of the container



kubectl logs <pod-name> -n <namespace> --previous

3. Verify configuration files and environment variables



kubectl exec -it <pod-name> -n <namespace> -- env

4. Check readiness/liveness probes



kubectl get pod <pod-name> -n <namespace> -o yaml | grep -A 10 readinessProbe

5. Check dependent services



kubectl run tmp-shell --rm -it --image=busybox -- sh
# ping DB, API, etc.


---

Example Fix YAML

If liveness/readiness probes are too strict:

livenessProbe:
  httpGet:
    path: /health
    port: 8080
  initialDelaySeconds: 30
  periodSeconds: 10

readinessProbe:
  httpGet:
    path: /ready
    port: 8080
  initialDelaySeconds: 30
  periodSeconds: 10


---

Production Tip

If issue persists but you need to stop restart loops temporarily:

kubectl scale deployment <deployment-name> --replicas=0 -n <namespace>


---

Scenario 2 – ImagePullBackOff / ErrImagePull

What Will Happen

Pod never starts because the container image cannot be pulled.

Affected application remains unavailable.

If multiple pods use the same image, a large part of the service might be down.



---

How It Happens

Wrong image name, tag, or registry URL.

Image deleted or tag changed in registry.

Private registry requires credentials but none provided.

Network/DNS issues blocking access to registry.



---

Troubleshooting Steps

1. Check events for detailed pull error



kubectl describe pod <pod-name> -n <namespace>

2. Verify image name and tag



kubectl get pod <pod-name> -n <namespace> -o yaml | grep image:

3. Test registry access from inside the cluster



kubectl run tmp-shell --rm -it --image=busybox -- sh
# Inside shell
wget <registry-url>

4. Check imagePullSecrets



kubectl get secrets -n <namespace>
kubectl describe secret <secret-name> -n <namespace>


---

Example Fix YAML

If using a private registry:

apiVersion: v1
kind: Pod
metadata:
  name: my-private-pod
spec:
  containers:
    - name: my-app
      image: myprivateregistry.com/app:1.0
  imagePullSecrets:
    - name: myregistry-secret

Create secret:

kubectl create secret docker-registry myregistry-secret \
  --docker-server=myprivateregistry.com \
  --docker-username=myuser \
  --docker-password=mypass \
  --docker-email=myemail@example.com \
  -n <namespace>


---

If you want, I can now do Scenario 3 (Pods stuck in Pending) and Scenario 4 (OOMKilled) in the same style so you’ll have a continuous production playbook. That will make it easier to compile into one printable PDF.

Great — continuing with the same deep-dive style. Here are Scenario 3 (Pending) and Scenario 4 (OOMKilled) with impact, causes, step-by-step troubleshooting, commands, YAML snippets, and quick production tips.


---

Scenario 3 – Pod Stuck in Pending

What will happen

Pod remains in Pending and never transitions to Running.

No containers start; the workload is unavailable.

Often a sign of scheduling/resource or storage problems.


How it happens (common root causes)

Insufficient cluster resources (CPU / memory) to satisfy requests.

NodeSelector / NodeAffinity / taints block scheduling.

PVC is not bound (no matching PV).

Pod topology constraints or quota limits preventing placement.

Cluster Autoscaler not configured or unable to scale.


Troubleshooting & Fix Steps

1. Describe the pod to see scheduler events



kubectl describe pod <pod-name> -n <ns>
# Look for messages like: "0/5 nodes are available: insufficient memory" or "node(s) didn't match node selector"

2. Check node capacity and available resources



kubectl get nodes -o wide
kubectl top nodes
kubectl describe node <node-name>

3. Check resource requests/limits of the pod



kubectl get pod <pod-name> -n <ns> -o yaml | yq '.spec.containers[].resources'
# or
kubectl describe pod <pod-name> -n <ns> | grep -A5 "Requests"

If requests too high → edit Deployment to lower requests.


4. Check node selectors / affinity / taints



kubectl get pod <pod-name> -n <ns> -o yaml | yq '.spec | {nodeSelector: .nodeSelector, affinity: .affinity, tolerations: .tolerations}'
kubectl get nodes --show-labels
kubectl describe node <node> | grep Taints -A2

Remove or relax overly strict selectors/affinities or add matching node labels.


5. If PVC is pending, inspect PVC/PV



kubectl get pvc -n <ns>
kubectl describe pvc <pvc-name> -n <ns>
kubectl get pv

Create a matching PV or adjust StorageClass.


6. If cluster autoscaler should add nodes, check CA logs



kubectl logs deploy/cluster-autoscaler -n kube-system

Adjust CA node-group min/max or node group configuration.


Commands to remediate (examples)

Reduce resource requests:


kubectl set resources deployment/<deploy> -n <ns> --requests=cpu=200m,memory=256Mi

Remove a nodeSelector (edit deployment):


kubectl edit deploy <deploy> -n <ns>
# remove spec.template.spec.nodeSelector section

Create a simple PV for PVC binding:


apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv-small
spec:
  capacity:
    storage: 5Gi
  accessModes:
    - ReadWriteOnce
  persistentVolumeReclaimPolicy: Retain
  hostPath:
    path: /mnt/data/pv-small

kubectl apply -f pv-small.yaml

Quick Production Tip

Enforce default requests via LimitRange and use ResourceQuotas to prevent runaway requests that keep pods pending.



---

Scenario 4 – OOMKilled (Container Killed Due to Out Of Memory)

What will happen

Container process is killed by the kernel (OOM Killer).

Pod restarts; repeated OOMs lead to CrashLoopBackOff or degraded service.

Memory pressure can affect co-located pods and node stability.


How it happens (common root causes)

Container memory limit too low for the workload.

Memory leak in the application.

Bursty workload without proper resource provisioning.

No limits set → node exhaustion leading to multiple pod evictions.


Troubleshooting & Fix Steps

1. Describe the pod to confirm OOMKilled



kubectl describe pod <pod-name> -n <ns> | grep -i -A5 "State" 
# Look for 'Reason: OOMKilled' in container status

2. Check container logs & previous logs



kubectl logs <pod-name> -n <ns>
kubectl logs <pod-name> -n <ns> --previous

3. Check resource usage



kubectl top pod <pod-name> -n <ns>
kubectl top node <node-name>

4. Inspect kubelet and syslogs on the node (if you have node access)



journalctl -u kubelet -n 200
dmesg | grep -i -E "oom|killed process"

5. If memory leak suspected: attach profiler, heap dump, or increase logging to capture allocations.



Commands & Remediations

Increase memory limit (imperative)


kubectl set resources deployment/<deploy> -n <ns> --limits=memory=1Gi --requests=memory=512Mi

Edit deployment (declarative)


spec:
  containers:
  - name: app
    image: myapp:1.2
    resources:
      requests:
        memory: "512Mi"
        cpu: "250m"
      limits:
        memory: "1Gi"
        cpu: "1"

Temporarily reduce load by scaling down replicas or rate-limiting traffic via Ingress:


kubectl scale deploy <deploy> --replicas=1 -n <ns>

If node OOM is observed: cordon & drain node, investigate other pods:


kubectl cordon <node>
kubectl drain <node> --ignore-daemonsets --delete-local-data

Quick Production Tip

Set both requests and limits. Requests ensure scheduler places the pod properly; limits prevent a single pod from starving others. Use monitoring (Prometheus) to create alerting on memory RSS close to limit (e.g., >80%).



---

Would you like me to continue with Scenario 5 (Service Not Accessible) and Scenario 6 (DNS/CoreDNS issues) next in the same format?




best kuber

Got it ✅ — I’ll prepare Kubernetes 50 Best Practices for Production Support in this structure for each point:

1. Best Practice (clear, short title)


2. What will happen if followed / if ignored (impact)


3. How to implement (step-by-step)


4. Commands (imperative)


5. YAML Example (if applicable)



Here’s the first 5 points in the new format — once you confirm this is what you want, I’ll continue with all 50:


---

1. Use Resource Requests & Limits for All Pods

What will happen:

If followed: Prevents noisy neighbor problems, ensures fair resource distribution, avoids node overload.

If ignored: Pods may consume excessive CPU/memory, causing other workloads to crash or get evicted.


How to implement:

1. Define CPU & memory requests (minimum) and limits (maximum) for each container.


2. Apply them in all deployments.



Command:

kubectl set resources deployment my-app --limits=cpu=500m,memory=512Mi --requests=cpu=200m,memory=256Mi

YAML Example:

resources:
  requests:
    cpu: "200m"
    memory: "256Mi"
  limits:
    cpu: "500m"
    memory: "512Mi"


---

2. Set Liveness & Readiness Probes

What will happen:

If followed: Detects unhealthy containers and restarts them automatically, ensures only ready pods receive traffic.

If ignored: Traffic may be routed to unhealthy pods, causing errors or downtime.


How to implement:

1. Add livenessProbe to check container health.


2. Add readinessProbe to delay traffic until the pod is ready.



Command:

kubectl edit deployment my-app # Add probes under containers

YAML Example:

livenessProbe:
  httpGet:
    path: /health
    port: 8080
  initialDelaySeconds: 15
  periodSeconds: 10
readinessProbe:
  httpGet:
    path: /ready
    port: 8080
  initialDelaySeconds: 5
  periodSeconds: 5


---

3. Use Pod Disruption Budgets (PDB)

What will happen:

If followed: Prevents too many pods from being evicted during maintenance, ensuring app availability.

If ignored: A node upgrade or drain may remove all pods at once, causing downtime.


How to implement:

1. Create a PDB specifying min pods available or max unavailable.



Command:

kubectl create pdb my-app-pdb --selector=app=my-app --min-available=2

YAML Example:

apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: my-app-pdb
spec:
  minAvailable: 2
  selector:
    matchLabels:
      app: my-app


---

4. Enable Logging & Centralized Log Collection

What will happen:

If followed: Easy debugging with all logs in one place (e.g., ELK, Loki, or Splunk).

If ignored: Troubleshooting requires manually checking each pod’s logs.


How to implement:

1. Ensure apps log to stdout & stderr.


2. Use Fluentd/Fluent Bit/Logstash to collect logs.



Command:

kubectl logs -f my-pod

(Central logging tools handle multi-pod aggregation.)

YAML Example (Fluent Bit DaemonSet snippet):

containers:
  - name: fluent-bit
    image: fluent/fluent-bit:latest
    volumeMounts:
      - name: varlog
        mountPath: /var/log


---

5. Use Network Policies for Traffic Control

What will happen:

If followed: Limits which pods/services can communicate, enhancing security.

If ignored: Any pod can connect to any other pod, risk of lateral movement in attacks.


How to implement:

1. Define NetworkPolicy to allow only required ingress/egress.



Command:

kubectl apply -f allow-frontend-to-backend.yaml

YAML Example:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-frontend-to-backend
spec:
  podSelector:
    matchLabels:
      role: backend
  ingress:
  - from:
    - podSelector:
        matchLabels:
          role: frontend


---

If you confirm, I’ll prepare all 50 best practices in this format so you have a complete production-ready reference with impact, implementation, commands, and YAML examples.

Do you want me to continue with the remaining 45 in this same detailed style?


best practices in kubernetes

Here’s a 50-point crisp checklist of Kubernetes production support best practices you can use in interviews — short, sharp, and easy to remember.


Kubernetes Production Support – 50 Best Practices

A. Cluster & Node Management

  1. Keep Kubernetes version up to date with LTS and security patches.
  2. Use multiple master nodes for HA (High Availability).
  3. Label and taint nodes for workload segregation.
  4. Use autoscaling for nodes (Cluster Autoscaler).
  5. Reserve system resources on nodes using --system-reserved.
  6. Regularly monitor node health via kubectl get nodes.
  7. Spread workloads across zones/regions for resilience.
  8. Avoid overcommitting node resources beyond safe limits.
  9. Ensure OS and kernel are tuned for container workloads.
  10. Apply OS-level security updates on nodes regularly.

B. Pod & Workload Management

  1. Use resource requests and limits for all pods.
  2. Configure PodDisruptionBudgets to avoid downtime during maintenance.
  3. Use Readiness and Liveness probes for health checks.
  4. Implement pod anti-affinity to avoid co-locating critical workloads.
  5. Use init containers for dependency checks before main app starts.
  6. Deploy workloads via Deployment, StatefulSet, or DaemonSet as per use case.
  7. Keep images lightweight and scan for vulnerabilities.
  8. Avoid running pods as root.
  9. Use imagePullPolicy=IfNotPresent for stable deployments.
  10. Tag images with version, not latest.

C. Networking & Service Management

  1. Use ClusterIP for internal services, LoadBalancer/Ingress for external.
  2. Secure Ingress with TLS (Let’s Encrypt or custom certs).
  3. Use NetworkPolicies to control pod-to-pod communication.
  4. Avoid exposing the API server publicly.
  5. Keep DNS resolution stable via CoreDNS monitoring.
  6. Use headless services for Stateful workloads.
  7. Implement connection timeouts and retries in services.
  8. Configure externalTrafficPolicy=Local for preserving client IP.
  9. Limit public access to services via firewalls or security groups.
  10. Load-test services before going live.

D. Observability & Troubleshooting

  1. Integrate Prometheus & Grafana for metrics monitoring.
  2. Centralize logs via ELK or Loki.
  3. Enable Kubernetes audit logging for API server.
  4. Set up alerts for pod restarts, CPU/memory saturation.
  5. Use kubectl describe and kubectl logs for quick debugging.
  6. Maintain runbooks for common incident scenarios.
  7. Use kubectl top to identify resource bottlenecks.
  8. Set up traceability with OpenTelemetry/Jaeger.
  9. Store historical metrics for capacity planning.
  10. Regularly test disaster recovery (DR) playbooks.

E. Security & Compliance

  1. Enable Role-Based Access Control (RBAC).
  2. Use namespaces for workload isolation.
  3. Scan container images before deployment.
  4. Use secrets in Kubernetes Secret objects, not plain env variables.
  5. Rotate secrets and credentials periodically.
  6. Enable API authentication and authorization.
  7. Restrict kubectl exec access in production.
  8. Use CIS Kubernetes Benchmark for compliance checks.
  9. Enable admission controllers (PodSecurity, ValidatingWebhook).
  10. Perform periodic security audits with tools like Kube-bench/Kubescape.

If you want, I can also convert these 50 points into an interview-ready “cheatsheet” in .docx format so you can print and revise quickly.

Do you want me to prepare that formatted docx for you now?

kubernetes crisp

Got it — you want crisp, 30–45 second interview-ready answers for each Kubernetes real-time scenario, so you can speak confidently without sounding like you’re reading a script.

I’ll make them in this format:

ScenarioConcise Answer (Why + How + Example in bullets, with imperative command if relevant)


1. Pods Stuck in CrashLoopBackOff

  • Why: Container is repeatedly failing — bad config, missing env vars, wrong image.
  • How: Describe how to check logs, events, and fix root cause.
  • Example:
    kubectl describe pod <pod>
    kubectl logs <pod> -c <container>
    
  • Interview line: “First, I’d check kubectl describe and logs to see the failure reason, fix the image/config, then redeploy.”

2. Pod Pending (Scheduling Issue)

  • Why: No matching node (resource shortage, node selector mismatch, taints).
  • How: Check events, resource requests, node taints.
  • Example:
    kubectl describe pod <pod>
    kubectl get nodes --show-labels
    
  • Interview line: “I’d inspect scheduling events, verify resource requests, and adjust node selectors or scale nodes.”

3. High CPU/Memory Usage

  • Why: Container limits too low, memory leak, heavy workload.
  • How: Use metrics, adjust resources, scale pods.
  • Example:
    kubectl top pod
    kubectl top node
    kubectl scale deploy <name> --replicas=5
    
  • Interview line: “I’d use kubectl top to confirm high usage, then tune requests/limits or scale the deployment.”

4. Service Not Accessible

  • Why: Service type mismatch, wrong selector, missing endpoints.
  • How: Check service endpoints and pod labels.
  • Example:
    kubectl get svc
    kubectl describe svc <svc>
    kubectl get endpoints <svc>
    
  • Interview line: “I’d verify the service has correct selectors and endpoints, then test connectivity from inside the cluster.”

5. Image Pull BackOff

  • Why: Wrong image name, private repo without creds.
  • How: Fix image reference or add imagePullSecret.
  • Example:
    kubectl create secret docker-registry mysecret --docker-username=... --docker-password=...
    
  • Interview line: “I’d confirm the image name, check registry access, and add an imagePullSecret if needed.”

If you want, I can prepare all 20 Lloyds scenarios in this exact 30–45 second bullet style with imperative commands so you have a single “speak-ready” document for the interview.

Do you want me to go ahead and prepare the full 20 in this short-answer style?



Alright, here’s a Kubernetes Troubleshooting Interview Quick-Answer Sheet — each scenario condensed into 30–45 seconds with key imperative commands you can rattle off in an interview without over-talking.



---


1. Pod Stuck in CrashLoopBackOff


Short Answer:

"Usually due to application crashes or bad configs. First, check logs and events to find the root cause, fix config, and redeploy."

Commands:


kubectl get pod <pod> -n <ns>

kubectl logs <pod> -n <ns> --previous

kubectl describe pod <pod> -n <ns>

kubectl rollout restart deploy <deploy> -n <ns>



---


2. Pod Pending


Short Answer:

"Pending means the scheduler can’t place the pod — usually no matching nodes, insufficient resources, or affinity rules blocking scheduling."

Commands:


kubectl describe pod <pod> -n <ns>

kubectl get nodes -o wide

kubectl describe node <node>



---


3. ImagePullBackOff


Short Answer:

"Registry auth issues, wrong image name, or tag mismatch. Check events and fix image config or secret."

Commands:


kubectl describe pod <pod> -n <ns>

kubectl create secret docker-registry <name> \

  --docker-server=<server> --docker-username=<user> \

  --docker-password=<pass> --docker-email=<email>

kubectl patch serviceaccount default \

  -p '{"imagePullSecrets":[{"name":"<name>"}]}'



---


4. Node Not Ready


Short Answer:

"Can be due to kubelet failure, disk pressure, network issue, or cloud node health problem. Check node status and kubelet logs."

Commands:


kubectl get nodes

kubectl describe node <node>

journalctl -u kubelet -f



---


5. High Pod Restarts


Short Answer:

"Often caused by memory/CPU limits, readiness probe failure, or app bugs. Analyze logs, events, and resource usage."

Commands:


kubectl logs <pod> -n <ns>

kubectl top pod <pod> -n <ns>

kubectl describe pod <pod> -n <ns>



---


6. OOMKilled


Short Answer:

"Container exceeded memory limit. Increase limits or optimize memory usage."

Commands:


kubectl describe pod <pod> -n <ns>

kubectl edit deploy <deploy> -n <ns>



---


7. Service Not Accessible


Short Answer:

"Check if service type and selector match pods, and ensure endpoints are created."

Commands:


kubectl get svc -n <ns>

kubectl describe svc <svc> -n <ns>

kubectl get endpoints <svc> -n <ns>



---


8. DNS Resolution Failing


Short Answer:

"Usually CoreDNS crash or misconfig. Check CoreDNS pods and logs."

Commands:


kubectl get pods -n kube-system -l k8s-app=kube-dns

kubectl logs -n kube-system <coredns-pod>



---


9. PVC Pending


Short Answer:

"StorageClass mismatch or no available PV. Check PVC events and storage backend."

Commands:


kubectl describe pvc <pvc> -n <ns>

kubectl get sc

kubectl get pv



---


10. Deployment Not Updating


Short Answer:

"Wrong selector, failing readiness probe, or paused rollout. Check rollout status."

Commands:


kubectl rollout status deploy <deploy> -n <ns>

kubectl rollout resume deploy <deploy> -n <ns>

kubectl describe deploy <deploy> -n <ns>



---


If you want, I can expand this to all 20 Lloyds interview scenarios in the same short-answer + imperative command style so you can literally answer in 40 seconds per question in the interview w

ithout going blank.


Do you want me to prepare all 20 like this in one printable PDF? That will make it a perfect rapid-fire prep sheet.


Saturday, August 9, 2025

yaml node affinity

Node affinity 
--‐-----------------
Add a label to a node 

List the nodes in your cluster, along with their labels:

kubectl get nodes --show-labels
The output is similar to this:

NAME STATUS ROLES AGE VERSION LABELS
worker0 Ready <none> 1d v1.13.0 ...,kubernetes.io/hostname=worker0
worker1 Ready <none> 1d v1.13.0 ...,kubernetes.io/hostname=worker1
worker2 Ready <none> 1d v1.13.0 ...,kubernetes.io/hostname=worker2
Choose one of your nodes, and add a label to it:

kubectl label nodes <your-node-name> disktype=ssd
where <your-node-name> is the name of your chosen node.

Verify that your chosen node has a disktype=ssd label:

kubectl get nodes --show-labels
The output is similar to this:

NAME STATUS ROLES AGE VERSION LABELS
worker0 Ready <none> 1d v1.13.0 ...,disktype=ssd,kubernetes.io/hostname=worker0
worker1 Ready <none> 1d v1.13.0 ...,kubernetes.io/hostname=worker1
worker2 Ready <none> 1d v1.13.0 ...,kubernetes.io/hostname=worker2
In the preceding output, you can see that the worker0 node has a disktype=ssd label.

Schedule a Pod using required node affinity
This manifest describes a Pod that has a requiredDuringSchedulingIgnoredDuringExecution node affinity,disktype: ssd. This means that the pod will get scheduled only on a node that has a disktype=ssd label.

pods/pod-nginx-required-affinity.yaml

apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
        - matchExpressions:
          - key: disktype
            operator: In
            values:
            - ssd            
  containers:
  - name: nginx
    image: nginx
    imagePullPolicy: IfNotPresent
Apply the manifest to create a Pod that is scheduled onto your chosen node:

kubectl apply -f https://k8s.io/examples/pods/pod-nginx-required-affinity.yaml
Verify that the pod is running on your chosen node:

kubectl get pods --output=wide
The output is similar to this:

NAME READY STATUS RESTARTS AGE IP NODE
nginx 1/1 Running 0 13s 10.200.0.4 worker0
Schedule a Pod using preferred node affinity
This manifest describes a Pod that has a preferredDuringSchedulingIgnoredDuringExecution node affinity,disktype: ssd. This means that the pod will prefer a node that has a disktype=ssd label.

pods/pod-nginx-preferred-affinity.yaml

apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  affinity:
    nodeAffinity:
      preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 1
        preference:
          matchExpressions:
          - key: disktype
            operator: In
            values:
            - ssd          
  containers:
  - name: nginx
    image: nginx
    imagePullPolicy: IfNotPresent
Apply the manifest to create a Pod that is scheduled onto your chosen node:

kubectl apply -f https://k8s.io/examples/pods/pod-nginx-preferred-affinity.yaml
Verify that the pod is running on your chosen node:

kubectl get pods --output=wide
The output is similar to this:

NAME READY STATUS RESTARTS AGE IP NODE
nginx 1/1 Running 0 13s 10.200.0.4 worker0

Node affinity is conceptually similar to nodeSelector, allowing you to constrain which nodes your Pod can be scheduled on based on node labels. There are two types of node affinity:

requiredDuringSchedulingIgnoredDuringExecution: The scheduler can't schedule the Pod unless the rule is met. This functions like nodeSelector, but with a more expressive syntax.
preferredDuringSchedulingIgnoredDuringExecution: The scheduler tries to find a node that meets the rule. If a matching node is not available, the scheduler still schedules the Pod.
Note:
In the preceding types, IgnoredDuringExecution means that if the node labels change after Kubernetes schedules the Pod, the Pod continues to run.
You can specify node affinities using the .spec.affinity.nodeAffinity field in your Pod spec.

For example, consider the following Pod spec:

apiVersion: v1
kind: Pod
metadata:
  name: with-node-affinity
spec:
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
        - matchExpressions:
          - key: topology.kubernetes.io/zone
            operator: In
            values:
            - antarctica-east1
            - antarctica-west1
      preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 1
        preference:
          matchExpressions:
          - key: another-node-label-key
            operator: In
            values:
            - another-node-label-value
  containers:
  - name: with-node-affinity
    image: registry.k8s.io/pause:3.8

In this example, the following rules apply:

The node must have a label with the key topology.kubernetes.io/zone and the value of that label must be either antarctica-east1 or antarctica-west1.
The node preferably has a label with the key another-node-label-key and the value another-node-label-value.
You can use the operator field to specify a logical operator for Kubernetes to use when interpreting the rules. You can use In, NotIn, Exists, DoesNotExist, Gt and Lt.

Read Operators to learn more about how these work.

NotIn and DoesNotExist allow you to define node anti-affinity behavior. Alternatively, you can use node taints to repel Pods from specific nodes.

Note:
If you specify both nodeSelector and nodeAffinity, both must be satisfied for the Pod to be scheduled onto a node.

If you specify multiple terms in nodeSelectorTerms associated with nodeAffinity types, then the Pod can be scheduled onto a node if one of the specified terms can be satisfied (terms are ORed).

If you specify multiple expressions in a single matchExpressions field associated with a term in nodeSelectorTerms, then the Pod can be scheduled onto a node only if all the expressions are satisfied (expressions are ANDed).