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

CKAD cheat sheet: essential kubectl commands

By updated

Improve this page

Logo Kubernetes

This cheat sheet is about execution speed. The exam is 100% hands-on: you solve several tasks on the command line, against the clock. The page gathers the commands that are useful for these tasks, grouped by CKAD domain.

What you will learn

This page is a reference to keep open during your practice sessions. It does not re-explain the Kubernetes objects, which the lessons of the course teach: it saves you time on the gestures the exam repeats. By the end, you will be able to:

  • prepare your session with the k alias and the $do variable;
  • generate a YAML skeleton with --dry-run=client -o yaml, then complete it;
  • find the command that answers each domain of the CKAD exam;
  • diagnose a Pod that does not start, with describe, logs and events;
  • find the exact syntax of a field with kubectl explain.

Need-to-command table

This table reads in the direction of the exam: you start from a task statement, not from a command. Two shortcuts come back all the time and are defined right after: k is an alias for kubectl, and $do is a variable that holds the options for generating YAML. Without them, every line takes much longer to type.

The images carry their @sha256:… digest, as everywhere on this site: it guarantees that you run exactly the image that was tested. On exam day, type the image exactly as the task gives it, usually a name and a tag, without a digest.

NeedCommand
Generate a Pod YAMLk run nginx --image=nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb $do > pod.yaml
Generate a Deployment YAMLk create deploy webapp --image=nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb $do > deploy.yaml
Quickly expose a Deploymentk expose deploy webapp --port=80
Update a Deployment's imagek set image deploy webapp webapp=nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb
See why a Pod does not startk describe pod <name>
Read the logs of a crashk logs <pod> --previous
Find the syntax of a fieldk explain pod.spec.containers
Switch namespace quicklykn <namespace> (alias below)
See recent eventsk get events --sort-by='.lastTimestamp'
Roll back a Deploymentk rollout undo deploy webapp

Session bootstrap

Check these items right at the start of the exam:

Terminal window
# Check the available aliases
alias
# The k alias must exist
alias k=kubectl
# Variable to generate the YAML without creating the object
export do="--dry-run=client -o yaml"
# Alias to switch namespace quickly
alias kn='kubectl config set-context --current --namespace'
# Autocompletion
source <(kubectl completion bash)
complete -F __start_kubectl k
# Editor
export KUBE_EDITOR="vim"

A common pitfall is to forget to check the namespace: each question can target a different namespace.

Terminal window
# Show the current namespace
k config view --minify | grep namespace
# Switch namespace
kn production

Application Design and Build (20%)

This domain is about creating the objects that run your code: Pods, Deployments, Jobs and CronJobs. The technique is always the same: generate a YAML skeleton with an imperative command, then edit it to add what the command line cannot express, such as volumes or health probes.

Create a Pod

The most direct form creates the Pod immediately in the current namespace, without going through a file.

Terminal window
k run nginx --image=nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb

This simple Pod suits a quick test or a throwaway Pod. The pitfall is to forget to generate the YAML when you need to add volumes or probes: the direct command cannot express them.

Terminal window
# Generate the YAML to edit it
k run nginx --image=nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb $do > pod.yaml

Useful options for kubectl run

These options spare you from editing the YAML in simple cases. The last one is the one to remember first: --command -- sleep 3600 keeps a Pod alive even though its image would exit immediately.

OptionUsage
--port=80Declares a port (documentation only)
--labels="app=web"Adds labels
--env="DB_HOST=mysql"Environment variable
--requests="cpu=100m,memory=128Mi"Minimum resources
--limits="cpu=200m,memory=256Mi"Maximum resources
--command -- sleep 3600Replaces ENTRYPOINT

Create a Deployment

Unlike run, the subcommand is create deploy, and it accepts the number of replicas directly.

Terminal window
k create deploy webapp --image=nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb --replicas=3

This Deployment suits a stateless application that you want to be able to multiply. Note that kubectl automatically adds the label app=webapp to the Pods: it is the one that expose will reuse for the Service.

Terminal window
# Generate the YAML
k create deploy webapp --image=nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb --replicas=3 $do > deploy.yaml

Job and CronJob

The -- separates the kubectl options from the command run inside the container. Everything after it is passed as is and replaces the default command of the image.

Terminal window
# One-off Job
k create job backup --image=busybox:1.38.0@sha256:a46257e06c82ad85242d0d38077d0a52d9896389ca60a1a59d3463db586e5fa4 -- tar -czf /backup/data.tar.gz /data
# Scheduled CronJob
k create cronjob daily-backup --image=busybox:1.38.0@sha256:a46257e06c82ad85242d0d38077d0a52d9896389ca60a1a59d3463db586e5fa4 --schedule="0 2 * * *" -- /scripts/backup.sh

Remember three cron schedules: */5 * * * * runs every 5 minutes, 0 * * * * every hour on the hour, 0 2 * * * every day at 2 a.m.


Application Deployment (20%)

This domain covers the life of an application that is already deployed: changing its image, following the progressive rollout, rolling back, adjusting the number of replicas. All these commands act on an existing Deployment, so they are replayable without recreating anything.

Update the image

This command modifies the Deployment in place, which triggers the progressive replacement of the Pods. The difficulty is that the command expects the container name, not the Deployment name, even though they are often identical.

Terminal window
k set image deploy webapp webapp=nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb

The syntax is <container>=<new-image>. If the container name does not match the one defined in the Deployment, kubectl rejects the command.

Follow and undo a rollout

Kubernetes keeps a revision history of the Deployment, which lets you return to the previous state without rewriting the YAML. The rollout status command blocks the terminal until the rollout is finished: you therefore know whether the update succeeds or not. If it fails, the command returns a non-zero exit code, which a script can test.

Terminal window
# Follow the rollout
k rollout status deploy webapp
# See the history
k rollout history deploy webapp
# Immediate rollback
k rollout undo deploy webapp
# Roll back to a specific revision
k rollout undo deploy webapp --to-revision=1

The pitfall: rollout undo returns as soon as the rollback is started, not when it has completed. So check with rollout status.

Scale a Deployment

The change is immediate and works in both directions; going down to 0 stops the application without deleting the Deployment.

Terminal window
k scale deploy webapp --replicas=5

Autoscaling

This command creates a HorizontalPodAutoscaler, an object that adjusts the number of replicas on its own according to the CPU load. It only works if the cluster exposes consumption metrics.

Terminal window
k autoscale deploy webapp --min=2 --max=10 --cpu=80%

Application Observability and Maintenance (15%)

This domain is about diagnosis, and it follows a precise order: describe first, to know whether the Pod even started; logs next, to know what the application said before it stopped; exec last, to check from the inside. Reversing this order wastes time on a Pod that never ran.

Logs

Logs come from one container at a time: on a multi-container Pod, kubectl logs does not refuse, it picks the default container and announces it (Defaulted container "app" out of: app, preparer (init), attendre-db (init), journal (init)). This output comes from the app Pod of the lesson Init containers and sidecars, which declares two init containers and a native sidecar, all in initContainers, hence the (init) label. To read another container, add -c. The names preparer, attendre-db and journal are in French on purpose, so that the output stays the one produced by the tested cluster (preparer is "prepare", attendre-db is "wait for the database" and journal is "log").

Terminal window
k logs <pod>
k logs <pod> -c <container> # Multi-container
k logs <pod> --previous # After a crash
k logs <pod> -f # Follow in real time
k logs -l app=webapp # All the Pods of a label

The pitfall: after a crash, k logs reads the new instance of the container, whose log is often empty. Add --previous to read the previous instance.

Describe

The part that matters is at the very bottom of the output, in the Events section: this is where Kubernetes explains why it could not do what it was asked.

Terminal window
k describe pod <name>

This command prints the full state of the Pod, then its Events. Run it as soon as a Pod stays in Pending, ImagePullBackOff or CrashLoopBackOff.

Here is how to read a few typical signals:

  • ImagePullBackOff: the image cannot be found or reached;
  • CrashLoopBackOff: the application crashes at startup;
  • FailedScheduling: no node can host the Pod;
  • OOMKilled: the container exceeded its memory limit (the reason is read in Last State of kubectl describe pod).

Cluster events

Events are not sorted by default, hence the --sort-by option, which puts the most recent at the end of the list. They are kept for a limited time only, usually one hour: an old incident will already be gone.

Terminal window
k get events --sort-by='.lastTimestamp'

Exec into a container

Interactive access assumes that the Pod is running and that the image ships a shell, which is not the case for minimal images. Here again, the -- separates the kubectl options from the command to run.

Terminal window
k exec -it <pod> -- /bin/sh
k exec <pod> -- ls -la /app
k exec -it <pod> -c <container> -- /bin/sh # Multi-container

Once inside the container, these three commands give a first overview:

Terminal window
env # Environment variables
cat /etc/resolv.conf # DNS config
wget -qO- localhost:80 # Local test

Application Environment, Configuration and Security (25%)

At 25%, this is the domain that weighs the most in the exam. It covers everything that is injected into a Pod without being in the image: configuration through a ConfigMap, sensitive data through a Secret, and the identity of the Pod through a ServiceAccount. The three objects are created the same way; only their destination changes.

ConfigMap

A ConfigMap stores key/value pairs in clear text. The choice between the two ways of creating one depends on what the application expects: separate environment variables, or a complete configuration file.

Terminal window
# Create from literals
k create cm app-config --from-literal=DB_HOST=mysql --from-literal=LOG_LEVEL=debug
# Create from a file
k create cm app-config --from-file=config.properties
# Check
k describe cm app-config

The choice goes like this: --from-literal for simple values, --from-file for an entire file.

Secret

The generic keyword designates the generic type, the one for key/value pairs; there are others, dedicated to image registries and TLS certificates. kubectl base64-encodes the values for you: do not do it yourself.

Terminal window
k create secret generic db-creds --from-literal=username=admin --from-literal=password=secret123

The pitfall: a Secret is base64-encoded, not encrypted. Anyone who can read it can decode it.

ServiceAccount

A ServiceAccount is the identity under which a Pod talks to the Kubernetes API. Creating the account gives it no permission: you then have to reference it in the Pod and attach a role to it.

Terminal window
k create sa my-sa

Services and Networking (20%)

A Service gives a stable name and address to a set of Pods that themselves come and go. The link between the two is not made by an identifier but by labels: this is where silent network failures hide, because a label mistake raises no message.

Expose a Deployment

expose builds the Service by automatically reusing the labels of the targeted Deployment, which spares you from writing them by hand.

Terminal window
# ClusterIP (default, internal)
k expose deploy webapp --port=80
# NodePort (external through the node port)
k expose deploy webapp --port=80 --type=NodePort
# With a different target-port
k expose deploy webapp --port=8080 --target-port=80

Remember that port is the port of the Service and targetPort is the port of the container.

Check a Service

Seeing the Service exist proves nothing: a Service whose selector matches no Pod is created without error and simply returns refused connections. The useful check is on the endpoints.

Terminal window
k get svc webapp
k get endpointslice -l kubernetes.io/service-name=webapp # See the selected Pods

The pitfall: if the ENDPOINTS column lists no IP address, the labels of the Service match no Pod.

Test a Service from inside the cluster

A ClusterIP Service can only be reached from inside the cluster: you therefore have to run a throwaway Pod there. The --rm option deletes it as soon as the command ends, which avoids leaving test Pods behind.

Terminal window
k run test --image=busybox:1.38.0@sha256:a46257e06c82ad85242d0d38077d0a52d9896389ca60a1a59d3463db586e5fa4 --rm -it -- wget -qO- webapp:80

Exploring the API

The exam gives access to the official documentation, but searching it costs more than querying the cluster. Two commands are enough to find most structural information: explain for the fields of an object, api-resources for the list of objects and their abbreviations.

kubectl explain

The dotted notation walks down the YAML hierarchy and shows, at each level, the expected type and the official description of the field.

Terminal window
k explain pod.spec.containers
k explain pod.spec.containers.livenessProbe
k explain deployment.spec.strategy

This command finds the exact syntax of a field without memorizing it. Run it before writing complex YAML.

Terminal window
# Recursive view + grep
k explain pod.spec --recursive | grep -i volume

api-resources

This command lists all the object types the cluster recognizes, with their abbreviation and their API group. It is also the way to check that an object brought by an extension is actually available.

Terminal window
k api-resources

Remember these abbreviations (short names): po for pods, svc for services, deploy for deployments, cm for configmaps, pvc for persistentvolumeclaims.


Output and filtering

Many questions ask you to extract a single value and write it to a file. The jsonpath format answers exactly this need and avoids any post-processing: it returns the raw value, with no header or formatting. Label filters, for their part, are used to find the objects concerned when the task statement does not give their name.

Terminal window
# Wide view (IP, node)
k get pods -o wide
# Export as YAML
k get pod nginx -o yaml > pod.yaml
# JSONPath
k get pod nginx -o jsonpath='{.status.podIP}'
k get pods -o jsonpath='{.items[*].metadata.name}'
# Filter by label
k get pods -l app=nginx
k get pods -l 'app in (nginx,redis)'
# All namespaces
k get pods -A
# Sort by date
k get pods --sort-by='.metadata.creationTimestamp'

Commands to know by heart

This list is the minimum to type without thinking on exam day. It deliberately fits in ten lines: the first three cover creation, the next three the update, the last four the diagnosis. Everything else can be found with kubectl explain.

Terminal window
k run ... $do # Generate Pod YAML
k create deploy ... $do # Generate Deployment YAML
k expose deploy ... # Create Service
k set image deploy ... # Update image
k rollout status deploy ... # Follow rollout
k rollout undo deploy ... # Rollback
k logs ... --previous # Logs after a crash
k describe pod ... # State + Events
k explain ... # YAML syntax
k get events # Cluster events

Look up quickly in the docs

Do not waste time memorizing these items, find them with kubectl explain or in the docs:

  • Ingress details (k explain ingress.spec)
  • Advanced probe fields (k explain pod.spec.containers.livenessProbe)
  • securityContext options (k explain pod.spec.securityContext)
  • Exact CronJob syntax (k explain cronjob.spec)
  • NetworkPolicy rules (k explain networkpolicy.spec)

Quick troubleshooting

This table links a symptom visible in kubectl get pods to the command that gives the answer. Remember the main dividing line: a Pod stuck before starting is diagnosed with describe, a Pod that started and then stopped is diagnosed with logs.

SymptomCommandLikely cause
Pendingk describe podNo node, requests too high
ImagePullBackOffk describe podImage not found or unreachable
CrashLoopBackOffk logs --previousThe application crashes at startup
Service does not answerk get endpointsliceWrong labels (no Pod selected)
ConfigMap missingk get cmWrong namespace

Key takeaways

  1. $do generates the YAML without creating the object: always start there.
  2. Check the namespace before each question.
  3. kubectl explain gives the syntax: no need to memorize it.
  4. kubectl describe explains why a Pod does not start.
  5. --previous reads the logs of the instance before the crash.
  6. set image then rollout status drive an update; rollout undo goes back.
  7. Labels link a Service or a Deployment to its Pods.
  8. Events give a quick diagnosis of the cluster.

Test your knowledge

Seven questions on the gestures that save time during the exam, and on the commands whose result is not the one you expect.

Knowledge check

Check what you have learned with this interactive quiz

7 questions
6 min
70% 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