⌂ Home

kubectl Command Reference

Comprehensive, copy-ready kubectl patterns: everyday operations, output filters, ergonomics, patching, debugging, and lab cross-links.

Use this guide beside a live cluster. Every tab groups related commands you can paste, adapt, and combine — from kubectl get basics through JSONPath, patches, diff, debug, and RBAC checks.

Start with Everyday and Output & Filtering, keep Tips & Aliases open while you work, then jump to Patching or Debugging when something breaks. The Practice tab mirrors Lab 62 exercises end-to-end.

Daily workflow

Everyday kubectl

Create

Spin up workloads and namespaces; prefer create/apply over deprecated patterns where noted in your cluster version docs.

kubectl run demo --image=nginx:1.25 --restart=Never
kubectl create deployment web --image=nginx:1.25 --replicas=2
kubectl apply -f deployment.yaml
kubectl apply -f ./manifests/ --recursive
kubectl create namespace dev-team
Inspect

List objects, drill into details, and scan the event stream for state transitions.

kubectl get pods,svc,deploy,sts,ds -A
kubectl get nodes -o wide
kubectl describe pod mypod-7d8f9
kubectl get events -A --sort-by=.lastTimestamp | tail -30
kubectl top pods -n prod
Expose

Publish workloads inside the cluster or forward ports for local debugging.

kubectl expose deployment web --port=80 --target-port=8080 --type=ClusterIP
kubectl expose deployment web --type=NodePort --port=80
kubectl port-forward deployment/web 8080:80
kubectl port-forward pod/mypod-abc 8443:443
kubectl port-forward svc/database 5432:5432
Scale

Change replica counts manually or attach metric-driven scaling.

kubectl scale deployment/web --replicas=5
kubectl scale sts/redis --replicas=3
kubectl autoscale deployment web --cpu-percent=70 --min=2 --max=10
kubectl get hpa -w
Delete

Remove objects by name, file, or broad selectors — always scope carefully in shared clusters.

kubectl delete pod unwanted --grace-period=30
kubectl delete deployment,services -l app=demo
kubectl delete -f ./manifest.yaml
kubectl delete all -l app=temp --namespace=sandbox
kubectl delete ns scratch --wait=false
Recipes

Everyday command cookbook

Beyond create/get/delete

ConfigMaps, secrets, cluster metadata, labels, cordon/drain, raw API paths, and kustomize.

Beyond create/get/delete — full command cookbook
kubectl create configmap app --from-literal=key=value --dry-run=client -o yaml
kubectl create secret generic db --from-literal=password=changeme --dry-run=client -o yaml
kubectl create job --from=cronjob/backup manual-run-1 -n cron
kubectl run curl --image=curlimages/curl --rm -it --restart=Never -- curl -s http://web.default.svc.cluster.local
kubectl attach mypod -i -t
kubectl cp -h | head -5
kubectl version --client -o yaml
kubectl version -o json | jq '.serverVersion.gitVersion'
kubectl cluster-info dump --output-directory=/tmp/cluster-dump
kubectl api-versions | sort | tail -20
kubectl api-resources --verbs=list --namespaced -o name
kubectl config view --minify --raw
kubectl config get-contexts
kubectl config set-context --current --namespace=dev
kubectl label pod mypod color=blue --overwrite
kubectl annotate pod mypod inspected-at=$(date -Iseconds)
kubectl taint nodes worker-1 key=value:NoSchedule
kubectl cordon worker-2
kubectl drain worker-2 --ignore-daemonsets --delete-emptydir-data
kubectl uncordon worker-2
kubectl replace -f pod.yaml --force --grace-period=0
kubectl apply --server-side -f deployment.yaml
kubectl kustomize ./overlays/prod/ | kubectl apply -f -
kubectl get --raw /healthz?verbose
kubectl get --raw /api/v1/namespaces/kube-system/pods
Verb & noun cheatsheet

Fifty high-frequency operator commands with a one-line “why” — complements the Everyday cards above.

Verb & noun cheatsheet — fifty commands with notes
IntentCommandNote
Cluster discoverykubectl cluster-infoVerify API endpoint and DNS addon
Contextskubectl config get-contextsSee current * context and namespace defaults
Nodes overviewkubectl get nodes -o wideCapacity, IPs, OS, readiness
All types in namespacekubectl get allShortcut bundle; excludes some resources
Pods by labelkubectl get pods -l app=webEquality selector
Pods multi-resourcekubectl get pods,svc,ingressComma-separated kinds
Describe Podkubectl describe pod PODEvents at bottom — read first
Describe Nodekubectl describe node NODEPressure, capacity, taints
Logs followkubectl logs -f deploy/appFollows first container if only one
Logs previous instancekubectl logs POD --previousAfter crash / restart
Exec shellkubectl exec -it POD -- bashOmit -it for non-TTY scripts
Port-forward Servicekubectl port-forward svc/db 5432:5432Local dev database tunnel
Apply manifestkubectl apply -f dir/Recursive with -R or shell glob
Delete by filekubectl delete -f manifest.yamlRemoves objects declared in file
Delete by labelkubectl delete pods -l run=tmpScoped label delete
Force delete Podkubectl delete pod POD --grace-period=0 --forceLast resort — risks data loss
Scale Deploymentkubectl scale deploy/web --replicas=5Immediate replica change
Autoscalekubectl autoscale deploy web --min=2 --max=8 --cpu-percent=60Creates HPA
Rollout restartkubectl rollout restart deploy/webNew ReplicaSet via annotation bump
Rollout historykubectl rollout history deploy/webSee revision list
Rollout undokubectl rollout undo deploy/webBack to previous ReplicaSet
Expose Deploymentkubectl expose deploy web --port=80Creates ClusterIP Service
Create Job from CronJobkubectl create job run-1 --from=cronjob/backupManual trigger
Create secret generickubectl create secret generic db --from-literal=pw=xImperative secret
Create configmapkubectl create cm app --from-file=app.propertiesFile-backed CM
Dry-run client YAMLkubectl run x --image=nginx --dry-run=client -o yamlBootstrap manifests
Explain fieldkubectl explain pod.spec.containers.portsAPI schema help
API resourceskubectl api-resourcesDiscover kind names and shortnames
API versionskubectl api-versionsWhich group/version pairs exist
Get raw APIkubectl get --raw /versionUnstructured JSON from API server
Auth self-checkkubectl auth can-i create podsRBAC sanity for current user
Auth list allkubectl auth can-i --listEnumerate allowed verbs/resources
Cordon nodekubectl cordon NODEMark unschedulable
Drain nodekubectl drain NODE --ignore-daemonsetsEvict workloads safely
Uncordon nodekubectl uncordon NODEAllow scheduling again
Taint nodekubectl taint nodes NODE k=v:NoScheduleExclusive scheduling
Remove taintkubectl taint nodes NODE dedicated:NoSchedule-Strip matching taint key
Label objectkubectl label deploy web tier=feMutable metadata
Annotate objectkubectl annotate deploy web cost-center=42Non-identifying metadata
Patch mergekubectl patch deploy web -p '{"spec":{"replicas":3}}'Quick field tweak
Wait availablekubectl wait --for=condition=available deploy/web --timeout=120sScript-friendly gate
Copy to Podkubectl cp ./file POD:/tmp/fileTar-based transfer
Top podskubectl top pods -ANeeds metrics-server
Top nodeskubectl top nodesCPU/memory utilization snapshot
Proxy APIkubectl proxy --port=8001Local unauthenticated loopback to API
Kustomize buildkubectl kustomize ./overlay/Render without applying
Diff manifestkubectl diff -f app.yamlPreview apply delta
Server-side applykubectl apply --server-side -f app.yamlField manager conflicts visible
Replace recreatekubectl replace -f pod.yaml --forceRecreate pattern for immutable Pod specs
Debug copy Podkubectl debug POD --copy-to=debug --image=busybox -- shClone for triage
Ephemeral attachkubectl debug POD -it --image=nicolaka/netshoot --target=app -- bashNetwork toolbox sidecar
Pair these with a fixed namespace (-n / --namespace) or kubens so you never delete in the wrong scope.
Views & queries

Output & Filtering

-o wide

Adds node placement and extra network columns beyond the default table.

ResourceExtra columns (typical)
PodsNODE, IP (Pod IP), possibly wider readiness if shown
NodesINTERNAL-IP, EXTERNAL-IP, OS image, kernel, container runtime
ServicesCLUSTER-IP, EXTERNAL-IP (if any), PORT(S)
DeploymentsCONTAINERS/IMAGES selectors, wider strategy columns in some versions
kubectl get pods -o wide
kubectl get nodes -o wide
kubectl get svc -o wide
kubectl get deploy -o wide
-o yaml / -o json

Full API object representation — ideal for saving to Git or piping to tools.

kubectl get deploy web -o yaml > web-deploy.yaml
kubectl get pod mypod -o json | jq '.status.phase'
kubectl get cm app-config -o yaml | yq '.data."app.properties"'
-o jsonpath

Template mini-language: {.path}, {range}, filters [?(@.field==value)].

kubectl get svc web -o jsonpath='{.spec.clusterIP}{"\n"}'
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.podIP}{"\n"}{end}'
kubectl get pods -o jsonpath='{.items[*].spec.containers[*].image}'
kubectl get nodes -o jsonpath='{.items[?(@.status.conditions[-1].type=="Ready")].metadata.name}'
kubectl get deploy web -o jsonpath='{.status.readyReplicas}/{.spec.replicas} ready'

More patterns

kubectl get po -o jsonpath='{range .items[*]}{.metadata.namespace}/{.metadata.name}{"\n"}{end}'
kubectl get no -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.allocatable.cpu}{"\n"}{end}'
-o custom-columns

Syntax: -o custom-columns=NAME:.json.path,NAME2:.other.path — commas separate columns; escape carefully in shells.

kubectl get pods -o custom-columns=NAME:.metadata.name,IP:.status.podIP,NODE:.spec.nodeName,PHASE:.status.phase
kubectl get deploy -o custom-columns=NAME:.metadata.name,IMAGE:.spec.template.spec.containers[0].image,WANT:.spec.replicas,READY:.status.readyReplicas
kubectl get nodes -o custom-columns=NODE:.metadata.name,CPU:.status.capacity.cpu,MEM:.status.capacity.memory,ACPU:.status.allocatable.cpu
-o name

Prints resource/name form — handy for xargs pipelines.

kubectl get pods -o name
kubectl get pods -l app=web -o name | xargs -r kubectl delete
--show-labels

Appends a LABELS column with all key=value pairs on the object.

kubectl get pods --show-labels
kubectl get deploy -n prod --show-labels
-l label selector

Equality app=web, inequality env!=prod, set-based tier in (frontend,api), !release.

kubectl get pods -l app=nginx,tier=frontend
kubectl get all -l 'app in (web,api)'
kubectl delete pods -l 'release notin (stable,beta)'
--field-selector

Filter on declared API fields such as phase, node, or namespace metadata.

kubectl get pods -A --field-selector=status.phase=Running
kubectl get pods --field-selector=spec.nodeName=worker-1
kubectl get pods -A --field-selector=metadata.namespace=kube-system
kubectl get pods --field-selector=status.phase!=Succeeded
--sort-by

JSONPath to a numeric or string field; prefix - for descending where supported.

kubectl get pods --sort-by=.metadata.creationTimestamp
kubectl get pods --sort-by=.metadata.name
kubectl get pods -A --sort-by=.spec.nodeName
kubectl top pods -A
kubectl top nodes
-w (--watch)

Streams subsequent changes after the initial list; combine with labels for focused monitoring.

kubectl get pods -w
kubectl get events -n dev --watch
kubectl get deploy web -w
--no-headers

Suppresses the header row for machine parsing.

kubectl get pods -o name --no-headers
kubectl get ns -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}'
-A (--all-namespaces)

Lists resources across every namespace (subject to RBAC).

kubectl get pods -A
kubectl get svc -A -l app=monitoring
kubectl get events -A --sort-by=.lastTimestamp
Cookbook

Long-form output examples

JSONPath (extended)

Forty-five copy-ready extractions for services, storage, workloads, webhooks, and discovery.

JSONPath Cookbook — 45 copy-ready extractions
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
kubectl get deploy -n prod -o jsonpath='{.items[*].metadata.name}'
kubectl get svc -A -o jsonpath='{range .items[*]}{.metadata.namespace}{"\t"}{.metadata.name}{"\t"}{.spec.clusterIP}{"\n"}{end}'
kubectl get pods -o jsonpath='{.items[0].status.podIP}'
kubectl get nodes -o jsonpath='{.items[*].metadata.name}'
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}'
kubectl get pods -o jsonpath='{.items[?(@.status.phase=="Running")].metadata.name}'
kubectl get pods -o jsonpath='{.items[?(@.spec.nodeName=="worker-1")].metadata.name}'
kubectl get deploy web -o jsonpath='{.metadata.generation}'
kubectl get deploy web -o jsonpath='{.status.observedGeneration}'
kubectl get pods -o jsonpath='{range .items[*]}{.spec.containers[*].name}{"\n"}{end}'
kubectl get pod mypod -o jsonpath='{.spec.containers[0].resources.requests.cpu}'
kubectl get pod mypod -o jsonpath='{.spec.containers[0].resources.limits.memory}'
kubectl get ingress -A -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.rules[*].host}{"\n"}{end}'
kubectl get pv -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}'
kubectl get pvc -A -o jsonpath='{range .items[*]}{.metadata.namespace}/{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}'
kubectl get sa -n kube-system -o jsonpath='{.items[*].metadata.name}'
kubectl get cm coredns -n kube-system -o jsonpath='{.data.Corefile}'
kubectl get nodes -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.nodeInfo.kubeletVersion}{"\n"}{end}'
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.startTime}{"\n"}{end}'
kubectl get deploy -A -o jsonpath='{range .items[*]}{.metadata.namespace}{"\t"}{.metadata.name}{"\t"}{.spec.replicas}{"\n"}{end}'
kubectl get pods -o jsonpath='{.items[*].status.containerStatuses[*].imageID}'
kubectl get pods -o jsonpath='{range .items[*]}{range .status.conditions[*]}{.type}={.status}{"\n"}{end}{end}'
kubectl get hpa -A -o jsonpath='{range .items[*]}{.metadata.namespace}/{.metadata.name}{"\t"}{.status.currentReplicas}/{.spec.maxReplicas}{"\n"}{end}'
kubectl get pdb -A -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.disruptionsAllowed}{"\n"}{end}'
kubectl get networkpolicy -A -o jsonpath='{range .items[*]}{.metadata.namespace}{"\t"}{.metadata.name}{"\n"}{end}'
kubectl get cronjobs -A -o jsonpath='{range .items[*]}{.metadata.namespace}{"\t"}{.metadata.name}{"\t"}{.spec.schedule}{"\n"}{end}'
kubectl get job -A -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.succeeded}{"\n"}{end}'
kubectl get sts -A -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.replicas}{"\t"}{.status.readyReplicas}{"\n"}{end}'
kubectl get ds -A -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.numberReady}{"\t"}{.status.desiredNumberScheduled}{"\n"}{end}'
kubectl get endpointslices -A -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}'
kubectl get validatingwebhookconfigurations -o jsonpath='{.items[*].metadata.name}'
kubectl get mutatingwebhookconfigurations -o jsonpath='{.items[*].metadata.name}'
kubectl get ns -o jsonpath='{.items[*].metadata.name}{"\n"}'
kubectl get nodes -o jsonpath='{.items[?(@.spec.unschedulable==true)].metadata.name}'
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.ownerReferences[0].kind}{"\t"}{.metadata.ownerReferences[0].name}{"\n"}{end}'
kubectl get secret db-secret -o jsonpath='{.data.username}' | base64 -d
kubectl get pod -l app=web -o jsonpath='{.items[0].metadata.annotations}'
kubectl get deploy web -o jsonpath='{.spec.strategy.type}'
kubectl get svc web -o jsonpath='{.spec.ports[0].nodePort}'
kubectl get pod mypod -o jsonpath='{.spec.dnsPolicy}'
kubectl get pod mypod -o jsonpath='{.spec.restartPolicy}'
kubectl get nodes -o jsonpath='{range .items[*]}{.status.allocatable.pods}{" pods on "}{.metadata.name}{"\n"}{end}'
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.serviceAccountName}{"\n"}{end}'
kubectl get rs -l app=web -o jsonpath='{.items[*].metadata.name}'
kubectl api-resources -o name | head -30
custom-columns (extended)

Twenty tabular views when -o wide is not enough.

custom-columns (extended) — twenty tabular views
kubectl get pods -o custom-columns=NS:.metadata.namespace,NAME:.metadata.name,QOS:.status.qosClass
kubectl get pods -o custom-columns=NAME:.metadata.name,RESTARTS:.status.containerStatuses[0].restartCount
kubectl get pods -o custom-columns=NAME:.metadata.name,IMAGE:.spec.containers[0].image,PULL:.spec.containers[0].imagePullPolicy
kubectl get svc -o custom-columns=NAME:.metadata.name,TYPE:.spec.type,CLUSTER_IP:.spec.clusterIP,PORTS:.spec.ports[0].port
kubectl get ingress -o custom-columns=NAME:.metadata.name,CLASS:.spec.ingressClassName,HOSTS:.spec.rules[0].host
kubectl get pvc -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,VOL:.spec.volumeName,SIZE:.spec.resources.requests.storage
kubectl get pv -o custom-columns=NAME:.metadata.name,CAP:.spec.capacity.storage,CLAIM:.spec.claimRef.name,STATUS:.status.phase
kubectl get hpa -o custom-columns=NAME:.metadata.name,TARGET:.spec.scaleTargetRef.name,MIN:.spec.minReplicas,MAX:.spec.maxReplicas,CURRENT:.status.currentReplicas
kubectl get cronjob -o custom-columns=NAME:.metadata.name,SCHEDULE:.spec.schedule,SUSPEND:.spec.suspend
kubectl get job -o custom-columns=NAME:.metadata.name,COMPLETIONS:.status.succeeded,ACTIVE:.status.active,FAILED:.status.failed
kubectl get pdb -o custom-columns=NAME:.metadata.name,MIN:.spec.minAvailable,MAX:.spec.maxUnavailable,ALLOWED:.status.disruptionsAllowed
kubectl get networkpolicy -o custom-columns=NAME:.metadata.name,PODSEL:.spec.podSelector.matchLabels.app
kubectl get cm -o custom-columns=NAME:.metadata.name,KEYS:.data
kubectl get secret -o custom-columns=NAME:.metadata.name,TYPE:.type,KEYS:.data
kubectl get sa -o custom-columns=NAME:.metadata.name,NS:.metadata.namespace,SECRETS:.secrets[0].name
kubectl get endpoints -o custom-columns=NAME:.metadata.name,ENDPOINTS:.subsets[0].addresses[0].ip
kubectl get rs -o custom-columns=NAME:.metadata.name,DESIRED:.spec.replicas,CURRENT:.status.replicas,READY:.status.readyReplicas
kubectl get sts -o custom-columns=NAME:.metadata.name,REPLICAS:.spec.replicas,READY:.status.readyReplicas,CURRENT:.status.currentReplicas
kubectl get ds -o custom-columns=NAME:.metadata.name,DESIRED:.status.desiredNumberScheduled,READY:.status.numberReady
kubectl get nodes -o custom-columns=NAME:.metadata.name,TAINTS:.spec.taints[*].key
Field-selector cookbook

Pair with -l when you need both label and field constraints on the same get.

Field-selector cookbook — examples and combined filters
ExampleIntent
kubectl get pods -A --field-selector=status.phase=RunningOnly Running Pods
kubectl get pods -A --field-selector=status.phase=PendingPods stuck scheduling
kubectl get pods -A --field-selector=status.phase=FailedFailed Pods
kubectl get pods -A --field-selector=status.phase=SucceededCompleted Pods
kubectl get pods -A --field-selector=spec.nodeName=my-nodePods bound to a node
kubectl get pods -A --field-selector=spec.restartPolicy=NeverJobs / one-shot style
kubectl get pods -A --field-selector=metadata.namespace=kube-systemObjects in kube-system (with -A)
kubectl get pods -A --field-selector=spec.schedulerName=default-schedulerDefault scheduler assignment
kubectl get pods -n dev --field-selector=status.phase=Running -l app=web
kubectl get pods -A --field-selector=metadata.namespace!=kube-system,status.phase=Running
CLI behavior

Timeouts, verbosity, kubeconfig, admission

Global options & workflows

Frequently used flags, multi-context invocations, RBAC spot checks, and advanced apply patterns.

Global options & workflows — flags, contexts, RBAC, apply patterns
kubectl get pods -v=6
kubectl get pods -v=8 2>&1 | tail -20
kubectl get pods --request-timeout=3s
kubectl get pods --chunk-size=50
kubectl get pods --ignore-not-found
kubectl get pods --show-managed-fields
kubectl apply -f app.yaml --validate=true
kubectl apply -f app.yaml --validate=false
kubectl apply -f app.yaml --force-conflicts --server-side
kubectl apply -f app.yaml --prune -l app=myapp --prune-allowlist=core/v1/ConfigMap
kubectl delete pod demo --wait=false
kubectl delete pod demo --grace-period=0 --force
kubectl get pods --selector='environment in (prod,staging)'
kubectl get pods -o json | jq '.items | length'
kubectl config use-context prod
kubectl --context=staging get nodes
kubectl --kubeconfig=/path/kubeconfig get ns
kubectl options | head -40
kubectl help apply | col -b | head -30
kubectl create namespace tmp-ns --dry-run=client -o yaml | kubectl apply -f -
kubectl run tmp-shell --rm -it --image=busybox:1.36 --restart=Never -- nslookup kubernetes.default
kubectl auth can-i list secrets --as=system:anonymous
kubectl get rolebindings,roles --all-namespaces
kubectl get clusterrolebindings | grep admin
kubectl describe limitrange -n default
kubectl describe quota -n default
kubectl get podsecuritypolicy 2>/dev/null || kubectl get podsecuritystandards 2>/dev/null || true
kubectl get poddisruptionbudget -A
kubectl get resourcequota -A --sort-by=.metadata.namespace
kubectl get events -A --field-selector involvedObject.kind=Pod --sort-by=.lastTimestamp | tail -15
kubectl patch deployment web -p '{"spec":{"progressDeadlineSeconds":600}}'
kubectl scale deploy web --replicas=0
kubectl scale deploy web --replicas=3 --timeout=120s
kubectl wait --for=jsonpath='{.status.readyReplicas}'=3 deployment/web --timeout=180s
kubectl get lease -n kube-system
kubectl get componentstatuses 2>/dev/null || kubectl get --raw /healthz
kubectl config view -o jsonpath='{.users[*].name}'
kubectl config set-context --current --user=admin
kubectl config unset contexts.old
kubectl version --output=yaml
kubectl api-resources --api-group=apps -o wide
kubectl api-resources --verbs=create --namespaced
kubectl explain pod --recursive | head -80
kubectl convert -f old-deploy.yaml --output-version=apps/v1 2>/dev/null || echo 'convert removed in modern kubectl'
kubectl kustomize ./base | kubectl apply -f - --dry-run=client
kubectl apply -f https://example.com/manifest.yaml --dry-run=client
Flags & output matrix

Quick map from flag to behavior — check kubectl options and subcommand -h for authoritative syntax.

Flags & output matrix — full reference table
Flag / formMeaning
-o wideAdds node IP, Pod IP, OS image on nodes, etc.
-o yamlFull object; stable for kubectl apply -f
-o jsonMachine parse; pair with jq
-o jsonpath='{.path}'Template extract; use {range} for loops
-o jsonpath-file=tmplLong templates from disk
-o nameresource/name tuples for xargs
-o custom-columns=...Ad hoc tabular columns from paths
-o go-template=...Go text/template (advanced)
-o templatefile=...Template from file
--show-labelsAppend LABELS column
--show-managed-fieldsInclude managedFields in yaml/json
-l k=vEquality label selector
-l 'k in (a,b)'Set-based inclusion
-l '!k'Require absence of label key
--field-selector=Filter on object fields
--chunk-sizeServer-side list pagination size
--sort-by=.pathLexicographic / numeric sort by JSONPath
--no-headersOmit table header row
-w / --watchStream after initial list
--watch-onlySkip initial list (events)
-A / --all-namespacesList across namespaces
--namespace / -nExplicit namespace scope
--contextOverride kubeconfig context
--kubeconfigAlternate config file path
--request-timeoutClient-side wait for API
--server-print=falseDisable server-side printing (rare)
--ignore-not-foundExit 0 when object missing on delete/get
--validate=trueSchema validation on apply/create
--dry-run=clientLocal-only validation / render
--dry-run=serverAdmission + quota without persist
--forceRecreate on apply conflicts (careful)
--grace-periodSeconds before SIGKILL on delete
--nowForce immediate delete (shorthand)
--cascade=foregroundDelete owners after dependents
--cascade=orphanLeave dependents when deleting owner
--selector alias -lSame as label selector
--pod-running-timeoutWait for Pod running in run/exec
--rm (kubectl run)Auto-delete interactive debug Pod
--restart=NeverPod instead of Deployment for kubectl run
--replicas (create deployment)Initial replica count
--record (deprecated)Avoid; use annotations for change-cause
--output-watch-eventsInclude event types in watch stream
--allow-missing-template-keysTolerate missing template keys
--export (removed)Historically stripped cluster fields; gone in modern kubectl
--rawHTTP GET to API path; bypasses kubectl resource layer
--subresourcestatus/scale/etc. for patch|get
--asImpersonate user for auth can-i / API calls
--as-groupGroup impersonation flag
--tokenBearer token instead of kubeconfig user
--certificate-authorityTrust custom CA bundle
--insecure-skip-tls-verifyInsecure — lab only
--userOverride kubeconfig user for this invocation
--clusterOverride cluster within kubeconfig
--username / --passwordBasic auth to API — rare outside tests
--impersonateOlder alias of --as in some docs
--v=0..9klog verbosity for client transport
--log-flush-frequencyClient log flush interval
--vmodulePer-file verbosity (advanced)
--add-dir-headerPrefix log lines with directory
--skip-log-headersSuppress log header lines
--alsologtostderrMirror logs to stderr
--use-openapi-fetchPrefer OpenAPI fetch path (debug)
--tls-server-nameOverride SNI for TLS to API
--proxy-urlHTTP proxy for API traffic
--append-server-pathAppend path segment to server URL
--disable-compressionTurn off gzip on API responses
--cache-dirOverride discovery/docs cache location
--limit=...Deprecated list limit; prefer --chunk-size
--continueContinue token for paging large lists
--show-kindPrefix resource kind in name column
--label-columnsAdd columns from label keys
--sort-by metadata.uidDeterministic order for fuzzing/tests
--timeout (kubectl wait)Max time to wait for condition
--for=deletekubectl wait until object removed
--for=createWait helper patterns vary by version
--localOperate on manifest without contacting API
--edit-cache-dirCache for kubectl edit
--windows-line-endingsCRLF when editing on Windows
--unix-line-endingsLF endings for edited buffers
--openapi-patchExperimental OpenAPI patch merge (rare)
--validate=falseSkip schema validation on apply
--prune-allowlistRestrict kinds kubectl apply --prune may delete
--pruneDelete objects missing from apply set (dangerous)
--overwriteReplace existing field on annotate/label
--resource-versionOptimistic concurrency on replace
--save-configStore last-applied annotation on create commands
--templateAlias of -o go-template in some contexts
--containersRegex filter for multi-container logs
--prefixPrefix log lines with pod/container name
--timestampsPrefix each log line with timestamp
--since-timeRFC3339 lower bound for logs
--all-containersAggregate logs from every container
--previousPrior terminated container instance logs
--followStream new log lines (-f)
--pod-running-timeoutHow long run waits for Pod Running
--termination-grace-periodOverride Pod deletion grace
--recursive (-R)Apply to directories of manifests
--filename (-f)Manifest path, URL, or stdin (-)
--selector (-l)Synonym for label selector on many commands
--allSelect all resources of a type in namespace
--field-managerSet SSA field manager name on apply
--force-conflictsTake ownership on server-side apply conflicts
--server-sideUse server-side apply merge
kubectl alpha / kubectl betaHidden subcommands — vary by version; prefer stable paths
--timeout (rollout status)How long to wait for rollout completion
--revisionTarget specific ReplicaSet generation in rollout history
--to-revisionUndo to explicit revision number
--max-unavailableRollout flag on kubectl set (where supported)
--max-surgeRollout surge percent on set (where supported)
--historyInclude rollout history in describe (deployment)
--output (alias -o)Same as -o
--labelsSet labels on kubectl create
--annotationsSet annotations on kubectl create
--generator (removed)Legacy run generators — prefer create/run explicit
--scheduleCron expression on kubectl create cronjob
--from-literalKey=value data for secrets/configmaps
--from-fileFile path for secrets/configmaps
--from-env-file.env style file for configmap
--docker-registryCredential helper scope for secrets
--dry-run (alias)Maps to --dry-run=client in newer help text
--shortAbbreviated human output for version
--imageContainer image for kubectl run/create workload
--portContainer port mapping for expose/run helpers
--envKEY=value for kubectl run (imperative)
--commandOverride container entrypoint on kubectl run
--serviceaccountAttach SA on kubectl run (where supported)
--overridesJSON override of generated object fields
--requestsResource requests on kubectl set resources
--limitsResource limits on kubectl set resources
--cascadeforeground/orphan on delete (owner refs)
--ignore-not-found on deleteExit 0 if object absent
--waitBlock until delete completes (where supported)
--timeout on deleteMax wait for object removal
--ignore-dependenciesSkip waiting for dependents on delete
--local (diff)Compare against manifest without server fetch side
--server-side (diff)Include server fields in diff (default shifts by version)
--strip-trailing-whitespaceNormalize whitespace in diff output
--subresource=scalePatch or fetch horizontal scale subresource
--subresource=statusStatus-only patch for supported types
--raw on patchNot typical — prefer resource-aware patch
--type=strategicExplicit default merge type for supported resources
--patch-fileRead patch body from file instead of -p
--stdin -f -Pipe manifest: kubectl apply -f -
kubectl completion SHELLEmit shell completion script
kubectl config viewDump merged kubeconfig
kubectl config use-contextSwitch active context
kubectl config set-clusterAdd or update cluster stanza
kubectl config set-credentialsEmbed certs or token
kubectl config unsetRemove a kubeconfig key path
kubectl version --clientCLI-only version (no server call)
kubectl version -o yamlStructured client+server versions
kubectl plugin listDiscover kubectl-* binaries on PATH
kubectl krew (plugin)Popular plugin manager — third-party
kubectl config get-usersNames in kubeconfig users stanza
kubectl config get-clustersServer URLs stored locally
kubectl config current-contextShow active context string
kubectl config delete-userRemove stale credential blocks
kubectl config delete-clusterRemove cluster stanza
kubectl config set-context NAMEBind cluster+user+namespace
kubectl diff --pruneInclude prune in diff (use with care)
kubectl apply --server-side --force-conflictsTake field ownership during SSA
kubectl get events --types=WarningFilter event type column
kubectl get events --types=NormalOnly non-warning events
kubectl logs --since=5mRelative log window
kubectl logs --tail=-1Entire log buffer (heavy)
Speed & ergonomics

Tips & Aliases

Resource shortnames

Common API resource aliases (verify with kubectl api-resources).

Kind (plural)ShortnamesNote
podspoCore workload unit
servicessvcStable network endpoint
deploymentsdeployReplicaSet owner, rolling updates
replicasetsrsReplica count for a Pod template
daemonsetsdsOne Pod per matching node
statefulsetsstsOrdered Pods with stable identity
configmapscmNon-secret configuration data
secretsSensitive data (no shortname in many clusters)
namespacesnsAPI object scope
nodesnoCluster worker/control-plane machines
ingressesingHTTP/S routing rules
endpointsepLegacy Endpoint objects backing Services
endpointslicesScalable endpoint slices (often no shortname)
persistentvolumespvCluster storage volume
persistentvolumeclaimspvcPod storage request
serviceaccountssaPod identity for API access
cronjobscjTime-based Job templates
jobsRun-to-completion workloads
horizontalpodautoscalershpaScale on metrics
poddisruptionbudgetspdbVoluntary disruption limits
storageclassesscDynamic PV provisioning policy
networkpoliciesnetpolPod network rules
customresourcedefinitionscrd, crdsAPI extensions
replicationcontrollersrcLegacy replicas (prefer Deployment)
limitrangeslimitsDefault/min/max per-namespace limits
resourcequotasquotaNamespace aggregate caps
rolesRBAC namespaced permissions
rolebindingsBind Role/ClusterRole to subjects
clusterrolesCluster-wide permission rules
clusterrolebindingsCluster-wide bindings
priorityclassespcPod scheduling priority
certificatesigningrequestscsrX.509 signing workflow
ingressclassesIngress controller selection
volumeattachmentsCSI volume attach state
csinodesCSI driver registration per node
csidriversCSI driver cluster objects
csistoragecapacitiesCSI capacity reporting
validatingwebhookconfigurationsAdmission webhooks (validate)
mutatingwebhookconfigurationsAdmission webhooks (mutate)
leasesDistributed leader election
eventsevCluster warnings (deprecated alias in 1.x)

Run kubectl api-resources on your cluster for the authoritative list; shortnames can vary slightly by version and CRDs.

Shell aliases

Add to ~/.bashrc or ~/.zshrc and reload the shell.

alias k=kubectl
alias kg='kubectl get'
alias kd='kubectl describe'
alias kl='kubectl logs'
alias kgp='kubectl get pods'
alias kgpa='kubectl get pods -A'
alias kns='kubectl config set-context --current --namespace'
alias kctx='kubectl config use-context'
Tab completion

Bash (bash-completion package) and zsh.

# Bash
source <(kubectl completion bash)
echo 'source <(kubectl completion bash)' >> ~/.bashrc

# Zsh
source <(kubectl completion zsh)
echo 'source <(kubectl completion zsh)' >> ~/.zshrc
KUBE_EDITOR

Controls which program kubectl edit launches.

export KUBE_EDITOR='code --wait'
export KUBE_EDITOR='nano'
KUBE_EDITOR="vim" kubectl edit deploy web
kubectl explain

Built-in OpenAPI field documentation; recurse to discover nested structs.

kubectl explain pod.spec.containers
kubectl explain deployment.spec.template --recursive
kubectl explain ingress.spec.rules.http.paths.pathType
Imperative generators

Materialize YAML without persisting objects — great for GitOps bootstrapping.

kubectl run demo --image=nginx --dry-run=client -o yaml > pod.yaml
kubectl create deployment web --image=nginx:1.25 --replicas=3 --dry-run=client -o yaml
kubectl create job backup --from=cronjob/nightly --dry-run=client -o yaml
kubectl wait

Block until a condition becomes true (scripts and CI).

kubectl wait --for=condition=available deployment/web --timeout=120s
kubectl wait --for=condition=ready pod/mypod --timeout=60s
kubectl wait --for=condition=complete job/migrate --timeout=300s -n app
kubectl cp

Copy files using tar under the hood; container name optional when only one container exists.

kubectl cp ./local.txt mypod:/tmp/remote.txt
kubectl cp mypod:/var/log/app.log ./app.log
kubectl cp -c sidecar mypod:/data/out.bin ./out.bin
kubectl proxy

Local authenticated HTTP proxy to the API server — useful for raw API exploration.

kubectl proxy --port=8001
curl localhost:8001/api/v1/namespaces/default/pods
Deployment history

--record on apply/set is deprecated; prefer explicit annotations.

# Deprecated pattern (older tutorials)
kubectl annotate deployment/web kubernetes.io/change-cause='Set image to 1.26' --overwrite
kubectl rollout history deployment/web
Discovery

Cluster, kubeconfig, plugins

Cluster cookbook

Contexts, credentials, discovery, health endpoints, and version-dependent APIs.

Cluster cookbook — contexts, discovery, health, plugins
kubectl cluster-info
kubectl cluster-info dump --namespaces kube-system --output-directory=/tmp/cinfo
kubectl get --raw /version | jq .
kubectl get --raw /readyz?verbose
kubectl get --raw /livez?verbose
kubectl config current-context
kubectl config view --minify -o jsonpath='{.contexts[0].context.namespace}'
kubectl config rename-context old-name new-name
kubectl config delete-context stale-context
kubectl config unset users.old-user
kubectl config set-credentials lab-user --token=$TOKEN
kubectl plugin list
kubectl options
kubectl completion bash | head -3
kubectl describe ns kube-system | head -40
kubectl get validatingadmissionpolicies 2>/dev/null || true
kubectl get mutatingadmissionpolicies 2>/dev/null || true
kubectl get runtimeclasses 2>/dev/null || true
kubectl get apiservices | grep False
kubectl get crd | wc -l
Mutations

Patching & Editing

kubectl edit

Opens the live object in an editor; saving submits a replace/patch depending on resource. Use when you need interactive exploration.

kubectl edit deployment web
kubectl edit svc frontend -n prod
Strategic merge patch

Default for native types: lists like containers merge by name keys instead of wholesale replacement.

kubectl patch deployment web -p '{"spec":{"template":{"spec":{"containers":[{"name":"web","image":"nginx:1.26"}]}}}}'
kubectl patch deployment web -p '{"metadata":{"labels":{"tier":"frontend"}}}'
JSON merge patch (RFC 7396)

--type=merge replaces entire subtrees you specify; simpler but can clobber nested slices if you omit siblings.

kubectl patch deployment web --type=merge \
  -p '{"spec":{"template":{"spec":{"containers":[{"name":"web","image":"nginx:1.27"}]}}}}'
JSON patch (RFC 6902)

Surgical add, remove, replace, move, copy, test operations in order.

kubectl patch deployment web --type=json \
  -p '[{"op":"add","path":"/metadata/annotations/reviewer","value":"alice"}]'
kubectl patch deployment web --type=json \
  -p '[{"op":"remove","path":"/metadata/annotations/reviewer"}]'
kubectl set

Imperative helpers for common Pod template fields.

kubectl set image deployment/web web=nginx:1.27
kubectl set env deployment/web LOG_LEVEL=debug
kubectl set resources deployment/web -c web --limits=cpu=500m,memory=512Mi
kubectl set serviceaccount deployment/web app-sa
kubectl rollout

Inspect and control Deployment (and similar) revision lifecycle.

kubectl rollout status deployment/web
kubectl rollout history deployment/web
kubectl rollout undo deployment/web
kubectl rollout pause deployment/web
kubectl rollout resume deployment/web
kubectl rollout restart deployment/web
kubectl diff

Compare live state to manifests on disk without applying — requires diff program installed.

kubectl diff -f ./manifests/
KUBECTL_EXTERNAL_DIFF="diff -u" kubectl diff -f web.yaml
--dry-run=client vs server

Client validates schema locally; server validates admission, quotas, and conflicts against etcd.

kubectl apply -f app.yaml --dry-run=client -o yaml
kubectl apply -f app.yaml --dry-run=server
kubectl delete pod demo --dry-run=server
Mutation depth

Patch, set, rollout, and node maintenance

Patching & lifecycle cookbook

Fifty real-world patch, set, rollout, quota, and node maintenance commands.

Patching & lifecycle cookbook — fifty patch, set, and rollout commands
kubectl patch cm app-config --type merge -p '{"data":{"log_level":"debug"}}'
kubectl patch svc web --type=json -p '[{"op":"replace","path":"/spec/type","value":"ClusterIP"}]'
kubectl annotate deployment web deployment.kubernetes.io/revision-
kubectl label pod mypod app-
kubectl label pod mypod app=web --overwrite
kubectl patch deploy web -p '{"spec":{"template":{"metadata":{"annotations":{"kubectl.kubernetes.io/restartedAt":"'$(date -Iseconds)'"}}}}}'
kubectl rollout restart deployment/web
kubectl set probes deployment/web --liveness=exec -- bash -c true --period-seconds=10 2>/dev/null || kubectl explain deploy.spec.template.spec.containers.livenessProbe
kubectl edit deploy web --windows-line-endings=false
kubectl apply --server-side --field-manager=my-controller -f svc.yaml
kubectl replace -f pod-static.yaml --force --grace-period=0
kubectl patch pvc data --type=json -p '[{"op":"add","path":"/metadata/annotations/pv.kubernetes.io~1bind-completed","value":"true"}]' 2>/dev/null || true
kubectl patch hpa web --patch '{"spec":{"maxReplicas":20}}'
kubectl patch sts redis --type='merge' -p '{"spec":{"updateStrategy":{"type":"RollingUpdate"}}}'
kubectl patch cronjob backup --patch '{"spec":{"suspend":true}}'
kubectl patch job run-once --type=json -p '[{"op":"replace","path":"/spec/suspend","value":true}]' 2>/dev/null || true
kubectl patch networkpolicy deny-all -p '{"spec":{"podSelector":{}}}'
kubectl patch secret tls-cert --type=merge -p '{"stringData":{"tls.crt":"'"$(cat tls.crt)"'"}}' 2>/dev/null || true
kubectl diff -R -f ./manifests/
kubectl apply -f ./manifests/ --server-side --force-conflicts
kubectl apply -f pod.json --dry-run=client -o yaml | kubectl apply -f -
kubectl create deploy web --image=nginx --dry-run=client -o yaml | kubectl apply -f -
kubectl set resources deployment web -c web --requests=cpu=100m,memory=128Mi --limits=cpu=500m,memory=256Mi
kubectl set image deployment/web '*=nginx:1.27'
kubectl set env deployment/web FEATURE_FLAG=on --from=configmap/app-config --keys=log_level
kubectl set serviceaccount deployment/web sa-apps
kubectl patch deploy web --subresource=status --type=merge -p '{"status":{"conditions":[]}}' 2>/dev/null || true
kubectl wait --for=delete pod/old-pod --timeout=60s
kubectl delete pod -l app=web --field-selector=status.phase!=Running
kubectl patch node worker-1 -p '{"spec":{"unschedulable":true}}'
kubectl patch node worker-1 -p '{"spec":{"unschedulable":false}}'
kubectl cordon worker-1 && kubectl drain worker-1 --ignore-daemonsets --delete-emptydir-data
kubectl taint nodes worker-1 dedicated=team-a:NoSchedule
kubectl taint nodes worker-1 dedicated-
kubectl patch validatingwebhookconfigurations admission --type=json -p='[]' 2>/dev/null || true
kubectl get deploy web -o yaml | kubectl apply -f - --server-side
kubectl create cm patch-demo --from-literal=key=value --dry-run=client -o yaml | kubectl apply -f -
kubectl patch cm patch-demo --type merge -p '{"data":{"key":"new"}}'
kubectl delete cm patch-demo --ignore-not-found
kubectl patch deploy web --type=json -p '[{"op":"test","path":"/spec/replicas","value":3},{"op":"replace","path":"/spec/replicas","value":5}]' 2>/dev/null || true
kubectl rollout history deploy/web --revision=3
kubectl rollout undo deploy/web --to-revision=2
kubectl set image deployment/web web=nginx:bad && kubectl rollout undo deployment/web
kubectl patch deploy web -p '{"spec":{"strategy":{"type":"Recreate"}}}'
kubectl patch deploy web -p '{"spec":{"strategy":{"type":"RollingUpdate","rollingUpdate":{"maxSurge":"25%","maxUnavailable":"25%"}}}}'
Observability

Debugging

kubectl logs

Stream or slice container logs; multi-container Pods need -c.

kubectl logs deploy/web --tail=100
kubectl logs -f pod/mypod -c app
kubectl logs pod/mypod --previous
kubectl logs -l app=web --tail=50 --since=10m
kubectl logs pod/mypod --all-containers=true
kubectl exec

Run commands in a container; use -- before flags meant for the remote process.

kubectl exec -it mypod -- bash
kubectl exec mypod -c sidecar -- ls /var/log
kubectl exec deploy/web -- printenv | grep DB_
kubectl debug

Ephemeral debug containers (feature-gated on older clusters) or clone Pods for deeper inspection.

kubectl debug mypod -it --image=busybox:1.36 --target=app -- sh
kubectl debug mypod -it --copy-to=mypod-debug --image=nicolaka/netshoot -- sh
kubectl delete pod mypod-debug
kubectl port-forward

Targets resolve to a backing Pod even when you name a Service or Deployment.

kubectl port-forward pod/mypod 8080:80
kubectl port-forward svc/web 8080:80
kubectl port-forward deploy/web 8443:443
kubectl auth can-i

Self-service RBAC checks; impersonate other identities to validate least privilege.

kubectl auth can-i create deployments --namespace=dev
kubectl auth can-i '*' '*' --all-namespaces
kubectl auth can-i create pods --as=system:serviceaccount:dev:builder
kubectl auth can-i --list --namespace=prod
kubectl get events

Correlate timestamps with Pod transitions; combine sort and field filters.

kubectl get events -n app --sort-by=.lastTimestamp
kubectl get events -A --field-selector involvedObject.name=mypod
kubectl get events --watch
kubectl describe

Read bottom-up: Events (recent warnings), Conditions (Scheduled, Ready, …), then Spec vs Status deltas.

kubectl describe pod failing-pod
kubectl describe node worker-2
One-liners

More debugging recipes

Logs, exec, events, port-forward, auth

Fifteen high-signal commands to keep in your shell history.

More debugging recipes — fifteen high-signal commands
kubectl logs -f deploy/web --since-time='2026-04-01T12:00:00Z'
kubectl logs pod/mypod -c init --tail=20
kubectl logs -l app=web --prefix=true --tail=50
kubectl logs daemonset/fluent-bit -n logging --tail=100
kubectl exec -it sts/redis-0 -- redis-cli ping
kubectl exec deploy/api -- wget -qO- http://127.0.0.1:8080/ready
kubectl run netshoot --image=nicolaka/netshoot --rm -it --restart=Never -- bash
kubectl get pod mypod -o jsonpath='{.status.containerStatuses[*].state.waiting.message}'
kubectl describe pod mypod | sed -n '/Events/,$p'
kubectl get events --field-selector reason=FailedScheduling
kubectl get events --field-selector type=Warning -A | tail -20
kubectl port-forward svc/prometheus 9090:9090 -n monitoring
kubectl auth can-i get secret --namespace kube-system
kubectl auth can-i use podsecuritypolicies --as=system:serviceaccount:default:default
kubectl proxy --port=0 &

Troubleshooting checklist

1

Scope

Confirm context and namespace: kubectl config current-context, kubectl config view --minify.

2

Locate

kubectl get pods -n NAMESPACE -o wide — note node, restarts, readiness.

3

Describe

kubectl describe pod POD — scan Events and Conditions for scheduling, image pull, probe failures.

4

Logs

kubectl logs POD with --previous if CrashLoopBackOff; add -c for multi-container Pods.

5

Exec / debug

kubectl exec for quick checks; kubectl debug when the container filesystem is minimal or crashing instantly.

6

Network

kubectl port-forward or in-cluster probes; verify Service selectors match Pod labels.

7

RBAC & policy

kubectl auth can-i, NetworkPolicies, quotas — especially when “works for admin, fails for dev”.

Troubleshooting matrix

Seventy copy-ready pairings of intent and command — align with Lab 54 for full drills.

Troubleshooting matrix — seventy scenario and command pairings
ScenarioCommand
API endpoint sanitykubectl cluster-info
Dump kube-system statekubectl -n kube-system get pods -o wide
CoreDNS podskubectl -n kube-system get pods -l k8s-app=kube-dns
API server pods (kubeadm)kubectl -n kube-system get pods -l component=kube-apiserver
Scheduler podskubectl -n kube-system get pods -l component=kube-scheduler
Controller managerkubectl -n kube-system get pods -l component=kube-controller-manager
etcd member podskubectl -n kube-system get pods -l component=etcd
Pending Pods cluster-widekubectl get pods -A --field-selector=status.phase=Pending
Image pull errorskubectl get pods -A | grep -i imagepull || true
CrashLoop podskubectl get pods -A | grep CrashLoop || true
OOMKilled searchkubectl get pods -A -o jsonpath='{range .items[?(@.status.containerStatuses[*].lastState.terminated.reason=="OOMKilled")]}{.metadata.namespace}/{.metadata.name}{"\n"}{end}'
Node NotReadykubectl get nodes | grep NotReady || true
Node describe pressurekubectl describe node $(kubectl get nodes -o jsonpath='{.items[0].metadata.name}') | sed -n '/Conditions/,$p'
Kubelet version skewkubectl get nodes -o custom-columns=NAME:.metadata.name,VER:.status.nodeInfo.kubeletVersion
Service endpoints emptykubectl get endpoints -A | grep '<none>' | head
EndpointSliceskubectl get endpointslices -A | head -20
Ingress controllerkubectl get pods -A | grep -i ingress
NetworkPolicy countkubectl get networkpolicy -A --no-headers 2>/dev/null | wc -l
DNS from a Podkubectl run dnstest --image=busybox:1.36 --rm -it --restart=Never -- nslookup kubernetes.default
Service ClusterIP reachabilitykubectl run curltest --image=curlimages/curl --rm -it --restart=Never -- curl -sS -m 2 http://web.default.svc.cluster.local || true
PV stuck Releasedkubectl get pv | grep Released || true
PVC Pendingkubectl get pvc -A | grep Pending || true
StorageClass listkubectl get storageclass
VolumeAttachmentskubectl get volumeattachment
CSINode statuskubectl get csinodes -o wide
RBAC: who can delete nodeskubectl auth can-i delete nodes
RBAC: list cluster-admin bindingskubectl get clusterrolebindings | grep cluster-admin
ServiceAccount tokens (legacy)kubectl get secrets -n default | grep default-token || true
Validating webhookskubectl get validatingwebhookconfigurations
Mutating webhookskubectl get mutatingwebhookconfigurations
APIService availabilitykubectl get apiservices | grep False | head
CRD countkubectl get crd | wc -l
Events for a Podkubectl get events --field-selector involvedObject.kind=Pod --sort-by=.lastTimestamp
FailedScheduling detailkubectl describe pod PODNAME | sed -n '/Events/,$p'
ReplicaSet owned by Deploymentkubectl get rs -l app=web
Rollout stuckkubectl rollout status deployment/web --timeout=5s
Previous ReplicaSetkubectl rollout history deployment/web
Undo bad rolloutkubectl rollout undo deployment/web
HPA statuskubectl get hpa -A
Metrics server podskubectl -n kube-system get pods | grep metrics-server
PDB blocking drainskubectl get pdb -A
Jobs not completingkubectl get jobs -A | grep -v '1/1' | head
CronJob last schedulekubectl get cronjobs -A -o custom-columns=NS:.metadata.namespace,NAME:.metadata.name,SCHEDULE:.spec.schedule,SUSPEND:.spec.suspend
ResourceQuota usagekubectl describe resourcequota -n NAMESPACE
LimitRange defaultskubectl describe limitrange -n NAMESPACE
Taints on nodeskubectl get nodes -o custom-columns=NAME:.metadata.name,TAINTS:.spec.taints[*].effect
Cordon all before maintenancekubectl get nodes -o name | xargs -I {} kubectl cordon {}
Pod logs all containerskubectl logs POD --all-containers=true --tail=50
Stream multiple pods by labelkubectl logs -f -l app=web --max-log-requests=10 --tail=20
Copy kubelet logs hintkubectl get nodes -o wide # then SSH/journalctl on node for kubelet
Ephemeral debug shellkubectl debug POD -it --image=busybox:1.36 --target=CONTAINER -- sh
Network policy deny-all checkkubectl get netpol -n NAMESPACE -o yaml | head -40
Service type and portskubectl get svc -A -o wide | head -30
Headless service checkkubectl get svc -A | grep None | head
NodePort rangekubectl get svc -A | grep NodePort | head
LoadBalancer stuckkubectl describe svc SVC | sed -n '/Events/,$p'
Certificate expiry (secret)kubectl get secret TLS_SECRET -o yaml | grep 'tls.crt' | head -1
CSR pendingkubectl get csr | grep Pending || true
PriorityClasskubectl get priorityclass
RuntimeClasskubectl get runtimeclass 2>/dev/null || true
Pod Security labels (PSS)kubectl get ns NAMESPACE --show-labels
Finalizers blocking deletekubectl get pod POD -o jsonpath='{.metadata.finalizers}'
Owner referenceskubectl get pod POD -o jsonpath='{.metadata.ownerReferences[*].kind}{" "}{.metadata.ownerReferences[*].name}{"\n"}'
Last applied configurationkubectl get deploy web -o yaml | grep last-applied-configuration -A1 | head -3
Server-side apply managerskubectl get deploy web -o jsonpath='{.metadata.managedFields[*].manager}{"\n"}' | sort -u
Proxy to APIkubectl proxy --port=8001 # then: curl -s localhost:8001/version
Raw healthkubectl get --raw /readyz?verbose | head -20
Component status legacykubectl get componentstatuses 2>/dev/null || echo 'removed in newer releases'
List all resources in namespacekubectl api-resources --verbs=list --namespaced -o name | xargs -n1 kubectl get -n NAMESPACE --show-kind --ignore-not-found 2>/dev/null | head -50
Watch nodes while scalingkubectl get nodes -w
Top pods after loadkubectl top pods -A | head -20
Describe ingress ruleskubectl describe ing -n NAMESPACE
Gateway API (if installed)kubectl get gateway,httproute -A 2>/dev/null | head
Pod prioritykubectl get pods -A -o custom-columns=NAME:.metadata.name,PRIO:.spec.priorityClassName
Eviction dry runkubectl drain NODE --dry-run=server
Force delete stuck terminating podkubectl delete pod POD --grace-period=0 --force
TTL on finished jobskubectl get jobs -A -o custom-columns=NAME:.metadata.name,TTL:.spec.ttlSecondsAfterFinished | head
StatefulSet ordered podskubectl get pods -l app=sts -o wide
DaemonSet miss-scheduledkubectl get ds -A | grep -v 'DESIRED' | awk '$3!=$4 {print}' | head
Replica count mismatchkubectl get deploy -A -o custom-columns=NS:.metadata.namespace,N:.metadata.name,WANT:.spec.replicas,READY:.status.readyReplicas | awk '$3!=$4 {print}' | head
Hands-on

Practice

Exercise 1

JSONPath output: Deploy sample workloads, print ClusterIP, tab-separated pod name/IP/node, all container images, and filter Ready nodes by condition.

Exercise 2

Custom columns: Build tables for Pods (name, IP, node, phase), Deployments (image, desired vs ready replicas), and Nodes (capacity vs allocatable CPU/memory).

Exercise 3

Patching: Apply strategic merge labels, bump images with JSON merge patch, add annotations via JSON patch, and change a Service type with a strategic patch.

Exercise 4

Field selectors & sort: List Running pods cluster-wide, list Pods scheduled to a chosen node, combine label + field filters, sort by creation time and node CPU capacity.

Exercise 5

diff & dry-run: Author a manifest, preview with kubectl diff, validate using --dry-run=server, then apply with server-side apply and watch rollout.

Exercise 6

debug & auth: Attach an ephemeral debug container with --target, clone a Pod with --copy-to, and verify permissions via kubectl auth can-i including --as impersonation.

Lab alignment

Lab 62 paste buffer

Commands from Lab 62

Run in order with the lab manual for explanations, verification steps, and cleanup.

Commands from Lab 62 — full sequence
kubectl create namespace lab62
kubectl -n lab62 create deployment web --image=nginx:1.25 --replicas=3
kubectl -n lab62 expose deployment web --port=80 --type=ClusterIP
kubectl -n lab62 wait --for=condition=available deployment/web --timeout=60s
kubectl -n lab62 get svc web -o jsonpath='{.spec.clusterIP}'
kubectl -n lab62 get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.podIP}{"\t"}{.spec.nodeName}{"\n"}{end}'
kubectl -n lab62 get pods -o jsonpath='{.items[*].spec.containers[*].image}'
kubectl get nodes -o jsonpath='{.items[?(@.status.conditions[-1].type=="Ready")].metadata.name}'
kubectl -n lab62 get pods -o custom-columns=NAME:.metadata.name,IP:.status.podIP,NODE:.spec.nodeName,STATUS:.status.phase
kubectl -n lab62 get deployments -o custom-columns=NAME:.metadata.name,IMAGE:.spec.template.spec.containers[0].image,DESIRED:.spec.replicas,READY:.status.readyReplicas
kubectl get nodes -o custom-columns=NODE:.metadata.name,CPU_CAP:.status.capacity.cpu,MEM_CAP:.status.capacity.memory,CPU_ALLOC:.status.allocatable.cpu,MEM_ALLOC:.status.allocatable.memory
kubectl -n lab62 patch deployment web -p '{"metadata":{"labels":{"tier":"frontend"}}}'
kubectl -n lab62 get deployment web --show-labels
kubectl -n lab62 patch deployment web --type=merge -p '{"spec":{"template":{"spec":{"containers":[{"name":"nginx","image":"nginx:1.26"}]}}}}'
kubectl -n lab62 rollout status deployment/web
kubectl -n lab62 patch deployment web --type=json -p '[{"op":"add","path":"/metadata/annotations/patched-by","value":"lab62"}]'
kubectl -n lab62 get deployment web -o jsonpath='{.metadata.annotations.patched-by}'
kubectl -n lab62 patch svc web -p '{"spec":{"type":"NodePort"}}'
kubectl -n lab62 get svc web
kubectl get pods -A --field-selector=status.phase=Running | head -20
NODE=$(kubectl get nodes -o jsonpath='{.items[0].metadata.name}')
kubectl get pods -A --field-selector spec.nodeName=$NODE
kubectl -n lab62 get pods --field-selector=status.phase=Running -l app=web
kubectl -n lab62 get pods --sort-by=.metadata.creationTimestamp
kubectl get nodes --sort-by=.status.capacity.cpu
kubectl diff -f /tmp/lab62-web.yaml
kubectl apply -f /tmp/lab62-web.yaml --dry-run=server
kubectl apply -f /tmp/lab62-web.yaml --server-side
POD=$(kubectl -n lab62 get pods -l app=web -o jsonpath='{.items[0].metadata.name}')
kubectl -n lab62 debug $POD -it --image=busybox:1.36 --target=nginx -- sh
kubectl -n lab62 debug $POD -it --copy-to=debug-copy --image=busybox:1.36 -- sh
kubectl -n lab62 delete pod debug-copy
kubectl auth can-i create deployments -n lab62
kubectl auth can-i delete nodes
kubectl auth can-i '*' '*' --all-namespaces
kubectl auth can-i get pods -n lab62 --as=system:serviceaccount:lab62:default
kubectl auth can-i create deployments -n lab62 --as=system:serviceaccount:lab62:default
kubectl delete namespace lab62
rm -f /tmp/lab62-web.yaml
Commands from Lab 03

Core create → inspect → expose → scale → delete flow; substitute real pod names where noted.

Commands from Lab 03 — full sequence
kubectl create deployment hello --image=nginx:1.25
kubectl get deployments.apps
kubectl get pods -l app=hello
kubectl describe deployment hello
kubectl scale deployment/hello --replicas=3
kubectl get pods -o wide
kubectl expose deployment hello --port=80 --type=ClusterIP
kubectl get svc hello
kubectl port-forward svc/hello 8080:80
kubectl logs deploy/hello --tail=20
kubectl logs deploy/hello -f
kubectl exec -it deploy/hello -- nginx -v
kubectl delete svc hello
kubectl delete deployment hello
kubectl create namespace lab03-demo
kubectl -n lab03-demo run tmp --image=busybox:1.36 --restart=Never -- sleep 3600
kubectl -n lab03-demo get pods
kubectl -n lab03-demo describe pod tmp
kubectl -n lab03-demo delete pod tmp --force --grace-period=0
kubectl delete namespace lab03-demo
kubectl get all
kubectl get all -n kube-system | head
kubectl cluster-info
kubectl get nodes
kubectl version --short
kubectl config get-contexts
kubectl get events --sort-by=.metadata.creationTimestamp | tail -15
kubectl rollout status deployment/hello
kubectl set image deployment/hello hello=nginx:1.26
kubectl rollout undo deployment/hello
kubectl get rs -l app=hello
kubectl cp /etc/hosts hello-pod:/tmp/hosts 2>/dev/null || echo 'replace hello-pod name'
kubectl wait --for=condition=ready pod -l app=hello --timeout=90s
kubectl get pods --show-labels
kubectl label pod PODNAME color=blue
kubectl annotate pod PODNAME note=lab03
kubectl top pods 2>/dev/null || echo 'install metrics-server'
kubectl api-resources | head -25
kubectl explain pod.spec
kubectl run shell --rm -it --image=busybox:1.36 --restart=Never -- sh

Structured labs in this repository:

For complete step-by-step instructions, see Lab 62: Advanced kubectl Patterns (k8s/labmanuals/lab62-basics-kubectl-advanced.md) — this page is a quick reference companion.

Tip: keep this page beside your terminal — each pre block is plain text you can copy. Swap in your namespaces, object names, and file paths; double-check deletes on shared clusters.