kubectl skills
The kubectl habits that save minutes per task. Imperative generators, dry-run, explain, output formats with jsonpath and custom columns, label, patch and set, apply versus create versus replace, diff, wait, copy and port-forward.
Exam tasks: all of them. This page covers no single competency, because every task is typed through kubectl.
The decision: which command creates, changes or reads the object with the fewest keystrokes and the least chance of a YAML mistake?
--all-namespaces is the long form.status.phase or by labels.Imperative generators
| Create | Command |
|---|---|
| Pod | k run web --image=nginx:1.27 --port=80 --labels=a=b --env=K=V |
| Deployment | k create deploy web --image=nginx:1.27 --replicas=3 --port=80 |
| Service from a workload | k expose deploy web --port=80 --target-port=8080 --type=NodePort --name=web-svc |
| Job, CronJob | k create job j --image=busybox:1.36 -- date and k create cronjob c --image=busybox:1.36 --schedule="*/5 * * * *" -- date |
| ConfigMap, Secret | k create cm app --from-literal=K=V --from-file=app.conf and k create secret generic db --from-literal=pw=x |
| ServiceAccount, Namespace | k create sa ci -n ops and k create ns ops |
| Role, RoleBinding | k create role r --verb=get,list --resource=pods and k create rolebinding rb --role=r --user=jana |
| ClusterRole, ClusterRoleBinding | k create clusterrole cr --verb=get --resource=nodes and k create clusterrolebinding crb --clusterrole=cr --user=jana |
| Ingress | k create ingress web --class=nginx --rule="shop.test/cart*=cart:80" |
| Quota, PriorityClass | k create quota q --hard=pods=10,cpu=4 and k create pc high --value=1000 |
export do="--dry-run=client -o yaml"
k create deploy web --image=nginx:1.27 --replicas=3 $do > web.yaml # edit, then: k apply -f web.yaml
k run tmp --rm -it --image=busybox:1.36 --restart=Never -- wget -qO- http://web.shop # throwaway test Podk runcreates a Pod. For anything with replicas, usek create deploy.- Generators cannot set everything.
k create deployhas no--env,--resourcesor probe flags in the form you need: generate, edit and apply.k set env,k set resourcesandk set imagechange an existing workload. - No generator exists for NetworkPolicy, PersistentVolume, PersistentVolumeClaim, StorageClass, HPA with custom metrics or Gateway API objects. Copy a manifest from the docs and edit it.
kubectl explain
k explain pod.spec.containers.securityContext # one level
k explain deploy.spec.strategy.rollingUpdate # field types and descriptions
k explain pod.spec --recursive | less # the whole tree, search with /
k explain backups.spec --api-version=vault.lab.io/v1 # a custom resource
k api-resources --namespaced=false # cluster-scoped kinds
k api-resources | grep -i polic # short names and API groupsexplain works offline from the cluster's OpenAPI schema, so it is faster than the browser and always matches the
cluster's version.
Reading output
| Goal | Command |
|---|---|
| More columns | -o wide |
| Labels | --show-labels or -L app,tier |
| One field | -o jsonpath='{.items[*].metadata.name}' |
| Loop over items | -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.podIP}{"\n"}{end}' |
| Chosen columns | -o custom-columns=NAME:.metadata.name,IMAGE:.spec.containers[0].image,NODE:.spec.nodeName |
| Sorted | --sort-by=.metadata.creationTimestamp or --sort-by=.status.capacity.storage |
| Filter by label | -l app=web,tier!=db |
| Filter by field | --field-selector status.phase=Running,spec.nodeName=worker-1 |
| The saved YAML | -o yaml |
| Watch | -w |
k get nodes -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.nodeInfo.kubeletVersion}{"\n"}{end}'
k get pods -A --field-selector status.phase!=Running
k get pv --sort-by=.spec.capacity.storage
k get events -A --sort-by=.lastTimestamp | tail -20Exam signal
Tasks that say "write the names of … to a file" are checking your output flags. Write exactly what was asked, one per
line, and cat the file to check it before you move on.
Changing a live object
| Need | Command |
|---|---|
| Image, env or resources of a workload | k set image deploy/web web=nginx:1.28 and k set env deploy/web K=V and k set resources deploy/web --limits=cpu=500m,memory=256Mi |
| Replicas | k scale deploy/web --replicas=5 |
| Labels and annotations | k label pod web tier=front --overwrite and k annotate pod web note="canary" and a trailing - removes one (k label pod web tier-) |
| Node maintenance | k cordon n1, k drain n1 --ignore-daemonsets --delete-emptydir-data, k uncordon n1 |
| Taints | k taint nodes n1 gpu=true:NoSchedule and k taint nodes n1 gpu=true:NoSchedule- to remove |
| A single field | k patch deploy web -p '{"spec":{"replicas":4}}' |
| A list item | k patch pod web --type=json -p '[{"op":"replace","path":"/spec/containers/0/image","value":"nginx:1.28"}]' |
| In an editor | k edit deploy web |
patchdefaults to a strategic merge patch.--type=mergereplaces lists whole, and--type=jsonaddresses one item by path.k editon a field that cannot change fails and saves the file under/tmp. Fix the file and runk replace --force -f <file>.
apply, create, replace, diff
| Command | Creates | Updates | Needs the object to exist |
|---|---|---|---|
create -f | Yes | No, errors with AlreadyExists | No |
apply -f | Yes | Yes, three-way merge, stores last-applied-configuration | No |
replace -f | No | Yes, whole object, requires resourceVersion match when set | Yes |
replace --force -f | Yes | Delete, then create | No |
apply --server-side | Yes | Yes, field ownership tracked by the server | No |
k diff -f file.yamlshows whatapplywould change.k apply -f dir/applies every manifest in a directory. Add-Rfor subdirectories, and-k dir/for Kustomize.- Mixing
createandapplyon one object makesapplywarn about a missing annotation. Use one habit per object.
Waiting, copying, forwarding
k wait --for=condition=Ready pod/web --timeout=60s
k wait --for=condition=Available deploy/web --timeout=120s
k wait --for=delete pod/old --timeout=60s
k rollout status deploy/web
k cp shop/web-0:/var/log/app.log ./app.log -c web # needs tar in the container
k port-forward svc/web 8080:80 & # then curl localhost:8080
k exec -it web-0 -c web -- sh
k auth can-i create deploy --as=jana -n shop
k debug node/worker-1 -it --image=busybox:1.36 # a Pod on the node with the host file system at /hostNamespaces and cleanup
k get ns,k create ns x,k delete ns xremoves everything inside. A namespace stuck inTerminatingusually has an unavailable APIService or a finalizer on something inside.k config set-context --current --namespace=xchanges the default. Reset it todefaultafter the task if your habits need it.- Fast delete in the exam:
k delete pod web --force --grace-period=0. Use$nowas defined on the exam page.
Scenarios
The generator makes the Deployment and the set subcommands add what its flags cannot. kubectl run creates a single
Pod and has no --replicas, and create deploy has no flags for env or requests. Writing YAML by hand is slower and
easier to get wrong.
The field selector filters on the server, and the jsonpath range prints one bare name per line. The other commands write table, describe or YAML output, which a grader comparing names would reject.
replace --force deletes the Pod and recreates it from the edited file, which works when the field cannot change on a
live object. Applying again hits the same validation, nodes do not control Pod immutability, and deleting the namespace
is far more than needed. On a cluster that supports in-place resize, the resize subresource is the other valid path.
Drill
kubectl config use-context cka-lab1
Write to /tmp/nodes.txt the name and kubelet version of each node, tab-separated. Write the names of all Pods in the
kube-system namespace sorted by creation time, oldest first, to /tmp/pods.txt. Then create a Pod probe in
default that runs sleep 1d, labeled role=probe and env=lab, and remove the env label from it.
k get nodes -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.nodeInfo.kubeletVersion}{"\n"}{end}' > /tmp/nodes.txt
k get pods -n kube-system --sort-by=.metadata.creationTimestamp \
-o custom-columns=NAME:.metadata.name --no-headers > /tmp/pods.txt
k run probe --image=busybox:1.36 --labels=role=probe,env=lab -- sleep 1d
k label pod probe env-
k get pod probe --show-labels
cat /tmp/nodes.txt /tmp/pods.txtRelated
- The CKA exam: terminal setup, variables and time management.
- kubeconfig and certificates: contexts and namespaces.
- Pods and containers: what the generators build.
- Troubleshooting: the read commands in use.
Further reading
The CKA exam
Format, domain weights, the competency numbering used in this handbook, and a terminal setup that saves minutes on every task.
Domain 1 · Cluster architecture, installation and configuration
25% of the exam. Granting access with RBAC, building, upgrading and backing up kubeadm clusters, HA control planes, Helm and Kustomize, plugin interfaces, CRDs and operators.