Kubernetes Cheat Sheet: kubectl Commands and YAML Examples
kubernetes-cheatsheet is a practical kubectl and Kubernetes cheat sheet for developers, DevOps engineers and people studying for the CKA, CKAD or CKS exams. It lists the kubectl commands you actually type every day (contexts, get, describe, logs, exec, port-forward, rollouts, scaling, debugging), explains the core objects (Pods, Deployments, Services, Ingress and Gateway API, ConfigMaps, Secrets, volumes, Jobs, RBAC, NetworkPolicies), and ships schema-validated YAML manifests you can copy into a real cluster.
Every manifest in manifests/ passes strict schema validation with kubeconform and a set of consistency tests (selectors match labels, services find pods, containers are hardened and use pinned image tags).
Last reviewed: December 2026. Kubernetes 1.37 (released August 2026) was the newest minor release at review time; commands were checked against kubectl 1.34 and manifests validated against the 1.34 schemas. Always check kubernetes.io/releases for the current version.
git clone https://github.com/Ralpberry-Labs/kubernetes-cheatsheet
cd kubernetes-cheatsheet
kubectl create namespace demo
kubectl -n demo create secret generic postgres-auth --from-literal=password='change-me'
kubectl apply -k manifests/ # everything except Ingress / Gateway examples
kubectl -n demo get all
Table of Contents
- Kubernetes in One Page
- Setup: kubectl, Contexts and Namespaces
- Resource Short Names
- Viewing Resources: get and describe
- Output Formats, JSONPath and Custom Columns
- Creating and Updating Resources
- Imperative Generators (Fast YAML)
- Logs, exec, port-forward and cp
- Deployments, Rollouts and Scaling
- Services and Networking
- Ingress vs Gateway API
- ConfigMaps and Secrets
- Storage
- Jobs and CronJobs
- Labels, Selectors and Annotations
- Resources, Probes and Scheduling
- Security: RBAC, Pod Security, NetworkPolicy
- Nodes and Cluster Maintenance
- Troubleshooting by Symptom
- YAML Manifest Library
- Helm and Kustomize
- Local Kubernetes Clusters Compared
- Managed Kubernetes Services
- Best Tools Around kubectl
- Exam Tips: CKA, CKAD, CKS
- FAQ
- Where to Go Next
- Contributing
- License
- More free resources
Kubernetes in One Page
Kubernetes runs containers across a group of machines (a cluster) and keeps them in the state you declare. You write YAML describing what you want (“3 copies of this container, reachable on port 80”); controllers continuously work to make reality match.
| Object | What it is | You use it to |
|---|---|---|
| Pod | One or more containers sharing a network namespace and volumes | The unit that runs; rarely created directly |
| Deployment | Manages ReplicaSets of identical Pods, with rolling updates | Run stateless apps (web servers, APIs) |
| ReplicaSet | Keeps N Pods running | Managed by Deployments; do not edit directly |
| StatefulSet | Pods with stable names and per-pod storage | Databases, queues, clustered apps |
| DaemonSet | One Pod per node | Log shippers, monitoring agents, CNI |
| Job / CronJob | Run to completion, once or on a schedule | Migrations, batch work, reports |
| Service | Stable virtual IP + DNS name for a set of Pods | Internal load balancing and discovery |
| Ingress / Gateway + HTTPRoute | HTTP(S) routing from outside | Expose web apps with hosts, paths and TLS |
| ConfigMap / Secret | Configuration and credentials | Inject env vars or files |
| PersistentVolumeClaim | A request for storage | Data that survives Pod restarts |
| Namespace | A virtual partition of the cluster | Separate teams, apps or environments |
| ServiceAccount, Role, RoleBinding | Identity and permissions | Least-privilege access to the API |
| NetworkPolicy | Pod-level firewall rules | Restrict which Pods can talk |
| HorizontalPodAutoscaler | Scales replicas on metrics | Handle load automatically |
| Node | A machine (VM or physical) running Pods | Capacity |
Control plane components: kube-apiserver (the API everything talks to), etcd (the database), kube-scheduler (picks a node for each Pod), kube-controller-manager (runs the control loops), and on every node kubelet (starts containers) and kube-proxy or a CNI replacement (Service networking).
Setup: kubectl, Contexts and Namespaces
Install kubectl from the official instructions, or with a package manager (brew install kubectl, winget install Kubernetes.kubectl). Keep kubectl within one minor version of your cluster’s API server.
kubectl version # client and server versions
kubectl cluster-info
kubectl config view --minify # current context's config
kubectl config get-contexts # list contexts (cluster + user + namespace)
kubectl config current-context
kubectl config use-context my-cluster # switch cluster
kubectl config set-context --current --namespace=demo # default namespace for this context
kubectl config rename-context old new
kubectl config delete-context old
export KUBECONFIG=~/.kube/config:~/.kube/staging.yaml # merge several kubeconfig files
kubectl config view --flatten > merged.yaml
kubectl auth whoami # who the API server thinks you are
Useful shell setup:
alias k=kubectl
source <(kubectl completion bash) # or: kubectl completion zsh
complete -o default -F __start_kubectl k # bash: completion for the alias
export do="--dry-run=client -o yaml" # k create deploy web --image=nginx $do
export now="--force --grace-period=0" # k delete pod x $now (test clusters only)
Namespaces:
kubectl get namespaces
kubectl create namespace demo
kubectl get pods -n demo
kubectl get pods -A # all namespaces (--all-namespaces)
kubectl delete namespace demo # deletes everything inside it
Resource Short Names
| Short | Resource | Short | Resource |
|---|---|---|---|
po |
pods | deploy |
deployments |
rs |
replicasets | sts |
statefulsets |
ds |
daemonsets | cj |
cronjobs |
svc |
services | ep |
endpoints (prefer endpointslices) |
ing |
ingresses | netpol |
networkpolicies |
cm |
configmaps | sa |
serviceaccounts |
pv |
persistentvolumes | pvc |
persistentvolumeclaims |
sc |
storageclasses | ns |
namespaces |
no |
nodes | hpa |
horizontalpodautoscalers |
pdb |
poddisruptionbudgets | crd |
customresourcedefinitions |
ev |
events | quota |
resourcequotas |
limits |
limitranges | csr |
certificatesigningrequests |
kubectl api-resources lists every resource type, its short names, API group and whether it is namespaced. kubectl explain deployment.spec.strategy prints field documentation from the cluster’s own schema; add --recursive to see the whole tree.
Viewing Resources: get and describe
kubectl get pods # in the current namespace
kubectl get pods -o wide # + node, IP
kubectl get pods --show-labels
kubectl get pods -l app.kubernetes.io/name=web # label selector
kubectl get pods -l 'env in (prod,staging),tier!=db'
kubectl get pods --field-selector status.phase=Running
kubectl get pods --field-selector spec.nodeName=node-1
kubectl get pods --sort-by=.metadata.creationTimestamp
kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'
kubectl get pods -w # watch for changes
kubectl get deploy,svc,ing # several types
kubectl get all # common workload types (not everything)
kubectl get pod web-abc -o yaml # full object, including status
kubectl describe pod web-abc # human summary + recent events
kubectl describe node node-1 # capacity, allocations, conditions, taints
kubectl get events --sort-by=.lastTimestamp
kubectl events --for pod/web-abc # events for one object
kubectl events -A --types=Warning # only warnings, all namespaces
kubectl top nodes # CPU/memory (needs metrics-server)
kubectl top pods --containers --sort-by=memory
describe is the first command to run when something is wrong: the Events section at the bottom usually names the problem.
Output Formats, JSONPath and Custom Columns
| Flag | Output |
|---|---|
-o wide |
Extra columns |
-o yaml, -o json |
Full object |
-o name |
type/name only (great for scripts) |
-o jsonpath='{...}' |
Extract fields |
-o custom-columns=... |
Your own table |
-o go-template='...' |
Go templates |
# All pod names
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
# One per line with a range
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}'
# Images used in the namespace
kubectl get pods -o jsonpath='{.items[*].spec.containers[*].image}' | tr ' ' '\n' | sort -u
# Filter: pods on a given node
kubectl get pods -o jsonpath='{.items[?(@.spec.nodeName=="node-1")].metadata.name}'
# Decode a secret value
kubectl get secret web-secrets -o jsonpath='{.data.DATABASE_URL}' | base64 -d
# Node internal IPs
kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="InternalIP")].address}'
# Custom columns
kubectl get pods -o custom-columns='NAME:.metadata.name,NODE:.spec.nodeName,IMAGE:.spec.containers[0].image,RESTARTS:.status.containerStatuses[0].restartCount'
# Pipe JSON to jq
kubectl get deploy -o json | jq -r '.items[] | "\(.metadata.name) \(.status.readyReplicas)/\(.spec.replicas)"'
Creating and Updating Resources
| Command | Style | Use |
|---|---|---|
kubectl apply -f file.yaml |
Declarative | Create or update from files; the normal way |
kubectl apply -f dir/ / -k dir/ |
Declarative | A folder / a Kustomize overlay |
kubectl create -f file.yaml |
Imperative | Create only; fails if it exists |
kubectl replace -f file.yaml |
Imperative | Full replacement |
kubectl edit deploy/web |
Interactive | Quick fixes in $EDITOR |
kubectl patch |
Imperative | Change specific fields |
kubectl set image/env/resources |
Imperative | Common one-field updates |
kubectl delete -f file.yaml |
Delete what a file defines |
kubectl apply -f manifests/02-deployment.yaml
kubectl apply -f https://example.com/app.yaml # from a URL you trust
kubectl diff -f manifests/ # what apply would change
kubectl apply -f manifests/ --dry-run=server # server-side validation, no changes
kubectl apply --server-side -f manifests/ # server-side apply (field ownership)
kubectl apply -f manifests/ --prune -l app=demo # also delete labelled objects no longer in files (use with care)
kubectl patch deploy web -p '{"spec":{"replicas":5}}' # strategic merge
kubectl patch deploy web --type=json -p '[{"op":"replace","path":"/spec/replicas","value":2}]'
kubectl set image deploy/web web=nginxinc/nginx-unprivileged:1.31-alpine
kubectl set env deploy/web LOG_LEVEL=debug
kubectl set env deploy/web --list
kubectl set resources deploy/web -c web --requests=cpu=200m,memory=256Mi --limits=memory=512Mi
kubectl delete pod web-abc
kubectl delete pods -l app.kubernetes.io/name=web
kubectl delete deploy web --cascade=orphan # keep the pods
kubectl wait --for=condition=Available deploy/web --timeout=120s
kubectl wait --for=delete pod/web-abc --timeout=60s
kubectl wait --for=jsonpath='{.status.phase}'=Running pod/web-abc
Imperative Generators (Fast YAML)
Generate a correct starting manifest instead of typing YAML from memory. These work without a cluster when combined with --dry-run=client -o yaml:
kubectl create deployment web --image=nginx:1.30-alpine --replicas=3 --port=80 --dry-run=client -o yaml > deploy.yaml
kubectl run debug --image=busybox:1.37 --restart=Never --dry-run=client -o yaml -- sleep 3600
kubectl expose deployment web --port=80 --target-port=8080 --dry-run=client -o yaml
kubectl create service clusterip web --tcp=80:8080 --dry-run=client -o yaml
kubectl create configmap app-config --from-literal=LOG_LEVEL=info --from-file=app.properties --dry-run=client -o yaml
kubectl create secret generic db --from-literal=password=s3cret --dry-run=client -o yaml
kubectl create secret tls web-tls --cert=tls.crt --key=tls.key --dry-run=client -o yaml
kubectl create secret docker-registry regcred --docker-server=ghcr.io --docker-username=me --docker-password="$TOKEN" --dry-run=client -o yaml
kubectl create job migrate --image=busybox:1.37 --dry-run=client -o yaml -- echo hi
kubectl create cronjob nightly --image=busybox:1.37 --schedule="0 2 * * *" --dry-run=client -o yaml -- date
kubectl create job manual-run --from=cronjob/nightly # trigger a CronJob now (needs a cluster)
kubectl create ingress web --class=example --rule="app.example.com/*=web:80,tls=web-tls" --dry-run=client -o yaml
kubectl create role pod-reader --verb=get,list,watch --resource=pods --dry-run=client -o yaml
kubectl create rolebinding read-pods --role=pod-reader --serviceaccount=demo:log-reader --dry-run=client -o yaml
kubectl create serviceaccount ci --dry-run=client -o yaml
kubectl create token ci --duration=1h # short-lived token (needs a cluster)
kubectl create quota team-a --hard=cpu=4,memory=8Gi,pods=20 --dry-run=client -o yaml
kubectl create pdb web --selector=app=web --min-available=2 --dry-run=client -o yaml
kubectl autoscale deployment web --min=3 --max=10 --cpu-percent=70 --dry-run=client -o yaml
Logs, exec, port-forward and cp
kubectl logs web-abc # current container logs
kubectl logs web-abc -c sidecar # a specific container
kubectl logs web-abc --previous # the crashed previous instance (CrashLoopBackOff!)
kubectl logs -f deploy/web # follow, picks one pod of the deployment
kubectl logs -l app.kubernetes.io/name=web --all-containers --prefix --since=1h
kubectl logs web-abc --tail=100 --timestamps
kubectl exec -it web-abc -- sh # shell inside the container
kubectl exec web-abc -c web -- env # run one command
kubectl exec deploy/web -- cat /etc/web/app.properties
kubectl port-forward svc/web 8080:80 # localhost:8080 -> service port 80
kubectl port-forward pod/web-abc 9000:8080
kubectl port-forward deploy/web 8080:8080 --address 0.0.0.0 # listen on all interfaces
kubectl cp demo/web-abc:/tmp/dump.txt ./dump.txt # needs `tar` in the container
kubectl cp ./config.json demo/web-abc:/tmp/config.json
kubectl attach -it pod/debug # attach to a running process
kubectl proxy --port=8001 # API on localhost:8001 with your credentials
Debugging containers without a shell
Minimal and distroless images have no sh. Use ephemeral debug containers:
kubectl debug -it pod/web-abc --image=busybox:1.37 --target=web # share the process namespace of container "web"
kubectl debug pod/web-abc -it --copy-to=web-debug --container=web -- sh # copy of the pod, with a shell override
kubectl debug pod/web-abc -it --copy-to=web-debug --set-image=*=busybox:1.37
kubectl debug node/node-1 -it --image=busybox:1.37 # host filesystem mounted at /host
kubectl debug -it pod/web-abc --image=nicolaka/netshoot --profile=netadmin # network tools
kubectl run tmp --rm -it --image=busybox:1.37 --restart=Never -- sh # throwaway pod in the cluster
Inside a throwaway pod, test DNS and connectivity:
nslookup web.demo.svc.cluster.local
wget -qO- http://web.demo.svc.cluster.local
Deployments, Rollouts and Scaling
kubectl rollout status deploy/web # wait for a rollout to finish
kubectl rollout history deploy/web
kubectl rollout history deploy/web --revision=3
kubectl rollout undo deploy/web # back to the previous revision
kubectl rollout undo deploy/web --to-revision=2
kubectl rollout restart deploy/web # restart all pods (e.g. to pick up a new Secret)
kubectl rollout pause deploy/web # batch several changes...
kubectl rollout resume deploy/web # ...then roll them out once
kubectl annotate deploy/web kubernetes.io/change-cause="bump to 1.31" # shows in rollout history
kubectl scale deploy/web --replicas=5
kubectl scale deploy/web --current-replicas=5 --replicas=2 # only if currently 5
kubectl autoscale deploy/web --min=3 --max=10 --cpu-percent=70
kubectl get hpa -w
Deployment strategies:
| Strategy | How | When |
|---|---|---|
RollingUpdate (default) |
Replace pods gradually (maxSurge, maxUnavailable) |
Most stateless apps |
Recreate |
Kill all, then start new | Apps that cannot run two versions at once |
| Blue/green | Two Deployments, switch the Service selector | Instant switch and rollback |
| Canary | Second Deployment with few replicas, or weighted routes (Gateway API weight) |
Test a release on a slice of traffic |
Tools such as Argo Rollouts and Flagger automate canary and blue/green with metric checks.
Services and Networking
| Service type | Reachable from | Notes |
|---|---|---|
ClusterIP (default) |
Inside the cluster | Stable IP + DNS name.namespace.svc.cluster.local |
Headless (clusterIP: None) |
Inside | DNS returns pod IPs; StatefulSets use it for per-pod names |
NodePort |
<any node IP>:<30000-32767> |
Simple external access, mostly for testing |
LoadBalancer |
External IP from the cloud provider | One cloud load balancer per Service |
ExternalName |
Inside | DNS CNAME to an outside name |
kubectl expose deploy web --port=80 --target-port=8080
kubectl get svc web
kubectl get endpointslices -l kubernetes.io/service-name=web # which pod IPs back it
kubectl describe svc web
If a Service has no endpoints, its selector does not match any ready pod: compare kubectl get svc web -o jsonpath='{.spec.selector}' with kubectl get pods --show-labels, and check readiness probes.
DNS names:
| Name | Resolves to |
|---|---|
web |
Service web in the same namespace |
web.demo |
Service web in namespace demo |
web.demo.svc.cluster.local |
Fully qualified |
postgres-0.postgres.demo.svc.cluster.local |
Pod postgres-0 behind headless Service postgres |
Ingress vs Gateway API
Both route external HTTP(S) traffic to Services, and both need a controller running in the cluster: the YAML alone does nothing.
Ingress (networking.k8s.io/v1) |
Gateway API (gateway.networking.k8s.io/v1) |
|
|---|---|---|
| Status | Stable, frozen (no new features) | Stable core, actively developed |
| Roles | One object mixes infra and app concerns | GatewayClass (provider), Gateway (ops), HTTPRoute (app teams) |
| Features beyond host/path | Controller-specific annotations | Built in: header matching, traffic splitting with weights, redirects, rewrites, mirroring |
| Protocols | HTTP/HTTPS | HTTP, HTTPS, gRPC, TCP, UDP, TLS (some in experimental channel) |
| Portability | Annotations differ per controller | Same spec across implementations |
Important for 2026: the community ingress-nginx controller was retired; per the Kubernetes announcement, best-effort maintenance ended in March 2026 with no further releases or security fixes after that. If you still run it, plan a migration, ideally to a Gateway API implementation. The Gateway API implementations list shows conformant controllers (Envoy Gateway, Istio, Cilium, NGINX Gateway Fabric, Traefik, Kong, cloud provider gateways and others).
Examples: 04-ingress.yaml, 05-gateway-httproute.yaml (with a 90/10 canary split).
kubectl get gatewayclass
kubectl get gateway,httproute -A
kubectl describe httproute web # check "Accepted" and "ResolvedRefs" conditions
kubectl get ingressclass
ConfigMaps and Secrets
kubectl create configmap web-config --from-literal=LOG_LEVEL=info --from-env-file=.env.example
kubectl create secret generic web-secrets --from-literal=DATABASE_URL='postgres://...'
kubectl get secret web-secrets -o jsonpath='{.data.DATABASE_URL}' | base64 -d
kubectl rollout restart deploy/web # env vars are read at start: restart after changes
Four ways to consume them (all shown in 02-deployment.yaml):
| Method | YAML | Updates live? |
|---|---|---|
| All keys as env vars | envFrom: [{configMapRef: {name: x}}] |
No, restart needed |
| One key as env var | env: [{name: K, valueFrom: {secretKeyRef: {name: x, key: K}}}] |
No |
| Files in a volume | volumes: [{configMap: {name: x}}] + volumeMounts |
Yes, eventually (not with subPath) |
| Downward API | fieldRef: {fieldPath: metadata.name} |
Pod metadata as env/files |
Secrets are base64-encoded, not encrypted. Protect them: enable encryption at rest, restrict get/list on secrets with RBAC, and consider External Secrets Operator or Sealed Secrets so plaintext never lands in git. Set immutable: true on ConfigMaps/Secrets that never change; it reduces API server load and accidental edits.
Storage
| Object | Who creates it | Purpose |
|---|---|---|
StorageClass |
Cluster admin / provider | Describes a kind of storage and its provisioner |
PersistentVolumeClaim |
You | “I need 10Gi of RWO storage” |
PersistentVolume |
Usually provisioned automatically | The actual disk |
emptyDir |
You, in the pod spec | Scratch space that lives as long as the pod |
configMap / secret / projected volumes |
You | Config files |
hostPath |
Avoid | Node filesystem; security risk |
Access modes: ReadWriteOnce (one node), ReadOnlyMany, ReadWriteMany (many nodes; needs NFS-like storage), ReadWriteOncePod (one pod).
kubectl get sc # default class is marked "(default)"
kubectl get pvc,pv
kubectl describe pvc uploads # "waiting for first consumer" is normal with WaitForFirstConsumer
kubectl patch pvc uploads -p '{"spec":{"resources":{"requests":{"storage":"20Gi"}}}}' # expand, if the class allows it
Reclaim policy Delete (common default for dynamic provisioning) deletes the disk when the PVC is deleted. Use Retain for data you cannot lose, and back up anyway (for example with Velero).
Jobs and CronJobs
kubectl create job migrate --image=busybox:1.37 -- sh -c 'echo migrating'
kubectl get jobs
kubectl logs job/migrate
kubectl wait --for=condition=complete job/migrate --timeout=300s
kubectl get cronjobs
kubectl create job run-now --from=cronjob/nightly-report
kubectl patch cronjob nightly-report -p '{"spec":{"suspend":true}}'
Key fields (see 07-job-cronjob.yaml): backoffLimit, activeDeadlineSeconds, ttlSecondsAfterFinished, completions and parallelism for batch fan-out, restartPolicy: Never|OnFailure; for CronJobs schedule, timeZone, concurrencyPolicy: Allow|Forbid|Replace, startingDeadlineSeconds, suspend.
Cron syntax: minute hour day-of-month month day-of-week. */15 * * * * every 15 minutes; 0 9 * * 1-5 weekdays at 09:00; 0 0 1 * * monthly.
Labels, Selectors and Annotations
kubectl label pod web-abc tier=frontend
kubectl label pod web-abc tier=backend --overwrite
kubectl label pod web-abc tier- # remove label
kubectl annotate deploy web owner=team-a
kubectl get pods -L app.kubernetes.io/name,tier # labels as columns
Selectors: equality (app=web, env!=prod) and set-based (env in (a,b), env notin (a), tier, !tier).
Recommended labels (from the Kubernetes docs) that tools understand:
| Label | Example |
|---|---|
app.kubernetes.io/name |
web |
app.kubernetes.io/instance |
web-prod |
app.kubernetes.io/version |
1.4.2 |
app.kubernetes.io/component |
frontend |
app.kubernetes.io/part-of |
shop |
app.kubernetes.io/managed-by |
helm |
Labels are for selecting; annotations are for non-identifying metadata (build info, tool configuration). A Deployment’s spec.selector is immutable after creation, so choose it carefully.
Resources, Probes and Scheduling
Requests and limits
| Request | Limit | |
|---|---|---|
| CPU | Used for scheduling; guaranteed share | Throttled above it |
| Memory | Used for scheduling | Container is OOMKilled above it |
Quality of Service classes: Guaranteed (requests = limits for every container), Burstable (some requests), BestEffort (none; evicted first). Practical defaults: always set memory requests and limits; set CPU requests; many teams omit CPU limits to avoid throttling latency-sensitive apps. Enforce defaults per namespace with LimitRange and caps with ResourceQuota.
Units: CPU 1 = one core, 500m = half a core. Memory 128Mi (mebibytes), 1Gi; 128M means megabytes (decimal), a common typo.
Probes
| Probe | Failing means | Effect |
|---|---|---|
startupProbe |
Still starting | Other probes wait; restarts after failureThreshold |
readinessProbe |
Not ready for traffic | Removed from Service endpoints, not restarted |
livenessProbe |
Stuck | Container restarted |
Probe types: httpGet, tcpSocket, exec, grpc. Do not point liveness at dependencies (database down should not restart every web pod); keep it a cheap “process is alive” check.
Scheduling controls
nodeSelector:
kubernetes.io/arch: arm64
tolerations:
- key: dedicated
operator: Equal
value: gpu
effect: NoSchedule
affinity:
podAntiAffinity: # avoid two replicas on one node
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
topologyKey: kubernetes.io/hostname
labelSelector:
matchLabels:
app.kubernetes.io/name: web
priorityClassName: high-priority
kubectl taint nodes gpu-1 dedicated=gpu:NoSchedule
kubectl taint nodes gpu-1 dedicated=gpu:NoSchedule- # remove
kubectl label nodes node-1 disktype=ssd
Security: RBAC, Pod Security, NetworkPolicy
RBAC
| Object | Scope |
|---|---|
Role + RoleBinding |
One namespace |
ClusterRole + ClusterRoleBinding |
Whole cluster |
ClusterRole + RoleBinding |
Reuse a cluster-wide role inside one namespace |
kubectl auth can-i create deployments -n demo
kubectl auth can-i '*' '*' # am I cluster admin?
kubectl auth can-i get pods --as=system:serviceaccount:demo:log-reader -n demo
kubectl auth can-i --list -n demo
kubectl get rolebindings,clusterrolebindings -A -o wide | grep my-user
Example ServiceAccount with read-only pod and log access: 11-rbac.yaml. Set automountServiceAccountToken: false on pods that never call the API.
Pod Security Standards
Namespaces opt in with labels (see 00-namespace.yaml): pod-security.kubernetes.io/enforce: baseline|restricted|privileged. The restricted level requires non-root, no privilege escalation, dropped capabilities and a seccomp profile, which all workloads in this repo satisfy.
Hardened container checklist:
securityContext: # pod level
runAsNonRoot: true
seccompProfile:
type: RuntimeDefault
containers:
- securityContext: # container level
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
NetworkPolicy
By default every pod can reach every other pod. Start with default-deny, then allow specific flows: 10-networkpolicy.yaml. Policies need a CNI that enforces them (Calico, Cilium and most managed offerings do; some basic setups do not). Remember to allow DNS (UDP/TCP 53 to kube-dns) if you also default-deny egress.
Nodes and Cluster Maintenance
kubectl get nodes -o wide
kubectl describe node node-1 | grep -A5 Allocated # requests vs capacity
kubectl cordon node-1 # no new pods
kubectl drain node-1 --ignore-daemonsets --delete-emptydir-data # evict pods (respects PDBs)
kubectl uncordon node-1
kubectl get pods -A --field-selector spec.nodeName=node-1
kubectl get --raw='/readyz?verbose' # API server health checks
kubectl get --raw /metrics | head # API server metrics
kubeadm clusters (CKA territory):
kubeadm upgrade plan
kubeadm upgrade apply v1.37.x # control plane, then each node: kubeadm upgrade node
kubeadm token create --print-join-command
ETCDCTL_API=3 etcdctl snapshot save /backup/etcd.db \
--endpoints=https://127.0.0.1:2379 --cacert=/etc/kubernetes/pki/etcd/ca.crt \
--cert=/etc/kubernetes/pki/etcd/server.crt --key=/etc/kubernetes/pki/etcd/server.key
Upgrade one minor version at a time, control plane first, then nodes; read the release notes for removed APIs before each step. Each minor release gets roughly 14 months of patch support.
Troubleshooting by Symptom
| Pod status / symptom | Usual cause | Commands |
|---|---|---|
Pending |
No node fits: insufficient CPU/memory, taints, node selectors, unbound PVC | kubectl describe pod (Events), kubectl describe node, kubectl get pvc |
ImagePullBackOff / ErrImagePull |
Wrong image name/tag, private registry without imagePullSecrets, rate limits |
kubectl describe pod, check the tag exists, add a pull secret |
CrashLoopBackOff |
App exits on start: bad config, missing env, failing liveness probe | kubectl logs pod --previous, kubectl describe pod (exit code) |
OOMKilled (exit 137) |
Memory limit too low, or a leak | kubectl describe pod (Last State), raise limit, profile |
CreateContainerConfigError |
Referenced ConfigMap/Secret or key missing | kubectl describe pod, kubectl get cm,secret |
RunContainerError |
Bad command/entrypoint, missing volume mount path | kubectl describe pod |
Terminating forever |
Finalizers, unreachable node | kubectl get pod -o yaml (finalizers); last resort --force --grace-period=0 |
Running but 0/1 READY |
Readiness probe failing | kubectl describe pod, test the probe endpoint with kubectl exec |
| Service returns nothing | Selector mismatch, no ready endpoints, wrong targetPort |
kubectl get endpointslices, compare labels |
| Ingress/Gateway 404/503 | Wrong host/path, class name, backend Service/port | kubectl describe ingress / httproute conditions, controller logs |
Evicted pods |
Node under disk or memory pressure | kubectl describe node (Conditions), clean with kubectl delete pod --field-selector=status.phase==Failed |
Forbidden errors |
RBAC | kubectl auth can-i ... --as=... |
| DNS failures | CoreDNS issues, NetworkPolicy blocking port 53 | kubectl -n kube-system get pods -l k8s-app=kube-dns, test with nslookup from a busybox pod |
Exit codes: 0 normal exit, 1 app error, 137 killed by SIGKILL (often OOM), 143 SIGTERM (graceful stop), 126/127 command not executable / not found.
A five-step routine that solves most problems:
kubectl get pods -o wide(status, restarts, node)kubectl describe pod <pod>(events, last state, exit code)kubectl logs <pod> --previous(why it died)kubectl get events --sort-by=.lastTimestamp(what else is happening)kubectl exec/kubectl debug(test from inside)
YAML Manifest Library
All files live in manifests/, use the demo namespace, pinned image tags, resource requests, probes where it makes sense, and a restricted-compatible security context.
| File | Objects | Shows |
|---|---|---|
00-namespace.yaml |
Namespace | Pod Security Admission labels |
01-configmap-secret.yaml |
ConfigMap, Secret | Literal keys, a file key, stringData |
02-deployment.yaml |
Deployment | Rolling update, 3 probes, env from ConfigMap/Secret/Downward API, read-only root FS, topology spread |
03-service.yaml |
Service | ClusterIP with a named target port |
04-ingress.yaml |
Ingress | Host rule, TLS |
05-gateway-httproute.yaml |
Gateway, HTTPRoute | HTTPS listener, path match, weighted canary |
06-hpa-pdb.yaml |
HPA, PodDisruptionBudget | CPU autoscaling with scale-down stabilization |
07-job-cronjob.yaml |
Job, CronJob | Retries, deadlines, TTL cleanup, time zone, concurrency policy |
08-statefulset.yaml |
Headless Service, StatefulSet | Stable identity, volumeClaimTemplates |
09-pvc.yaml |
PVC | Dynamic provisioning |
10-networkpolicy.yaml |
NetworkPolicy x2 | Default deny + allow web to postgres |
11-rbac.yaml |
ServiceAccount, Role, RoleBinding | Least privilege |
12-daemonset.yaml |
DaemonSet | Tolerations for control-plane nodes |
kustomization.yaml |
Kustomize | kubectl apply -k manifests/ |
Validate them yourself:
./tests/validate.sh # kubeconform, strict schemas
uv run --with pyyaml python -m unittest discover -s tests # consistency checks
kubectl apply -k manifests/ --dry-run=server # against a real cluster
Pod skeleton (memorize this)
apiVersion: v1
kind: Pod
metadata:
name: hello
labels:
app: hello
spec:
containers:
- name: hello
image: busybox:1.37
command: ["sh", "-c", "echo hello && sleep 3600"]
resources:
requests: { cpu: 10m, memory: 16Mi }
limits: { memory: 32Mi }
restartPolicy: Always
Multi-container patterns
| Pattern | Example |
|---|---|
| Init container | Wait for a database or run migrations before the app starts (initContainers) |
| Sidecar | Log shipper, proxy, or file syncer next to the app. Native sidecars are init containers with restartPolicy: Always (stable since Kubernetes 1.33): they start before and stop after the main containers |
| Adapter / ambassador | Translate the app’s metrics format; proxy outbound connections |
spec:
initContainers:
- name: wait-for-db
image: busybox:1.37
command: ["sh", "-c", "until nc -z postgres 5432; do sleep 2; done"]
- name: log-shipper # native sidecar
image: busybox:1.37
restartPolicy: Always
command: ["sh", "-c", "tail -F /logs/app.log"]
Deprecated and removed APIs
Old tutorials still use removed API versions. If kubectl apply says “no matches for kind”, update the apiVersion:
| Kind | Use | Removed old versions |
|---|---|---|
| Deployment, DaemonSet, StatefulSet, ReplicaSet | apps/v1 |
extensions/v1beta1, apps/v1beta1, apps/v1beta2 (1.16) |
| Ingress | networking.k8s.io/v1 |
extensions/v1beta1, networking.k8s.io/v1beta1 (1.22) |
| CronJob | batch/v1 |
batch/v1beta1 (1.25) |
| PodDisruptionBudget | policy/v1 |
policy/v1beta1 (1.25) |
| HorizontalPodAutoscaler | autoscaling/v2 |
autoscaling/v2beta1 (1.25), v2beta2 (1.26) |
| PodSecurityPolicy | Pod Security Admission | Removed entirely in 1.25 |
The official deprecated API migration guide lists every removal.
Helm and Kustomize
| Helm | Kustomize | |
|---|---|---|
| Model | Templated charts + values | Plain YAML + patches/overlays |
| Built into kubectl | No | Yes (kubectl apply -k) |
| Packaging / sharing | Charts in repositories and OCI registries | Git folders |
| Best for | Installing third-party software; parameterized apps | Your own manifests across dev/staging/prod |
Helm (Helm 4 is the current major version since November 2025; Helm 3 receives only fixes until early 2027):
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update
helm search repo prometheus
helm show values oci://ghcr.io/stefanprodan/charts/podinfo > values.yaml # charts can live in OCI registries
helm install demo-app oci://ghcr.io/stefanprodan/charts/podinfo -n demo -f values.yaml
helm upgrade --install demo-app oci://ghcr.io/stefanprodan/charts/podinfo -n demo --set replicaCount=2
helm list -A
helm status demo-app -n demo
helm get values demo-app -n demo
helm history demo-app -n demo
helm rollback demo-app 1 -n demo
helm uninstall demo-app -n demo
helm template my ./chart -f values.yaml # render locally, apply nothing
helm lint ./chart
helm create mychart # scaffold a chart
Kustomize overlay layout:
k8s/
├── base/
│ ├── deployment.yaml
│ ├── service.yaml
│ └── kustomization.yaml # resources: [deployment.yaml, service.yaml]
└── overlays/
├── staging/kustomization.yaml
└── prod/kustomization.yaml
# overlays/prod/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: prod
resources:
- ../../base
images:
- name: nginxinc/nginx-unprivileged
newTag: 1.31-alpine
replicas:
- name: web
count: 6
patches:
- target: { kind: Deployment, name: web }
patch: |-
- op: replace
path: /spec/template/spec/containers/0/resources/limits/memory
value: 512Mi
configMapGenerator:
- name: web-config
literals: ["LOG_LEVEL=warn"]
kubectl kustomize k8s/overlays/prod # render
kubectl apply -k k8s/overlays/prod
GitOps tools Argo CD and Flux apply Helm charts and Kustomize overlays from git automatically and report drift.
Local Kubernetes Clusters Compared
| Tool | Runs nodes as | Multi-node | Good for |
|---|---|---|---|
| kind | Docker containers | Yes | CI, testing Kubernetes itself, quick throwaway clusters |
| minikube | VM or container | Yes | Learning; many add-ons (minikube addons enable ingress) |
| k3d | k3s in Docker | Yes | Very fast, light local clusters |
| k3s | Lightweight distribution on a host | Yes | Edge devices, Raspberry Pi, small servers |
| Docker Desktop | Built-in single node (kind-based option available) | Limited | Zero setup if you already use it |
| Rancher Desktop | k3s in a VM | No | Free Docker Desktop alternative with Kubernetes |
kind create cluster --name dev
kind load docker-image myapp:dev --name dev # use a local image without a registry
kind delete cluster --name dev
minikube start --cpus 4 --memory 8g
minikube service web -n demo # open a NodePort/LoadBalancer service
minikube dashboard
Managed Kubernetes Services
| Provider | Service | Notes |
|---|---|---|
| AWS | Amazon EKS | Auto Mode manages nodes; IAM integration via Pod Identity |
| Google Cloud | GKE | Autopilot mode bills per pod resources |
| Azure | AKS | Free control plane tier |
| DigitalOcean | DOKS | Simple, low-cost |
| Linode / Akamai | LKE | Simple, low-cost |
| Civo | Civo Kubernetes | k3s-based, fast cluster creation |
Pricing and free tiers change often; check each provider’s page. Fetch credentials with the provider CLI (aws eks update-kubeconfig, gcloud container clusters get-credentials, az aks get-credentials).
Best Tools Around kubectl
| Tool | What it does | Why pick it |
|---|---|---|
| k9s | Terminal UI for clusters | Fastest way to browse, tail logs and exec; the most popular add-on |
| kubectx + kubens | Switch context / namespace quickly | Two tiny commands you use all day |
| stern | Tail logs from many pods with colours | Better than kubectl logs -l for debugging |
| krew | kubectl plugin manager | Installs ctx, ns, neat, tree and more plugins |
| Headlamp | Web / desktop dashboard (a Kubernetes SIG project) | GUI for people who prefer one |
| kubeconform | Validate manifests against schemas | Fast CI check, used by this repo |
| Popeye | Scans a cluster for misconfigurations | Quick hygiene report |
| kube-linter | Lint YAML for best practices | Catches missing probes, root containers |
| Trivy | Scan images and clusters for vulnerabilities and misconfigs | One tool for both |
| kubectl-neat | Removes clutter from get -o yaml |
Readable YAML to copy |
| Lens | Desktop IDE for Kubernetes | Commercial with a free tier for personal use |
Exam Tips: CKA, CKAD, CKS
The Linux Foundation runs the CKA, CKAD and CKS exams: hands-on tasks in a live terminal, with access to the official Kubernetes docs.
- Set up
alias k=kubectl, completion andexport do="--dry-run=client -o yaml"in the first minute. - Generate YAML with imperative commands, then edit; do not type manifests from scratch.
- Always switch to the context the task names (
kubectl config use-context ...); tasks are spread across clusters. - Use
kubectl explain <kind>.<field>instead of searching docs for field names. - Verify every task (
get,describe,logs) before moving on; skip hard tasks and come back. - Practice with Killercoda scenarios and the simulator sessions included with exam registration.
FAQ
What is the difference between Docker and Kubernetes? Docker (or any OCI tool) builds and runs containers on one machine. Kubernetes schedules and manages containers across many machines: restarts, scaling, networking, rolling updates. Kubernetes runs containers through a container runtime such as containerd or CRI-O.
Do I need Kubernetes? Not for one small app. A PaaS, a single VM with Docker Compose, or serverless containers are simpler. Kubernetes pays off with many services, teams that need a shared platform, or demanding availability and scaling needs.
What is the difference between a Deployment and a StatefulSet?
Deployment pods are interchangeable, with random names and shared (or no) storage. StatefulSet pods have stable names (db-0, db-1), start in order and each gets its own PersistentVolumeClaim.
How do I restart a pod?
Delete it (kubectl delete pod x) if it belongs to a Deployment/StatefulSet; the controller recreates it. To restart all pods of a Deployment: kubectl rollout restart deploy/name.
How do I see why my pod keeps restarting?
kubectl describe pod for the exit code and reason, then kubectl logs pod --previous for the logs of the crashed instance.
Why is my pod stuck in Pending?
The scheduler cannot place it. kubectl describe pod shows the reason: insufficient CPU or memory, taints without tolerations, node selectors that match nothing, or a PVC that cannot bind.
What does kubectl apply do that create does not?
apply is declarative: it creates the object if missing, otherwise computes the difference between your file, the live object and the last applied config, and updates only what changed. create fails if the object exists.
How do I expose my app to the internet?
A Service of type LoadBalancer on a cloud cluster, or a Service plus an Ingress or Gateway API route handled by a controller. For local testing, kubectl port-forward.
Are Kubernetes Secrets secure? Only partially: they are base64-encoded and stored in etcd. Enable encryption at rest, lock down RBAC, and use an external secret manager for sensitive production credentials.
How do I copy a file out of a pod?
kubectl cp namespace/pod:/path ./local. It needs tar in the container image.
How many pods can a node run? The kubelet default is 110 pods per node; managed services set their own limits, often tied to network IP allocation.
What replaced PodSecurityPolicy?
Pod Security Admission (namespace labels with the privileged, baseline and restricted profiles), plus policy engines such as Kyverno or OPA Gatekeeper, or the built-in ValidatingAdmissionPolicy, for custom rules.
Where to Go Next
- Do the official Kubernetes Basics tutorial, then deploy this repo’s manifests to a kind or minikube cluster and break them on purpose.
- Read the concept pages on Workloads, Services and Configuration best practices.
- Keep the official kubectl quick reference open next to this page.
- Learn Helm by installing a real chart, and Kustomize by splitting this repo into base and overlays.
- Add observability: metrics-server, then Prometheus and Grafana (the kube-prometheus-stack chart).
- Practice hard mode with Kubernetes The Hard Way to understand every component.
- Pick a certification (CKAD for developers, CKA for operators) and practice daily on Killercoda.
Contributing
PRs welcome. Keep commands accurate for current kubectl versions, pin image tags in manifests, and run ./tests/validate.sh plus the unittest suite before opening a PR. If a feature depends on a Kubernetes version, say which.
License
MIT. See LICENSE.
If this helped you, a star helps others find it.
More free resources
Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.