Skip to content
Français
Account: not signed in, sync available My learning
Select theme
Français

kubectl cheat sheet: syntax, options, patterns and pitfalls

By updated

Improve this page

Logo Kubernetes

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 kubectl command 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.

Terminal window
kubectl get pods -n k-hub -o wide
No 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.

PartQuestionExamplesMandatory
VerbWhich action?get, describe, apply, delete, logsYes
TypeOn which type of resource?pod, deployment, service, nodeYes, except global commands such as version
NameWhich specific resource?web, <nom-d-un-pod>No: without a name, all the resources of the type
OptionsWith which parameters?-n k-hub, -o wide, -l app=webNo

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.

OptionEffectExample
-n NSTarget a namespacekubectl get pods -n kube-system
-AAll namespaceskubectl get pods -A
-o wideExtra columns (IP, node)kubectl get pods -o wide
-o yaml or -o jsonThe complete objectkubectl get deploy web -o yaml
-o nameOnly type/name, handy in scriptskubectl get pods -o name
-o jsonpath=...A specific fieldsee the JSONPath section
-o custom-columns=...Your own columnssee the JSONPath section
-l key=valueFilter by labelkubectl get pods -l app=web
--field-selectorFilter on a field of the object--field-selector=status.phase!=Running
--sort-bySort the output--sort-by=.metadata.creationTimestamp
-wFollow changes livekubectl get pods -w
--dry-run=client -o yamlPrint the YAML without creating anythingsee "Generate a manifest"
--context CTXTarget another context for this commandkubectl --context=staging get pods
--kubeconfig FILERead another kubeconfig filekubectl --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.

CommandsLessonModule
config, contexts, kubeconfigKubeconfig and contextsFundamentals
get, describe, logs, topGet information on resourcesFundamentals
label, annotateLabels and annotationsBasic resources
expose, port-forward, proxyReach an applicationBasic resources
rollout, set, scaleRolling updates and rollbacksBasic resources
api-resources, explainExplore the APIDeploy your applications
create, applyCreate and applyDeploy your applications
diff, waitPreview and wait (optional)Deploy your applications
exec, debug, cpDebug an applicationDeploy your applications
autoscaleHorizontal Pod scalingScheduling and capacity
auth can-iRBACWorkload security
edit, patch, replaceModify a resource in place (in French)Day-to-day operations
cordon, drain, taintPrepare 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.

Terminal window
kubectl config current-context
kubectl config get-contexts
kubectl config use-context kind-demo
kubectl create namespace k-hub
kubectl config set-context --current --namespace=k-hub
kind-demo
CURRENT NAME CLUSTER AUTHINFO NAMESPACE
* kind-demo kind-demo kind-demo
Switched to context "kind-demo".
namespace/k-hub created
Context "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:

Terminal window
kubectl create deployment web -n k-hub \
--image=nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb \
--replicas=2 --dry-run=client -o yaml > deploy.yaml
head -n 12 deploy.yaml
kubectl apply -f deploy.yaml
kubectl rollout status deployment/web -n k-hub
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: web
name: web
namespace: k-hub
spec:
replicas: 2
selector:
matchLabels:
app: web
deployment.apps/web created
Waiting 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 out

The 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.

Terminal window
kubectl expose deployment web -n k-hub --port=80
POD=$(kubectl get pods -n k-hub -l app=web -o name | head -n 1)
kubectl get deploy,rs,po,svc,cm,secret -n k-hub
kubectl describe "$POD" -n k-hub | tail -n 12
kubectl logs deploy/web -n k-hub --since=10m --tail=20
kubectl get events -n k-hub --sort-by=.metadata.creationTimestamp
service/web exposed
NAME READY UP-TO-DATE AVAILABLE AGE
deployment.apps/web 2/2 2 2 13s
NAME DESIRED CURRENT READY AGE
replicaset.apps/web-5f9ccb876d 2 2 2 13s
NAME READY STATUS RESTARTS AGE
pod/web-5f9ccb876d-55cds 1/1 Running 0 13s
pod/web-5f9ccb876d-ddqw4 1/1 Running 0 13s
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/web ClusterIP 10.96.232.212 <none> 80/TCP 0s
NAME DATA AGE
configmap/kube-root-ca.crt 1 13s
QoS Class: BestEffort
Node-Selectors: <none>
Tolerations: node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
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 started
Found 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.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-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 up
2026/11/11 08:08:06 [notice] 1#1: using the "epoll" event method
2026/11/11 08:08:06 [notice] 1#1: nginx/1.30.5
2026/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-amd64
2026/11/11 08:08:06 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1073741816:1073741816
2026/11/11 08:08:06 [notice] 1#1: start worker processes
2026/11/11 08:08:06 [notice] 1#1: start worker process 36
2026/11/11 08:08:06 [notice] 1#1: start worker process 37
LAST SEEN TYPE REASON OBJECT MESSAGE
13s Normal Scheduled pod/web-5f9ccb876d-55cds Successfully assigned k-hub/web-5f9ccb876d-55cds to demo-worker3
13s Normal ScalingReplicaSet deployment/web Scaled up replica set web-5f9ccb876d from 0 to 2
13s Normal SuccessfulCreate replicaset/web-5f9ccb876d Created pod: web-5f9ccb876d-55cds
13s Normal SuccessfulCreate replicaset/web-5f9ccb876d Created pod: web-5f9ccb876d-ddqw4
13s Normal Scheduled pod/web-5f9ccb876d-ddqw4 Successfully assigned k-hub/web-5f9ccb876d-ddqw4 to demo-worker2
12s 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 started
2s Normal Created pod/web-5f9ccb876d-ddqw4 Container created
2s 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 started
0s Normal Created pod/web-5f9ccb876d-55cds Container created
0s 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:

Terminal window
sed -i 's|nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb|nginx:1.30.6@sha256:42c68eab6f7e22611786a9fe1d1c019e275c50185bd54b8f75dc2b9184322703|' deploy.yaml
kubectl diff -f deploy.yaml; echo "code de sortie du diff : $?"
kubectl apply -f deploy.yaml
kubectl rollout status deployment/web -n k-hub --timeout=120s
kubectl rollout undo deployment/web -n k-hub
kubectl rollout status deployment/web -n k-hub --timeout=120s
kubectl 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 : 1
deployment.apps/web configured
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 out
Warning: 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 back
Waiting 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 out
nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb

In 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:

Terminal window
kubectl exec -n k-hub deploy/web -- ls /etc/nginx
kubectl exec -n k-hub deploy/web -- sh -c 'echo "exec fonctionne dans $(hostname)"'
conf.d
fastcgi_params
mime.types
modules
nginx.conf
scgi_params
uwsgi_params
exec fonctionne dans web-5f9ccb876d-tvpcp

ls 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.

Terminal window
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=120s
kubectl get nodes
kubectl uncordon "$NODE"
kubectl get nodes
node/demo-worker cordoned
node/demo-worker already cordoned
Warning: ignoring DaemonSet-managed Pods: kube-system/kindnet-4dvmd, kube-system/kube-proxy-ds6gl
evicting pod k-hub/web-6fd8ff4b7c-pkf6n
pod/web-6fd8ff4b7c-pkf6n evicted
node/demo-worker drained
NAME STATUS ROLES AGE VERSION
demo-control-plane Ready control-plane 60s v1.37.0
demo-worker Ready,SchedulingDisabled <none> 45s v1.37.0
demo-worker2 Ready <none> 45s v1.37.0
demo-worker3 Ready <none> 45s v1.37.0
node/demo-worker uncordoned
NAME STATUS ROLES AGE VERSION
demo-control-plane Ready control-plane 61s v1.37.0
demo-worker Ready <none> 46s v1.37.0
demo-worker2 Ready <none> 46s v1.37.0
demo-worker3 Ready <none> 46s v1.37.0

In 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.

Terminal window
kubectl auth can-i create deployments -n k-hub
kubectl auth can-i create deployments -n k-hub --as=system:serviceaccount:k-hub:default
kubectl auth can-i --list -n k-hub --as=system:serviceaccount:k-hub:default
yes
no
Resources Non-Resource URLs Resource Names Verbs
selfsubjectreviews.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.

Terminal window
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:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb
NOM IMAGE
web nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb

The 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:

Terminal window
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.4

The 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:

Terminal window
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-worker3
web-5f9ccb876d-5jlxc nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb
web-5f9ccb876d-tvpcp nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb

Two 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.

PitfallWhat you seeFix
Wrong active contextThe command succeeds, but on another clusterkubectl config current-context before any write, or --context on the command
Forgotten namespaceNo resources found in default namespace.Add -n NS, or search with -A
Believing get all shows everythingNo ConfigMap, Secret, Ingress or PVC in the outputName the wanted types, separated by commas
Running create again on an existing resourceError from server (AlreadyExists): ... already existskubectl apply -f, which creates or updates
exec without --error: exec [POD] [COMMAND] is not supported anymorekubectl exec POD -- COMMAND
drain --delete-local-dataerror: unknown flag: --delete-local-data--delete-emptydir-data, its replacement
Space in a selector: -l app=web, env=proderror: name cannot be provided when a selector is specifiedNo space: -l app=web,env=prod
logs without a bound on an old PodThousands of lines scrolling by--since=10m --tail=200
Deleting Pods to restart themAll the Pods go down at the same timekubectl rollout restart deployment/NAME
delete --force --grace-period=0Warning: 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 manifestThe next apply puts the old value backCarry the change into the versioned file
Forbidden without knowing which right is missingError 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.

Terminal window
kubectl api-resources --categories=all -o name
pods
replicationcontrollers
services
daemonsets.apps
deployments.apps
replicasets.apps
statefulsets.apps
horizontalpodautoscalers.autoscaling
cronjobs.batch
jobs.batch

The 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:

Terminal window
kubectl exec -n k-hub deploy/web ls /etc/nginx
kubectl drain "$NODE" --ignore-daemonsets --delete-local-data
error: exec [POD] [COMMAND] is not supported anymore. Use exec [POD] -- [COMMAND] instead
See 'kubectl exec -h' for help and examples
error: unknown flag: --delete-local-data
See '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:

Terminal window
kubectl delete namespace k-hub
kubectl config set-context --current --namespace=default
rm -f deploy.yaml
namespace "k-hub" deleted
Context "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.

MessageLikely causeFirst check
The connection to the server localhost:8080 was refusedNo kubeconfig found: kubectl tries the default addressecho $KUBECONFIG, then kubectl config current-context
Error from server (NotFound): pods "web" not foundWrong name or wrong namespaceSearch all namespaces with -A
Error from server (Forbidden)Missing RBAC rightkubectl auth can-i --list -n NS
ImagePullBackOffImage or tag not found, private registry without a secretkubectl describe pod, Events section
CrashLoopBackOffThe container starts then stops in a loopkubectl 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-context before any write; --context and --kubeconfig only apply to the command that carries them.
  • --dry-run=client -o yaml generates a manifest without creating anything.
  • get all shows neither ConfigMaps nor Secrets: list the types.
  • In 1.37, exec requires the -- and drain refuses --delete-local-data: write --delete-emptydir-data.
  • A -l selector is written without a space after the comma.
  • -o jsonpath extracts a value, -o custom-columns=NOM:path builds a table; the path is read in -o yaml.
  • A change made by hand (scale, set image) is carried into the manifest, otherwise the next apply cancels 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

6 questions
5 min
80% to pass

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

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.