This kubectl cheat sheet is the page to keep open throughout the Kubernetes course. It sums up on a single page the syntax of kubectl, its global options, the everyday command patterns and the classic pitfalls, with the real error messages of Kubernetes 1.37. It comes at the end of the module "Basic resources", right after Namespaces: you now know Pods, Deployments, Services and namespaces, and you have typed enough commands for a recap to be useful. This lesson stays optional in the course: it replays gestures already seen, and demonstrates a few that other lessons teach later (drain, auth can-i, diff). Each command points back to the lesson where it is really learned.
What you will learn
This page does not teach you a new resource: it gives you the landmarks to find the right command quickly, and to avoid the mistakes that hit the wrong cluster or the wrong namespace. By the end, you will be able to:
- read a
kubectlcommand by separating the verb, the type, the name and the options; - find the global option or the command pattern that fits a need;
- extract a precise field with JSONPath or
custom-columns; - recognize the common pitfalls and their error message in Kubernetes 1.37.
How do you read a kubectl command?
Every kubectl command follows the same order: a verb, a resource type, an optional name, then options. Each command becomes a request to the API Server of the cluster, the component that receives and validates all requests. Remembering this skeleton saves you from wondering in which order to write the arguments.
kubectl [VERBE] [TYPE] [NOM] [OPTIONS]The block above is a syntax template, not a command to type: the brackets mark the parts to replace. Here is a real command, with the verb get, the type pods and two options. The k-hub namespace does not exist yet, but kubectl does not report a nonexistent namespace: it simply answers No resources found, as for an empty namespace.
kubectl get pods -n k-hub -o wideNo resources found in k-hub namespace.The following table breaks down the command kubectl get pods -n k-hub -o wide (the name of a Pod is generated by Kubernetes, hence its placeholder <nom-d-un-pod>). Read the Mandatory column: only the verb always is, the type almost always is, and the absence of a name widens the command to all the resources of the type in the targeted namespace.
| Part | Question | Examples | Mandatory |
|---|---|---|---|
| Verb | Which action? | get, describe, apply, delete, logs | Yes |
| Type | On which type of resource? | pod, deployment, service, node | Yes, except global commands such as version |
| Name | Which specific resource? | web, <nom-d-un-pod> | No: without a name, all the resources of the type |
| Options | With which parameters? | -n k-hub, -o wide, -l app=web | No |
Types accept a short form: po for pods, deploy for deployments, svc for services, ns for namespaces, cm for configmaps. A resource can also be designated in the form type/name, such as deploy/web or pod/<nom-d-un-pod>: it is the form that logs, exec and rollout accept, and it removes any ambiguity about what is targeted.
One last separator matters: the double dash --. Everything that follows it belongs to the command run in the container, and no longer to kubectl. It is mandatory with exec, as the section on pitfalls shows.
Which global options should you remember?
A dozen options are enough day to day, and they combine with almost all verbs. Two deserve a beginner's attention: -n, whose omission often gives an empty result (without it, kubectl queries the default namespace of the context, often default), and --dry-run=client -o yaml, which generates a manifest without creating anything. Also note the difference between -l, which filters on the labels you set, and --field-selector, which filters on the fields that Kubernetes fills in, such as the phase of a Pod.
| Option | Effect | Example |
|---|---|---|
-n NS | Target a namespace | kubectl get pods -n kube-system |
-A | All namespaces | kubectl get pods -A |
-o wide | Extra columns (IP, node) | kubectl get pods -o wide |
-o yaml or -o json | The complete object | kubectl get deploy web -o yaml |
-o name | Only type/name, handy in scripts | kubectl get pods -o name |
-o jsonpath=... | A specific field | see the JSONPath section |
-o custom-columns=... | Your own columns | see the JSONPath section |
-l key=value | Filter by label | kubectl get pods -l app=web |
--field-selector | Filter on a field of the object | --field-selector=status.phase!=Running |
--sort-by | Sort the output | --sort-by=.metadata.creationTimestamp |
-w | Follow changes live | kubectl get pods -w |
--dry-run=client -o yaml | Print the YAML without creating anything | see "Generate a manifest" |
--context CTX | Target another context for this command | kubectl --context=staging get pods |
--kubeconfig FILE | Read another kubeconfig file | kubectl --kubeconfig=/tmp/admin.conf get nodes |
The last two lines are often mistaken for a lasting change. --context and --kubeconfig only apply to the command that carries them: your active context stays the same afterwards. This is why they are preferred in production, where a forgotten context switch makes the next command hit the wrong cluster.
Where is each gesture learned in the course?
This cheat sheet sums up, it does not teach: each family of commands has its lesson, with its explanations, its commented outputs and its quiz. The table says where to find it and in which module of the course it sits. Lessons from the later modules are normal at this stage: you will meet them further along in the course outline, and the cheat sheet will still serve you then.
| Commands | Lesson | Module |
|---|---|---|
config, contexts, kubeconfig | Kubeconfig and contexts | Fundamentals |
get, describe, logs, top | Get information on resources | Fundamentals |
label, annotate | Labels and annotations | Basic resources |
expose, port-forward, proxy | Reach an application | Basic resources |
rollout, set, scale | Rolling updates and rollbacks | Basic resources |
api-resources, explain | Explore the API | Deploy your applications |
create, apply | Create and apply | Deploy your applications |
diff, wait | Preview and wait (optional) | Deploy your applications |
exec, debug, cp | Debug an application | Deploy your applications |
autoscale | Horizontal Pod scaling | Scheduling and capacity |
auth can-i | RBAC | Workload security |
edit, patch, replace | Modify a resource in place (in French) | Day-to-day operations |
cordon, drain, taint | Prepare a maintenance (in French) and Manage nodes (in French) | Day-to-day operations |
Installing kubectl, with autocompletion and the k alias, is the lesson install and configure kubectl of the Fundamentals module. One topic stays outside the course, as a tutorial: extending kubectl with plugins (in French) with the Krew manager, to tackle once the basic commands are mastered.
Which command patterns should you keep at hand?
A command pattern is a formula to copy while changing the names. The ones below cover common situations, sorted by intention: find your bearings, read, produce YAML, deploy, get into a container, act on a node, check a permission. They are played in order on the demo cluster, with a k-hub namespace and a web Deployment that the first sections create.
Find your bearings before acting
The first command of a session is always config current-context. The context is the entry of the kubeconfig file that associates a cluster, a user and a default namespace. Checking the context before any write avoids a costly mistake: modifying production while believing you are on a test cluster. After the reads, the sequence creates the k-hub namespace and makes it the default namespace of the context.
kubectl config current-contextkubectl config get-contextskubectl config use-context kind-demokubectl create namespace k-hubkubectl config set-context --current --namespace=k-hubkind-demoCURRENT NAME CLUSTER AUTHINFO NAMESPACE* kind-demo kind-demo kind-demoSwitched to context "kind-demo".namespace/k-hub createdContext "kind-demo" modified.The outputs confirm each gesture: the active context is kind-demo (the star of get-contexts marks it, and its NAMESPACE column is empty as long as no default namespace is set), then Context "kind-demo" modified. after the namespace change.
The third line changes the active cluster for all the following commands (here, it goes back to the same context); the fifth sets the default namespace of the current context, which saves you from repeating -n. These two gestures modify your ~/.kube/config file on the workstation, without changing anything in the cluster. For the rest, the commands still keep -n k-hub, which does not depend on this setting.
Generate a manifest without creating anything
--dry-run=client -o yaml turns an imperative command into a YAML generator. The client builds the object and prints it, without sending it to the cluster: you get a manifest skeleton to complete and then version. The commands below write the manifest of the web Deployment into deploy.yaml, then apply it to create it:
kubectl create deployment web -n k-hub \ --image=nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb \ --replicas=2 --dry-run=client -o yaml > deploy.yamlhead -n 12 deploy.yamlkubectl apply -f deploy.yamlkubectl rollout status deployment/web -n k-hubapiVersion: apps/v1kind: Deploymentmetadata: labels: app: web name: web namespace: k-hubspec: replicas: 2 selector: matchLabels: app: webdeployment.apps/web createdWaiting for deployment "web" rollout to finish: 0 out of 2 new replicas have been updated...Waiting for deployment "web" rollout to finish: 0 of 2 updated replicas are available...Waiting for deployment "web" rollout to finish: 1 of 2 updated replicas are available...deployment "web" successfully rolled outThe output of head shows the beginning of the manifest: the label app: web, the k-hub namespace and replicas: 2. Nothing exists in the cluster until kubectl apply has applied the file.
The same suffix works with kubectl run for a Pod and with kubectl expose for a Service. The name and --image are mandatory for create deployment: without an image, kubectl stops on error: required flag(s) "image" not set.
Read the state of a namespace
To see a whole namespace, list the types explicitly, because get all forgets some (see the pitfalls). Then, the order for reading a problem stays the same: the state in get, the Events in describe, then the container logs, bounded in time. Pod names are generated by Kubernetes: the POD variable keeps the name of the first Pod of web.
kubectl expose deployment web -n k-hub --port=80POD=$(kubectl get pods -n k-hub -l app=web -o name | head -n 1)kubectl get deploy,rs,po,svc,cm,secret -n k-hubkubectl describe "$POD" -n k-hub | tail -n 12kubectl logs deploy/web -n k-hub --since=10m --tail=20kubectl get events -n k-hub --sort-by=.metadata.creationTimestampservice/web exposedNAME READY UP-TO-DATE AVAILABLE AGEdeployment.apps/web 2/2 2 2 13s
NAME DESIRED CURRENT READY AGEreplicaset.apps/web-5f9ccb876d 2 2 2 13s
NAME READY STATUS RESTARTS AGEpod/web-5f9ccb876d-55cds 1/1 Running 0 13spod/web-5f9ccb876d-ddqw4 1/1 Running 0 13s
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGEservice/web ClusterIP 10.96.232.212 <none> 80/TCP 0s
NAME DATA AGEconfigmap/kube-root-ca.crt 1 13sQoS Class: BestEffortNode-Selectors: <none>Tolerations: node.kubernetes.io/not-ready:NoExecute op=Exists for 300s node.kubernetes.io/unreachable:NoExecute op=Exists for 300sEvents: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Scheduled 13s default-scheduler Successfully assigned k-hub/web-5f9ccb876d-55cds to demo-worker3 Normal Pulling 12s kubelet spec.containers{nginx}: Pulling image "nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb" Normal Pulled 0s kubelet spec.containers{nginx}: Successfully pulled image "nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb" in 11.668s (11.668s including waiting). Image size: 63638242 bytes. Normal Created 0s kubelet spec.containers{nginx}: Container created Normal Started 0s kubelet spec.containers{nginx}: Container startedFound 2 pods, using pod/web-5f9ccb876d-ddqw4/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d//docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf/docker-entrypoint.sh: Sourcing /docker-entrypoint.d/15-local-resolvers.envsh/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh/docker-entrypoint.sh: Configuration complete; ready for start up2026/11/11 08:08:06 [notice] 1#1: using the "epoll" event method2026/11/11 08:08:06 [notice] 1#1: nginx/1.30.52026/11/11 08:08:06 [notice] 1#1: built by gcc 14.2.0 (Debian 14.2.0-19)2026/11/11 08:08:06 [notice] 1#1: OS: Linux 6.12.116+deb13-amd642026/11/11 08:08:06 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1073741816:10737418162026/11/11 08:08:06 [notice] 1#1: start worker processes2026/11/11 08:08:06 [notice] 1#1: start worker process 362026/11/11 08:08:06 [notice] 1#1: start worker process 37LAST SEEN TYPE REASON OBJECT MESSAGE13s Normal Scheduled pod/web-5f9ccb876d-55cds Successfully assigned k-hub/web-5f9ccb876d-55cds to demo-worker313s Normal ScalingReplicaSet deployment/web Scaled up replica set web-5f9ccb876d from 0 to 213s Normal SuccessfulCreate replicaset/web-5f9ccb876d Created pod: web-5f9ccb876d-55cds13s Normal SuccessfulCreate replicaset/web-5f9ccb876d Created pod: web-5f9ccb876d-ddqw413s Normal Scheduled pod/web-5f9ccb876d-ddqw4 Successfully assigned k-hub/web-5f9ccb876d-ddqw4 to demo-worker212s Normal Pulling pod/web-5f9ccb876d-55cds Pulling image "nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb"12s Normal Pulling pod/web-5f9ccb876d-ddqw4 Pulling image "nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb"2s Normal Started pod/web-5f9ccb876d-ddqw4 Container started2s Normal Created pod/web-5f9ccb876d-ddqw4 Container created2s Normal Pulled pod/web-5f9ccb876d-ddqw4 Successfully pulled image "nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb" in 9.716s (9.716s including waiting). Image size: 63638242 bytes.0s Normal Started pod/web-5f9ccb876d-55cds Container started0s Normal Created pod/web-5f9ccb876d-55cds Container created0s Normal Pulled pod/web-5f9ccb876d-55cds Successfully pulled image "nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb" in 11.668s (11.668s including waiting). Image size: 63638242 bytes.In the output of get, the web Deployment is at 2/2, with its ReplicaSet and its two Running Pods; the list shows no Secret and a single ConfigMap, kube-root-ca.crt. The Events section of describe tells the life of the Pod: Scheduled (the chosen node), Pulling then Pulled (the image fetched), Created and Started. The logs are not empty, because Nginx writes its startup messages, and their first line, Found 2 pods, using pod/…, says that kubectl chose only one of the two Pods when targeting deploy/web. Finally, the Events of the namespace, sorted by date, gather those of the Pods, the ReplicaSet and the Deployment.
The --previous option of kubectl logs shows the logs of the previous container, the one that just crashed: this is where the cause of a CrashLoopBackOff is found. It fails on a Pod that has never restarted. For a Service that does not answer, kubectl describe svc web -n k-hub shows the Endpoints line: if it is empty, two causes are possible, a selector that matches the labels of no Pod, or selected Pods that are not ready. The lesson Services shows how to tell them apart.
Deploy and follow an update
A manual deployment takes three commands, plus a fourth in case of trouble. The diff serves as a safeguard before writing, then rollout status blocks until the new Pods are ready: without it, you get control back while the deployment is still in progress, and an ImagePullBackOff that occurs ten seconds later goes unnoticed. rollout undo goes back to the previous revision. To have a difference to see, the first command changes the image version in deploy.yaml, from 1.30.5 to 1.30.6:
sed -i 's|nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb|nginx:1.30.6@sha256:42c68eab6f7e22611786a9fe1d1c019e275c50185bd54b8f75dc2b9184322703|' deploy.yamlkubectl diff -f deploy.yaml; echo "code de sortie du diff : $?"kubectl apply -f deploy.yamlkubectl rollout status deployment/web -n k-hub --timeout=120skubectl rollout undo deployment/web -n k-hubkubectl rollout status deployment/web -n k-hub --timeout=120skubectl get deployment web -n k-hub -o jsonpath='{.spec.template.spec.containers[0].image}{"\n"}'diff -u -N /tmp/LIVE-1042102036/apps.v1.Deployment.k-hub.web /tmp/MERGED-1142049178/apps.v1.Deployment.k-hub.web--- /tmp/LIVE-1042102036/apps.v1.Deployment.k-hub.web 2026-11-11 08:08:08.479822837 +0000+++ /tmp/MERGED-1142049178/apps.v1.Deployment.k-hub.web 2026-11-11 08:08:08.479822837 +0000@@ -6,7 +6,7 @@ kubectl.kubernetes.io/last-applied-configuration: | {"apiVersion":"apps/v1","kind":"Deployment","metadata":{"annotations":{},"labels":{"app":"web"},"name":"web","namespace":"k-hub"},"spec":{"replicas":2,"selector":{"matchLabels":{"app":"web"}},"strategy":{},"template":{"metadata":{"labels":{"app":"web"}},"spec":{"containers":[{"image":"nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb","name":"nginx","resources":{}}]}}},"status":{}} creationTimestamp: "2026-11-11T08:07:55Z"- generation: 1+ generation: 2 labels: app: web name: web@@ -31,7 +31,7 @@ app: web spec: containers:- - image: nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb+ - image: nginx:1.30.6@sha256:42c68eab6f7e22611786a9fe1d1c019e275c50185bd54b8f75dc2b9184322703 imagePullPolicy: IfNotPresent name: nginx resources: {}code de sortie du diff : 1deployment.apps/web configuredWaiting for deployment "web" rollout to finish: 1 out of 2 new replicas have been updated...Waiting for deployment "web" rollout to finish: 1 out of 2 new replicas have been updated...Waiting for deployment "web" rollout to finish: 1 out of 2 new replicas have been updated...Waiting for deployment "web" rollout to finish: 1 old replicas are pending termination...Waiting for deployment "web" rollout to finish: 1 old replicas are pending termination...Waiting for deployment "web" rollout to finish: 1 old replicas are pending termination...deployment "web" successfully rolled outWarning: resource deployments/web was previously managed with 'kubectl apply'. Rolling back will not update the kubectl.kubernetes.io/last-applied-configuration annotation, which may cause unexpected behavior on future 'kubectl apply' operations. Consider using 'kubectl apply' with your previous configuration file instead.deployment.apps/web rolled backWaiting for deployment "web" rollout to finish: 0 out of 2 new replicas have been updated...Waiting for deployment "web" rollout to finish: 1 out of 2 new replicas have been updated...Waiting for deployment "web" rollout to finish: 1 out of 2 new replicas have been updated...Waiting for deployment "web" rollout to finish: 1 out of 2 new replicas have been updated...Waiting for deployment "web" rollout to finish: 1 out of 2 new replicas have been updated...Waiting for deployment "web" rollout to finish: 1 old replicas are pending termination...Waiting for deployment "web" rollout to finish: 1 old replicas are pending termination...Waiting for deployment "web" rollout to finish: 1 old replicas are pending termination...deployment "web" successfully rolled outnginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edbIn the output of diff, the lines prefixed by - show the current state of the cluster and those prefixed by + the state that apply would produce: generation goes from 1 to 2 and the image goes from 1.30.5 to 1.30.6. The line code de sortie du diff : 1 comes from the echo of the command. The rollout undo prints a Warning: it does not update the last-applied-configuration annotation, so a later apply would start from an annotation that no longer reflects the cluster. The safest approach, says the warning, is to run kubectl apply again with the previous file. After the undo and its rollout status, the image is back to 1.30.5.
kubectl diff exits with code 0 when nothing changes and code 1 when it prints a difference: this is what makes it usable in a script. To restart all the Pods without changing the manifest, for example after the renewal of a Secret, use kubectl rollout restart deployment/web -n k-hub: it replaces the Pods progressively, at the pace of the rolling update strategy.
Get into a container
kubectl exec runs a command in a container that is already running. With the -it option, you open an interactive session (kubectl exec -it -n k-hub deploy/web -- sh, which you leave with exit), -c chooses the container when the Pod has several, and the double dash separates the kubectl options from the command run. A single command, without a session, is enough to read a file:
kubectl exec -n k-hub deploy/web -- ls /etc/nginxkubectl exec -n k-hub deploy/web -- sh -c 'echo "exec fonctionne dans $(hostname)"'conf.dfastcgi_paramsmime.typesmodulesnginx.confscgi_paramsuwsgi_paramsexec fonctionne dans web-5f9ccb876d-tvpcpls lists nginx.conf, conf.d, mime.types and other files. The second command prints the name of the Pod that ran it, web-…: the single quotes protect $(hostname) from your local shell, which would have evaluated it on your machine instead of in the container.
A minimal image, called distroless, contains no shell: exec then fails, and it is kubectl debug, taught in the lesson Debug an application, that attaches an ephemeral container equipped with tools.
Prepare a node for maintenance
Before restarting a node, you empty it cleanly. cordon forbids placing new Pods on it, drain evicts the existing Pods, and uncordon puts it back in service after the intervention. On a node that carries Pods, drain often asks for two options. The NODE variable picks the first worker node of the demo cluster.
NODE=$(kubectl get nodes -l '!node-role.kubernetes.io/control-plane' -o name | head -n 1)kubectl cordon "$NODE"kubectl drain "$NODE" --ignore-daemonsets --delete-emptydir-data --timeout=120skubectl get nodeskubectl uncordon "$NODE"kubectl get nodesnode/demo-worker cordonednode/demo-worker already cordonedWarning: ignoring DaemonSet-managed Pods: kube-system/kindnet-4dvmd, kube-system/kube-proxy-ds6glevicting pod k-hub/web-6fd8ff4b7c-pkf6npod/web-6fd8ff4b7c-pkf6n evictednode/demo-worker drainedNAME STATUS ROLES AGE VERSIONdemo-control-plane Ready control-plane 60s v1.37.0demo-worker Ready,SchedulingDisabled <none> 45s v1.37.0demo-worker2 Ready <none> 45s v1.37.0demo-worker3 Ready <none> 45s v1.37.0node/demo-worker uncordonedNAME STATUS ROLES AGE VERSIONdemo-control-plane Ready control-plane 61s v1.37.0demo-worker Ready <none> 46s v1.37.0demo-worker2 Ready <none> 46s v1.37.0demo-worker3 Ready <none> 46s v1.37.0In the output, drain reports already cordoned: it cordons the node itself, and the explicit command only shows the two steps. The warning ignoring DaemonSet-managed Pods cites kindnet and kube-proxy, which stay in place, then the web Pod present on this node is evicted. The first get nodes shows the node as Ready,SchedulingDisabled, and it becomes Ready again after uncordon.
--ignore-daemonsets leaves in place the Pods of DaemonSets, which by definition run on every node. --delete-emptydir-data agrees to lose emptyDir volumes, temporary directories tied to the life of the Pod: check that no useful data lives there. Without --timeout, drain waits indefinitely (--timeout=0s by default, according to kubectl drain --help). drain also refuses to delete a Pod started without a controller, a bare Pod that nothing would recreate elsewhere, unless --force is used.
Check a permission with auth can-i
kubectl auth can-i answers yes or no to the question "am I allowed to...". Permissions come from RBAC, the access control of Kubernetes, taught in the Workload security module. The --as option asks the question for another identity, for example a ServiceAccount, the account that an application uses.
kubectl auth can-i create deployments -n k-hubkubectl auth can-i create deployments -n k-hub --as=system:serviceaccount:k-hub:defaultkubectl auth can-i --list -n k-hub --as=system:serviceaccount:k-hub:defaultyesnoResources Non-Resource URLs Resource Names Verbsselfsubjectreviews.authentication.k8s.io [] [] [create]selfsubjectaccessreviews.authorization.k8s.io [] [] [create]selfsubjectrulesreviews.authorization.k8s.io [] [] [create]clustertrustbundles.certificates.k8s.io [] [] [get list watch] [/.well-known/openid-configuration/] [] [get] [/.well-known/openid-configuration] [] [get] [/api/*] [] [get] [/api] [] [get] [/apis/*] [] [get] [/apis] [] [get][...]The administrator account of the test cluster answers yes, and the default ServiceAccount of the k-hub namespace answers no: it has no right on Deployments. --list prints all the rights of an identity at once, which quickly answers an unexplained Forbidden. Here, the list only contains discovery rights (selfsubjectreviews, /api addresses, /version, /healthz...) and no right on Deployments. When the answer is no, the command exits with code 1, which a script can exploit.
How do you extract a specific field with JSONPath?
JSONPath extracts a value from the object without going through another tool. Kubernetes returns each resource as a JSON document; -o jsonpath designates a path in this document, and -o custom-columns builds a table where each column is a path. To find the path of a field, first print the object with -o yaml and follow the indentation. A frequent case: reading the image of a Deployment, in two ways.
kubectl get deployment web -n k-hub -o jsonpath='{.spec.template.spec.containers[0].image}{"\n"}'kubectl get deployment web -n k-hub -o custom-columns="NOM:.metadata.name,IMAGE:.spec.template.spec.containers[0].image"nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edbNOM IMAGEweb nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edbThe same mechanism reads a field of a Pod. The updates and the drain have replaced the Pods since the start of the lesson: a name noted earlier no longer exists and would return NotFound. The POD variable is therefore (re)assigned just before its use, keeping only a running Pod: right after a drain, a Pod that has just been recreated does not have an address yet, and the command would return an empty line. Here it returns the IP address of the Pod:
POD=$(kubectl get pods -n k-hub -l app=web --field-selector=status.phase=Running -o name | head -n 1)kubectl get "$POD" -n k-hub -o jsonpath='{.status.podIP}{"\n"}'10.244.2.4The output is an address of the Pod network, here in the 10.244.0.0/16 range of the kind cluster: yours will be different.
On a list, the following command prints all the nodes on one line, then one line per Pod with its image:
kubectl get nodes -o jsonpath='{.items[*].metadata.name}{"\n"}'kubectl get pods -n k-hub -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.containers[0].image}{"\n"}{end}'demo-control-plane demo-worker demo-worker2 demo-worker3web-5f9ccb876d-5jlxc nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edbweb-5f9ccb876d-tvpcp nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edbTwo clarifications help when reading a Deployment and its Pods. The node that hosts a Pod is read in the Pod, under .spec.nodeName. And the image that a Deployment requests is read in its Pod template, under .spec.template: during an update, or if it is paused, this template has already changed while Pods still run with the old image.
Three landmarks for reading these expressions. On a single object, the path starts from its root (.status.podIP). On a list, the objects are in .items, and [*] takes them all. range ... end repeats a pattern for each element, which lets you insert a tab and a newline between the values. The quotes around the expression prevent the shell (zsh in particular) from interpreting its brackets, braces and commas. The expression ends with {"\n"}, which adds a newline: without it, JSONPath writes none and the output sticks to the next prompt. With custom-columns, each column is written NOM:path and the columns are separated by commas, without a space.
Which pitfalls should you avoid with kubectl?
Many incidents caused by kubectl come from an exact command run in the wrong place, or from a syntax that the tool interprets differently from what you meant. The table gathers the classic pitfalls, with what you see and the correct command. The first three produce no error: they are spotted by an unexpected result, which is what makes them dangerous.
| Pitfall | What you see | Fix |
|---|---|---|
| Wrong active context | The command succeeds, but on another cluster | kubectl config current-context before any write, or --context on the command |
| Forgotten namespace | No resources found in default namespace. | Add -n NS, or search with -A |
Believing get all shows everything | No ConfigMap, Secret, Ingress or PVC in the output | Name the wanted types, separated by commas |
Running create again on an existing resource | Error from server (AlreadyExists): ... already exists | kubectl apply -f, which creates or updates |
exec without -- | error: exec [POD] [COMMAND] is not supported anymore | kubectl exec POD -- COMMAND |
drain --delete-local-data | error: unknown flag: --delete-local-data | --delete-emptydir-data, its replacement |
Space in a selector: -l app=web, env=prod | error: name cannot be provided when a selector is specified | No space: -l app=web,env=prod |
logs without a bound on an old Pod | Thousands of lines scrolling by | --since=10m --tail=200 |
| Deleting Pods to restart them | All the Pods go down at the same time | kubectl rollout restart deployment/NAME |
delete --force --grace-period=0 | Warning: Immediate deletion does not wait for confirmation... | Diagnose first; keep --force for a node that is definitively lost |
scale or set image without touching the manifest | The next apply puts the old value back | Carry the change into the versioned file |
Forbidden without knowing which right is missing | Error from server (Forbidden): pods is forbidden: User ... cannot list resource "pods" | kubectl auth can-i --list -n NS |
Why get all misleads: all is not a wildcard, it is a category declared by the API Server. The following command lists the types it contains. ConfigMaps and Secrets are not among them, and a namespace can look empty when it is not.
kubectl api-resources --categories=all -o namepodsreplicationcontrollersservicesdaemonsets.appsdeployments.appsreplicasets.appsstatefulsets.appshorizontalpodautoscalers.autoscalingcronjobs.batchjobs.batchThe list of the all category contains Pods, Services, workloads (deployments.apps, statefulsets.apps...) and Jobs, but no configmaps or secrets.
Two pitfalls of the table come from syntaxes still found in old tutorials, and version 1.37 refuses them instead of warning. The two following commands fail, and the failure is intended:
kubectl exec -n k-hub deploy/web ls /etc/nginxkubectl drain "$NODE" --ignore-daemonsets --delete-local-dataerror: exec [POD] [COMMAND] is not supported anymore. Use exec [POD] -- [COMMAND] insteadSee 'kubectl exec -h' for help and exampleserror: unknown flag: --delete-local-dataSee 'kubectl drain --help' for usage.Each message gives the fix: Use exec [POD] -- [COMMAND] instead for the first, and for the second the unknown flag, which --delete-emptydir-data replaces, used above.
The scale pitfall deserves a clarification, because it surprises even after a few months of practice. The versioned manifest remains the reference: a kubectl scale deployment web --replicas=3 followed by an apply of the file that declares replicas: 2 brings the Deployment back to 2 replicas. The fix is to write the new value in the manifest.
How do you clean up what the cheat sheet created?
Delete the k-hub namespace, which takes the Deployment and the Service with it, restore the default namespace of the context and erase the generated file:
kubectl delete namespace k-hubkubectl config set-context --current --namespace=defaultrm -f deploy.yamlnamespace "k-hub" deletedContext "kind-demo" modified.What does this error message mean?
A kubectl message first says where the request failed. A message that starts with Error from server comes from the API Server: the cluster answered, but it refuses or finds nothing. A connection refused, on the contrary, signals that the request never arrived. The states ImagePullBackOff and CrashLoopBackOff are of a different nature: the object exists, it is the kubelet, the agent of each node, that stumbles on the container.
| Message | Likely cause | First check |
|---|---|---|
The connection to the server localhost:8080 was refused | No kubeconfig found: kubectl tries the default address | echo $KUBECONFIG, then kubectl config current-context |
Error from server (NotFound): pods "web" not found | Wrong name or wrong namespace | Search all namespaces with -A |
Error from server (Forbidden) | Missing RBAC right | kubectl auth can-i --list -n NS |
ImagePullBackOff | Image or tag not found, private registry without a secret | kubectl describe pod, Events section |
CrashLoopBackOff | The container starts then stops in a loop | kubectl logs POD --previous |
Put it into practice
The guided lab starts from a web Deployment whose update is paused, in the extraction namespace of a kind cluster: its template asks for nginx 1.30.6, but its Pods still run 1.30.5. You record in ~/extraction/releve.txt the image requested by the Pod template, then you write the list of the web Pods with their node, once with JSONPath without a header, once with custom-columns under a header line. The validation compares these files with the state of the cluster, and it rejects an image read from a Pod of the old revision.
Key takeaways
- A kubectl command reads verb, type, name, options; without a name, it covers all the resources of the type in the targeted namespace.
kubectl config current-contextbefore any write;--contextand--kubeconfigonly apply to the command that carries them.--dry-run=client -o yamlgenerates a manifest without creating anything.get allshows neither ConfigMaps nor Secrets: list the types.- In 1.37,
execrequires the--anddrainrefuses--delete-local-data: write--delete-emptydir-data. - A
-lselector is written without a space after the comma. -o jsonpathextracts a value,-o custom-columns=NOM:pathbuilds a table; the path is read in-o yaml.- A change made by hand (
scale,set image) is carried into the manifest, otherwise the nextapplycancels it.
Test your knowledge
Six questions on reading a command, the options that change its scope and the pitfalls to recognize by their error message, in Kubernetes 1.37.
Knowledge check
Check what you have learned with this interactive quiz
How it works
- The timer starts when you click Start
- Multiple choice, true/false and short answer questions
- You can move between questions
- Detailed results are shown at the end
Starts the quiz and the timer
Review
(0/0)Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: Knowledge check: the basic Kubernetes resources
A new full quiz with random questions
Work again only on the questions you missed
Frequently asked questions about kubectl
These ten answers take up common questions about kubectl, in a short, self-contained form. They complete the cheat sheet on three distinctions that are best fixed early: apply versus create, edit versus patch versus replace, and the output formats -o wide, -o yaml and -o json.
Definition
kubectl is the official command-line interface of Kubernetes. Each command you type is translated into a REST request to the cluster's API Server.What kubectl lets you do
- Inspect the state of the cluster (pods, nodes, events)
- Deploy applications (apply, create)
- Debug problems (describe, logs, exec, debug)
- Maintain the cluster (drain, cordon, taint)
- Automate through scripts and CI/CD pipelines
Basic syntax
kubectl [VERB] [TYPE] [NAME] [OPTIONS]
- Verb: the action (
get,apply,delete,describe) - Type: the targeted resource (
pod,deploy,svc,node) - Name: optional (without a name = all resources)
- Options:
-n(namespace),-o(output format),-l(label selector)
Installation by OS
| OS | Method |
|---|---|
| Linux | Official binary downloaded from dl.k8s.io (below) |
| macOS | brew install kubectl |
| Windows | choco install kubernetes-cli or winget install Kubernetes.kubectl |
Official binary (Linux, amd64)
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
Verification
kubectl version --client
Autocompletion (strongly recommended)
# Bash
echo 'source <(kubectl completion bash)' >> ~/.bashrc
# Zsh
echo 'source <(kubectl completion zsh)' >> ~/.zshrc
The tutorial Install and configure kubectl (in French) details each method, checksum verification and aliases.The kubeconfig file
By default, kubectl reads~/.kube/config. This file contains:- clusters: addresses of the API servers
- users: identities and authentication methods
- contexts: combination of cluster + user + default namespace
Essential commands
# Show the active context
kubectl config current-context
# List all contexts
kubectl config get-contexts
# Switch context
kubectl config use-context my-staging-cluster
# Set a default namespace
kubectl config set-context --current --namespace=production
Multiple kubeconfigs
export KUBECONFIG=~/.kube/config:~/.kube/staging:~/.kube/prod
Companion tools
- kubectx: switch context in one word (
kubectx staging) - kubens: switch namespace (
kubens production) - kubie: per-shell isolation (no risk of the "wrong context")
The 10 everyday commands
| Command | Role |
|---|---|
kubectl get |
List resources (pods, deploy, svc…) |
kubectl describe |
Details + Events of a resource |
kubectl logs |
Logs of a container |
kubectl apply -f |
Deploy declaratively |
kubectl delete |
Delete a resource |
kubectl exec -it |
Open a shell in a container |
kubectl rollout |
Status, restart, undo of a deployment |
kubectl diff -f |
Preview changes before apply |
kubectl top |
CPU/memory consumption (pods, nodes) |
kubectl config |
Manage contexts and kubeconfig |
Example of a diagnostic workflow
# 1) Overview
kubectl get deploy,rs,po,svc -n production
# 2) Details of a failing pod
kubectl describe pod <pod> -n production
# 3) Recent logs
kubectl logs -n production pod/<pod> --since=10m --tail=200
Comparison
| Aspect | kubectl create |
kubectl apply |
|---|---|---|
| Mode | Imperative | Declarative |
| If the resource exists | Error | Update (3-way merge) |
| History | No | Yes (last-applied-configuration annotation) |
| Recommended use | Prototyping, one-shot scripts | Production, GitOps, CI/CD |
Recommended workflow
# 1) Generate a manifest
kubectl create deploy web --image=nginx:1.29-alpine@sha256:5616878291a2eed594aee8db4dade5878cf7edcb475e59193904b198d9b830de --dry-run=client -o yaml > deploy.yaml
# 2) Preview the changes
kubectl diff -f deploy.yaml
# 3) Apply
kubectl apply -f deploy.yaml
Simple rule
- Prototyping:
create(fast, one-shot) - Production:
apply(idempotent, traceable, GitOps-compatible)
Diagnostic workflow (fixed order)
# 1) Identify the problem
kubectl get pod <pod> -n <ns>
# 2) Read the Events
kubectl describe pod <pod> -n <ns>
# 3) See the logs (including from the previous crash)
kubectl logs <pod> -n <ns> --previous --tail=100
# 4) Sorted namespace events
kubectl get events -n <ns> --sort-by=.metadata.creationTimestamp
Frequent causes
| Status | Likely cause | Action |
|---|---|---|
| ImagePullBackOff | Image not found or registry auth | Check image, imagePullSecrets |
| CrashLoopBackOff | The app crashes at startup | logs --previous, env variables |
| OOMKilled | Memory limit exceeded | Increase limits.memory |
| Pending | No node available | describe pod → Events (taints, resources) |
| CreateContainerConfigError | Missing ConfigMap/Secret | Check that the refs exist |
Advanced debugging (distroless)
kubectl debug -it pod/<pod> -n <ns> --image=busybox:1.38.0@sha256:a46257e06c82ad85242d0d38077d0a52d9896389ca60a1a59d3463db586e5fa4 --target=<container>
Comparison
| Command | Use | Risk | Scriptable |
|---|---|---|---|
kubectl edit |
Interactive modification | Medium | No |
kubectl patch |
Targeted change (1-2 fields) | Low | Yes |
kubectl replace |
Full replacement | High | Yes |
Examples
# edit: opens in $EDITOR
kubectl edit deploy/web -n production
# patch: change the image without touching the rest
kubectl patch deploy/web -n production \
-p '{"spec":{"template":{"spec":{"containers":[{"name":"nginx","image":"nginx:1.29-alpine@sha256:5616878291a2eed594aee8db4dade5878cf7edcb475e59193904b198d9b830de"}]}}}}'
# replace: total replacement (careful!)
kubectl replace -f deploy.yaml
Which command to choose?
- Production emergency:
edit(fast, visual) - Script / CI:
patch(targeted, idempotent) - Full replacement:
replace(destructive, last resort)
Complete workflow
# 1) Block: no new pods on this node
kubectl cordon <node>
# 2) Evict: move the existing pods
kubectl drain <node> --ignore-daemonsets --delete-emptydir-data
# 3) Maintain: OS update, kubelet, etc.
# 4) Put back in service
kubectl uncordon <node>
# 5) Check
kubectl get nodes
kubectl get pods -A -o wide | grep <node>
Points of attention
- PodDisruptionBudget (PDB): drain respects PDBs. If
minAvailableblocks, drain waits --delete-emptydir-data: deletes emptyDir data (destructive but necessary)--ignore-daemonsets: DaemonSets stay (normal, they run everywhere)- Check beforehand:
kubectl get pdb -Ato anticipate blockages
Recommended CI/CD workflow
# 1) Validate the syntax
kubectl apply -f manifests/ --dry-run=server
# 2) Preview the changes
kubectl diff -f manifests/
# 3) Apply
kubectl apply -f manifests/
# 4) Wait for the rollout
kubectl rollout status deploy/<name> -n <ns> --timeout=300s
# 5) Check the pods
kubectl wait --for=condition=Ready pod -l app=<name> -n <ns> --timeout=120s
Automatic rollback
# If the rollout fails
if ! kubectl rollout status deploy/<name> --timeout=300s; then
kubectl rollout undo deploy/<name>
exit 1
fi
Best practices
- Always use
--dry-run=server(notclient) to validate on the API side - Set a
--timeoutonrollout statusandwait - Never use
kubectl editin a pipeline - Prefer
applyovercreatefor idempotence
Output formats
| Option | Use | Example |
|---|---|---|
| (default) | Summary table | kubectl get pods |
-o wide |
Table + extra columns (IP, node) | kubectl get pods -o wide |
-o yaml |
Complete resource in YAML | kubectl get deploy/web -o yaml |
-o json |
Complete resource in JSON | kubectl get pod/web -o json |
-o jsonpath |
Targeted field extraction | See examples below |
-o name |
Just the type/name | kubectl get pods -o name |
jsonpath examples
# IP of a pod
kubectl get pod web -o jsonpath='{.status.podIP}'
# Image of each pod
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.containers[0].image}{"\n"}{end}'
# Names of all nodes
kubectl get nodes -o jsonpath='{.items[*].metadata.name}'
Practical advice
- Quick debug:
-o wide(keeps the table format readable) - Scripting:
-o jsonpath(extract exactly what you need) - Understanding the resource:
-o yaml(see all the fields)