Skip to main content

Command Patterns: kubectl by Task

Docs: kubectl overview · kubectl quick reference · kubectl command reference

Skip memorising flags. Learn one grammar, the lookup commands, and the patterns below, organized by what you want to do. -h fills in the rest. To see which object each command acts on, look at the object map. Every Lab's 🟢 Guided tier uses exactly these patterns, and the 🟡 Hints tier points you back to them. Exam-speed tricks (aliases, $do, jsonpath) live in the kubectl Cheatsheet.

The grammar​

kubectl <verb> <type>[/<name>] [-n <namespace>] [flags] [-- <command> <args>]
kubectl get pods/web -n lab2-2 -o wide
kubectl create deployment web -n lab2-2 --image=nginx:1.27 --replicas=3
kubectl run tmp -n lab2-2 --image=busybox:1.36 --rm -it --restart=Never -- sh
PartWhat goes thereFind valid values with
verbWhat to do: get, create, delete…kubectl -h
typeA resource: pods, deployments, or short names po, deploy, svckubectl api-resources
nameOne object. Omit it to act on all of that type.kubectl get <type>
-nThe namespace. -A means all namespaces.Which namespace?
flagsOptions for this verbkubectl <verb> -h
--Everything after it is the container's commandWhat -- does

Verb families​

FamilyVerbsChanges the cluster?
Lookget, describe, logs, events, top, explain, auth can-iNo
Create from flags (imperative)run, create, expose, autoscaleYes
Changeapply, set, scale, label, annotate, patch, edit, rolloutYes
Get insideexec, port-forward, cp, debugNo (except debug, which adds a container)
RemovedeleteYes

What -- does​

CommandWords after -- becomeResult with an image that has an entrypoint
kubectl run x --image=img -- a bargsEntrypoint runs with a b as arguments
kubectl run x --image=img --command -- a bcommandEntrypoint replaced by a b
kubectl create deployment x --image=img -- a bcommandEntrypoint replaced by a b
kubectl create job x --image=img -- a bcommandEntrypoint replaced by a b

This is why the image kit starts agnhost with -- netexec under run, but -- /agnhost netexec under create deployment.

Look it up instead of memorising​

I don't know…RunWhat you get
Which flags a command takeskubectl create deployment -hExamples first, then flags. Copy an example and change the names.
What I can create from flagskubectl create -hThe list of generators: deployment, job, secret, role…
What a field is called, or where it goeskubectl explain deploy.spec.strategyField docs. Add --recursive for the whole tree.
A kind's short name, API group, or whether it's namespacedkubectl api-resourcesOne row per kind
What YAML a command would produceAppend --dry-run=client -o yamlThe manifest. Nothing is created.
Which flags work on every commandkubectl options-n, --context, -v…

I want to…​

Run something​

I want to…PatternExample
Run one Podkubectl run <name> --image=<img>kubectl run web --image=nginx:1.27
Run N copies that heal themselveskubectl create deployment <name> --image=<img> --replicas=<n>kubectl create deployment web --image=nginx:1.27 --replicas=3
Run a task to completionkubectl create job <name> --image=<img> -- <cmd>kubectl create job hello --image=busybox:1.36 -- echo hi
Run a task on a schedulekubectl create cronjob <name> --image=<img> --schedule="<cron>" -- <cmd>kubectl create cronjob tick --image=busybox:1.36 --schedule="*/5 * * * *" -- date
Get a throwaway shellkubectl run tmp --rm -it --image=busybox:1.36 --restart=Never -- shDeleted when you exit

Expose it​

I want to…PatternExample
Give Pods one stable namekubectl expose deployment <name> --port=<svc-port> --target-port=<container-port>kubectl expose deployment web --port=80
Reach it from my laptopkubectl port-forward svc/<name> <local>:<svc-port>kubectl port-forward svc/web 8080:80
Route HTTP by host and pathkubectl create ingress <name> --rule="<host>/<path>*=<svc>:<port>"kubectl create ingress shop --rule="shop.example.com/api*=api:80"

Configure it​

I want to…PatternExample
Store settingskubectl create configmap <name> --from-literal=<K>=<V>kubectl create configmap cfg --from-literal=MODE=prod
Store a passwordkubectl create secret generic <name> --from-literal=<K>=<V>kubectl create secret generic db --from-literal=password=s3cr3t
Inject them as env varskubectl set env deployment/<name> --from=configmap/<cm>kubectl set env deployment/web --from=configmap/cfg
Set requests and limitskubectl set resources deployment/<name> --requests=... --limits=...kubectl set resources deployment/web --requests=cpu=100m,memory=128Mi
Autoscalekubectl autoscale deployment <name> --min=<n> --max=<n> --cpu-percent=<pct>kubectl autoscale deployment web --min=2 --max=10 --cpu-percent=50. kubectl 1.34+ prefers --cpu=50% and warns that --cpu-percent is deprecated; both create the same HPA.

Change it​

I want to…PatternExample
Ship a new imagekubectl set image deployment/<name> <container>=<img>kubectl set image deployment/web nginx=nginx:1.28
Change the replica countkubectl scale deployment <name> --replicas=<n>kubectl scale deployment web --replicas=5
Undo the last rolloutkubectl rollout undo deployment/<name>kubectl rollout undo deployment/web
Restart all Podskubectl rollout restart deployment/<name>Picks up new ConfigMap values
Change one fieldkubectl patch <type> <name> -p '<json>'kubectl patch svc web -p '{"spec":{"selector":{"app":"web"}}}'
Change anything, by handkubectl edit <type>/<name>Opens the live object in $EDITOR
Apply a filekubectl apply -f <file>kubectl apply -f web.yaml

Check it​

I want to…PatternExample
See if it's runningkubectl get <type> [-o wide] [-w]kubectl get pods -w
See why it isn'tkubectl describe <type>/<name>, then read Eventskubectl describe pod/web-7d4f
See what it printedkubectl logs <pod> [-c <container>] [--previous] [-f]kubectl logs web-7d4f --previous
See what just happenedkubectl get events --sort-by=.lastTimestampAdd --field-selector type=Warning
See who did itkubectl get events -o custom-columns=REASON:.reason,SOURCE:.source.component,MESSAGE:.messageSOURCE is replicaset-controller, default-scheduler, kubelet…
Wait for a rolloutkubectl rollout status deployment/<name>kubectl rollout status deployment/web
Wait for a conditionkubectl wait --for=condition=<c> <type>/<name> --timeout=<t>kubectl wait --for=condition=Ready pod/web --timeout=60s
Check a permissionkubectl auth can-i <verb> <type> --as=<who>kubectl auth can-i list pods --as=system:serviceaccount:lab6-2:ci-bot

Get inside​

I want to…PatternExample
Run a command in a containerkubectl exec <pod> [-c <container>] -- <cmd>kubectl exec web-7d4f -- nginx -v
Open a shell in itkubectl exec -it <pod> -- shNeeds a shell in the image
Call a Service from insidekubectl exec <client> -- wget -qO- -T 3 http://<svc>Uses the client Pod
Debug an image with no shellkubectl debug -it <pod> --image=busybox:1.36 --target=<container>Adds a temporary container

Clean up​

I want to…PatternExample
Delete one objectkubectl delete <type> <name>kubectl delete pod web
Delete a whole labkubectl delete namespace <ns>kubectl delete namespace lab2-2

Generate, edit, apply​

Generators can't set everything: probes, volumes and resources need YAML. Generate a correct skeleton instead of typing one:

kubectl create deployment web --image=nginx:1.27 --dry-run=client -o yaml > web.yaml # 1. generate
# 2. edit web.yaml: add only what the generator can't set
kubectl apply -f web.yaml # 3. apply
ResourceGeneratorAdd by hand
PodrunProbes, volumes, resources, securityContext
Deploymentcreate deploymentProbes, strategy, volumes
Serviceexpose / create serviceNamed ports
Job / CronJobcreate job / create cronjobcompletions, parallelism, backoffLimit / concurrencyPolicy, timeZone
ConfigMap, Secret, ServiceAccount, Role, RoleBinding, Quotacreate <kind>Rarely anything
Ingresscreate ingressTLS details
HPAautoscalebehavior
NetworkPolicy, PVC, LimitRangeNoneCopy a skeleton from the reference page or the docs

Which namespace does my command use?​

The first of these that is set wins:

  1. The -n flag
  2. metadata.namespace in the YAML (a conflict with -n is an error)
  3. The current context's namespace
  4. default

Check the current default with kubectl config view --minify | grep namespace. The Guided tier of every lab passes -n lab<N> explicitly, so it works whatever your default is.

The image kit​

Four images cover every lab. Pin the tags: the rollout labs rely on the difference between nginx:1.27 and 1.28, and latest changes under you.

ImageGives youUse it forStart it with
busybox:1.36sh, wget, nslookup, sleepTest clients, one-off commands, Jobs, fake apps that crash on purposekubectl run c --image=busybox:1.36 --restart=Never -- sleep 3600
nginx:1.27 (and 1.28)Web server on port 80Deployments, Services, rolling updateskubectl create deployment web --image=nginx:1.27
registry.k8s.io/e2e-test-images/agnhost:2.53HTTP server on any port, with /hostname, /healthz and /readyzServices where targetPort isn't 80, probes, NetworkPolicykubectl create deployment api --image=registry.k8s.io/e2e-test-images/agnhost:2.53 -- /agnhost netexec --http-port=8080
registry.k8s.io/hpa-exampleA CPU-heavy page on port 80HPA load testskubectl create deployment web --image=registry.k8s.io/hpa-example --port=80

Keep a client Pod. Start c once per lab and test through it with kubectl exec c -- wget -qO- -T 3 http://<svc>. It's faster than a new run --rm each time, and run --rm -i can lose output while it attaches.


Next in path → Architecture (skim), then Phase 2