Skip to content
AkOps Labs
Playgrounds

Kubernetes

Deploy, scale and fix apps on a real-looking cluster with kubectl.

18 levels · 101 lessons · about 3 hours

Kubernetes commands cheat sheet

Every command in the Kubernetes Playground, grouped by level. Practise each one above in the interactive terminal.

Show all 101 commands

Level 1: Meet the Cluster (Beginner)

Talk to a cluster and see what's running.

Cluster info
kubectl cluster-info

kubectl is the command-line tool for Kubernetes. cluster-info shows where the control plane is.

List the nodes
kubectl get nodes

Nodes are the machines (VMs) that run your containers.

List namespaces
kubectl get namespaces

Namespaces split one cluster into separate areas, e.g. dev and prod.

List pods
kubectl get pods

A pod is the smallest unit in Kubernetes - one or more containers running together.

Pods everywhere
kubectl get pods -A

-A (all namespaces) shows pods from every namespace at once.

Level 2: Deploy an App (Beginner)

Create a deployment, expose it and apply YAML.

Create a deployment
kubectl create deployment web --image=nginx

A Deployment keeps a set of identical pods running and replaces them if they die.

List deployments
kubectl get deployments

READY shows how many pods are up out of how many you asked for.

Expose it with a Service
kubectl expose deployment web --port=80

Pods come and go, so a Service gives them one stable address and load-balances traffic.

List services
kubectl get services

svc is the short name for services.

Apply a YAML file
kubectl apply -f deployment.yaml

In real teams everything lives in YAML files in Git. kubectl apply -f creates or updates what the file describes.

Level 3: Debug Like an SRE (Intermediate)

Find out why a pod is broken.

Describe a pod
kubectl describe pod api-5f7d9c8b6-x2k1

describe shows a pod's full details and, most importantly, its recent Events.

Read pod logs
kubectl logs api-5f7d9c8b6-x2k1

kubectl logs prints what the container wrote to stdout - usually the real error.

Shell into a pod
kubectl exec -it api-5f7d9c8b6-x2k1 -- sh

kubectl exec -it runs an interactive command inside a pod. Everything after -- runs in the container.

Check cluster events
kubectl get events

get events lists recent warnings across the namespace - great for scheduling and image-pull problems.

Test it from your laptop
kubectl port-forward svc/web 8080:80

port-forward tunnels a local port to a service in the cluster, without exposing it publicly.

Level 4: Scale & Release (Intermediate)

Scale up, ship new versions and roll back safely.

Scale out
kubectl scale deployment web --replicas=5

scale changes how many pod replicas a deployment runs.

Ship a new version
kubectl set image deployment/web nginx=nginx:1.27

set image changes the container image, which triggers a rolling update with zero downtime.

Watch the rollout
kubectl rollout status deployment/web

rollout status waits until the new version is fully running (or tells you it's stuck).

See release history
kubectl rollout history deployment/web

Every change creates a revision you can roll back to.

Roll back!
kubectl rollout undo deployment/web

rollout undo switches back to the previous revision - the fastest fix for a bad release.

Clean up
kubectl delete deployment web

kubectl delete removes resources. Deleting a deployment also removes its pods.

Level 5: Production Ready (Intermediate)

Config, secrets, autoscaling, permissions and node maintenance.

Which cluster am I on?
kubectl config get-contexts

A context = cluster + user + namespace. Always check it before running commands, so you don't hit prod by mistake.

Store config
kubectl create configmap app-config --from-literal=ENV=prod

A ConfigMap holds non-secret settings (like ENV=prod) that pods read as env vars or files.

Store a secret
kubectl create secret generic db-pass --from-literal=password=s3cret

A Secret holds passwords and tokens. generic makes one from key=value pairs.

CPU & memory per pod
kubectl top pods

kubectl top shows live CPU and memory use. It needs metrics-server installed in the cluster.

Autoscale
kubectl autoscale deployment web --min=2 --max=10 --cpu-percent=70

A HorizontalPodAutoscaler adds or removes pods based on CPU. You set min, max and the target CPU %.

Check permissions
kubectl auth can-i delete pods

RBAC controls who can do what. auth can-i answers yes or no for your current user.

Drain a node
kubectl drain worker-2 --ignore-daemonsets

Before patching a node, drain moves its pods to other nodes and stops new ones landing there.

Level 6: Storage & Config (Advanced)

Keep data when pods restart and reload config safely.

See the storage classes
kubectl get storageclass

A StorageClass says what kind of disk the cluster can create, for example fast SSD on AWS (gp3). Claims ask for a class.

Ask for a disk
kubectl apply -f pvc.yaml

A PersistentVolumeClaim (PVC) asks for storage, like 'give me 10Gi'. Kubernetes creates the disk and the pod mounts it.

Check the claim
kubectl get pvc

STATUS Bound means a real disk is attached to the claim. Pending often means no pod uses it yet, or no class matches.

See the real disks
kubectl get pv

PersistentVolumes (PV) are the actual disks. Each Bound PVC points to one.

Reload new config
kubectl rollout restart deployment/web

Pods read ConfigMaps and Secrets when they start. After changing one, rollout restart replaces the pods one by one with no downtime.

Level 7: Networking & Ingress (Advanced)

Route web traffic into the cluster and debug connections between services.

List the ingress rules
kubectl get ingress

An Ingress routes outside HTTP traffic to Services by host name and path, through one load balancer.

Read an ingress
kubectl describe ingress web

describe shows each rule (host, path and backend service) and the TLS certificate in use.

Is the Service connected to pods?
kubectl get endpoints web

A Service only sends traffic to pods whose labels match its selector. If ENDPOINTS is empty, the labels do not match. A very common bug.

Test from inside the cluster
kubectl run tmp --rm -it --image=busybox -- sh

A throwaway busybox pod lets you test DNS and connections exactly as other pods see them. --rm deletes it when you exit.

Check network policies
kubectl get networkpolicy

NetworkPolicies are firewalls between pods. If a policy exists, only the traffic it allows gets through.

Level 8: Cluster Admin (Advanced)

Do the tasks of a cluster administrator: node maintenance, scheduling rules, access and Helm.

Stop new pods on a node
kubectl cordon worker-2

cordon marks a node unschedulable. Running pods stay, but no new pods go there. Step one of node maintenance.

Put the node back
kubectl uncordon worker-2

After maintenance, uncordon lets the scheduler use the node again.

Reserve a node with a taint
kubectl taint nodes worker-1 gpu=true:NoSchedule

A taint keeps pods away from a node unless they have a matching toleration. Used for GPU nodes or dedicated workloads.

An identity for a pipeline
kubectl create serviceaccount deployer

A ServiceAccount is an identity for an app or a CI pipeline inside the cluster.

Give it permissions
kubectl create rolebinding deployer-edit --clusterrole=edit --serviceaccount=default:deployer

A RoleBinding gives a role to someone in one namespace. The built-in edit role can change most resources but not permissions.

Install an app with Helm
helm install web bitnami/nginx

Helm is the package manager for Kubernetes. One command installs a whole app (deployments, services, config) from a chart.

Level 9: Namespaces & Contexts (Advanced)

Split one cluster into teams and environments, and switch between clusters safely.

Create a namespace
kubectl create namespace staging

A namespace is a separate space in the cluster: staging and prod apps can have the same names without clashing.

Look in a namespace
kubectl get pods -n staging

-n picks the namespace for one command.

Change the default namespace
kubectl config set-context --current --namespace=staging

Set the namespace on your current context so you don't type -n every time.

Switch clusters
kubectl config use-context prod

A context is a cluster plus a user plus a namespace. Always check which one you're on before deleting anything.

See everything in a namespace
kubectl get all -n staging

get all lists the common resources at once.

Level 10: Resources & Probes (Advanced)

Give pods the right CPU and memory, and let Kubernetes know when they're healthy.

Set requests and limits
kubectl set resources deployment web --requests=cpu=100m,memory=128Mi --limits=cpu=500m,memory=256Mi

Requests are what the scheduler reserves. Limits are the maximum. A pod over its memory limit is OOMKilled.

How full is a node?
kubectl describe node worker-1

describe node shows how much of the node's CPU and memory is already requested.

Learn a field from the cluster
kubectl explain pod.spec.containers.livenessProbe

kubectl explain is built-in documentation for every field. No browser needed in an exam.

Count restarts
kubectl get pod api-5f7d9c8b6-x2k1 -o jsonpath='{.status.containerStatuses[0].restartCount}'

jsonpath pulls one value out of the object. Many restarts mean a failing liveness probe or a crash.

Is the pod ready?
kubectl get pods -o wide

Readiness decides if a pod gets traffic. READY 0/1 means the readiness probe is failing: the Service skips this pod.

Level 11: Jobs & CronJobs (Expert)

Run one-off tasks and scheduled tasks like backups and reports.

Run a one-off job
kubectl create job backup --image=busybox -- echo done

A Job runs a pod until the task finishes successfully, then stops.

Did it finish?
kubectl get jobs

COMPLETIONS 1/1 means it succeeded.

Read its output
kubectl logs job/backup

You can read logs straight from the job.

Schedule it every night
kubectl create cronjob nightly --image=busybox --schedule="0 2 * * *" -- echo backup

A CronJob creates a Job on a schedule, using cron syntax. 0 2 * * * is 02:00 every day.

Run it now
kubectl create job manual-run --from=cronjob/nightly

Test a CronJob without waiting for 2am by creating a Job from it.

Level 12: StatefulSets & DaemonSets (Expert)

Run databases with stable names and storage, and one agent on every node.

List StatefulSets
kubectl get statefulsets

A StatefulSet gives each pod a stable name (db-0, db-1) and its own volume. Used for databases and queues.

Add replicas
kubectl scale statefulset db --replicas=3

StatefulSet pods start one at a time, in order: db-1 waits until db-0 is ready.

Find pods by label
kubectl get pods -l app=db

-l selects by label. Services and Deployments find their pods the same way.

One volume per pod
kubectl get pvc

Each db pod gets its own PersistentVolumeClaim from the volumeClaimTemplate.

One pod on every node
kubectl get daemonsets -n kube-system

A DaemonSet runs one pod per node: log collectors, monitoring agents, network plugins.

Level 13: Helm Charts (Expert)

Install, configure, upgrade and roll back apps with Helm, the Kubernetes package manager.

Add a chart repo
helm repo add bitnami https://charts.bitnami.com/bitnami

A Helm repo is a catalogue of charts (packaged apps).

Update the catalogue
helm repo update

Like apt update: download the latest list of chart versions.

Find a chart
helm search repo redis

Search the repos you added.

See the settings
helm show values bitnami/redis

show values prints every setting a chart accepts. Copy the ones you change into your own values.yaml.

Install with your values
helm install cache bitnami/redis -f values.yaml

-f applies your values file. A release is one installed copy of a chart.

Upgrade a setting
helm upgrade cache bitnami/redis -f values.yaml --set replica.replicaCount=2

upgrade changes a release. --set overrides one value. Each upgrade is a new revision.

Roll back
helm rollback cache 1

If an upgrade breaks things, go back to a revision. helm history shows them all.

Level 14: Monitoring: Prometheus & Grafana (Expert)

Install Prometheus and Grafana with Helm, open the dashboards and query metrics.

Add the community charts
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts

prometheus-community has the official charts for Prometheus.

Install the full stack
helm install monitoring prometheus-community/kube-prometheus-stack -n monitoring --create-namespace

kube-prometheus-stack installs Prometheus, Alertmanager, Grafana, node-exporter and ready-made dashboards in one go.

Check it's running
kubectl get pods -n monitoring

You should see Prometheus, Alertmanager, Grafana, the operator and one node-exporter per node.

Get the Grafana password
kubectl get secret monitoring-grafana -n monitoring -o jsonpath='{.data.admin-password}' | base64 -d

The chart stores the admin password in a secret. Secrets are base64-encoded, so decode it.

Open Grafana
kubectl port-forward -n monitoring svc/monitoring-grafana 3000:80

port-forward gives you Grafana on localhost:3000. Log in as admin and open Dashboards → Kubernetes / Compute Resources.

Open Prometheus
kubectl port-forward -n monitoring svc/monitoring-kube-prometheus-prometheus 9090

Prometheus listens on 9090. Try the query up, or rate(container_cpu_usage_seconds_total[5m]).

Add an alert rule
kubectl apply -f high-cpu-rule.yaml

A PrometheusRule is a Kubernetes object holding alert rules. The operator loads it into Prometheus automatically.

Level 15: Troubleshoot Broken Pods (Expert)

Find and fix the 4 pod problems you'll see at work: CrashLoopBackOff, ImagePullBackOff, OOMKilled and Pending.

Spot the broken pods
kubectl get pods

Read the STATUS column first. Each status points to a different cause.

Why does it crash?
kubectl logs api-5f7d9c8b6-x2k1 --previous

CrashLoopBackOff: the app starts and exits. --previous shows the logs of the container that just died.

Why can't it pull?
kubectl describe pod web-7c9d8f6b5-m3n4b

ImagePullBackOff: wrong image name or tag, or a private registry without imagePullSecrets. The Events at the bottom say which.

Fix the image
kubectl set image deployment/web nginx=nginx:1.27

Set the correct tag. The Deployment rolls out new pods.

Why OOMKilled?
kubectl get pod worker-6d5c4b3a2-z9y8 -o jsonpath='{.status.containerStatuses[0].lastState.terminated.reason}'

OOMKilled: the container used more memory than its limit. Check the last state, then raise the limit or fix the leak.

Why Pending?
kubectl get events --sort-by=.lastTimestamp

Pending: the scheduler can't place it. Usually not enough CPU or memory, a taint, or a PVC that won't bind. Recent events tell you.

Level 16: Security & RBAC (Expert)

Give people and apps only the access they need, and lock pods down.

Make a read-only role
kubectl create role pod-reader --verb=get,list --resource=pods

A Role lists allowed verbs on resources in one namespace.

Give it to a user
kubectl create rolebinding read-pods --role=pod-reader --user=alex

A RoleBinding links a role to a user, group or service account.

Test as that user
kubectl auth can-i delete pods --as=alex

--as checks permissions as someone else. Always test RBAC before you hand it over.

Enforce pod security
kubectl label namespace web pod-security.kubernetes.io/enforce=restricted

Pod Security labels on a namespace block risky pods, like ones running as root or privileged.

Block all traffic by default
kubectl apply -f deny-all.yaml

A default-deny NetworkPolicy stops all traffic into the namespace. Then allow only what's needed.

Read a secret safely
kubectl get secret db-pass -o jsonpath='{.data.password}' | base64 -d

Secrets are only base64-encoded, not encrypted. Anyone who can get secrets can read them, so restrict that verb.

Level 17: Upgrades & Backups (Expert)

Upgrade a cluster without downtime and back up etcd, the cluster's database.

Check the versions
kubectl version

Client and server versions should be within one minor version of each other.

Plan the upgrade
sudo kubeadm upgrade plan

kubeadm upgrade plan shows which versions you can upgrade to and checks the cluster first.

Upgrade the control plane
sudo kubeadm upgrade apply v1.31.2

Upgrade one minor version at a time, control plane first, then each worker.

Empty a worker first
kubectl drain worker-1 --ignore-daemonsets --delete-emptydir-data

Drain moves the pods off a node before you upgrade it. emptyDir data is lost, so you must allow it.

Back up etcd
ETCDCTL_API=3 etcdctl snapshot save /backup/etcd.db

etcd holds every object in the cluster. A snapshot is your disaster recovery plan, and a CKA exam favourite.

Check the backup
etcdctl snapshot status /backup/etcd.db --write-out=table

Always verify a backup.

Level 18: Kustomize & GitOps-Ready YAML (Expert)

Keep one base config and small overlays per environment, ready for GitOps.

Render an overlay
kubectl kustomize overlays/prod

Kustomize builds YAML from a base plus an overlay (prod: more replicas, other image tag). Nothing is applied yet.

See what would change
kubectl diff -k overlays/prod

kubectl diff compares the cluster with your files. Review it like a terraform plan.

Apply the overlay
kubectl apply -k overlays/prod

-k applies a kustomization folder.

Record why it changed
kubectl annotate deployment web kubernetes.io/change-cause="release v1.2.0"

The change-cause annotation shows up in rollout history, so everyone knows what each revision was.

Export clean YAML
kubectl get deployment web -o yaml > web.yaml

Save what's running as a file to put in Git. Remove status and generated fields before committing.