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 commandsHide commands
Level 1: Meet the Cluster (Beginner)
Talk to a cluster and see what's running.
- Cluster info
kubectl cluster-infokubectl is the command-line tool for Kubernetes. cluster-info shows where the control plane is.
- List the nodes
kubectl get nodesNodes are the machines (VMs) that run your containers.
- List namespaces
kubectl get namespacesNamespaces split one cluster into separate areas, e.g. dev and prod.
- List pods
kubectl get podsA 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=nginxA Deployment keeps a set of identical pods running and replaces them if they die.
- List deployments
kubectl get deploymentsREADY shows how many pods are up out of how many you asked for.
- Expose it with a Service
kubectl expose deployment web --port=80Pods come and go, so a Service gives them one stable address and load-balances traffic.
- List services
kubectl get servicessvc is the short name for services.
- Apply a YAML file
kubectl apply -f deployment.yamlIn 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-x2k1describe shows a pod's full details and, most importantly, its recent Events.
- Read pod logs
kubectl logs api-5f7d9c8b6-x2k1kubectl logs prints what the container wrote to stdout - usually the real error.
- Shell into a pod
kubectl exec -it api-5f7d9c8b6-x2k1 -- shkubectl exec -it runs an interactive command inside a pod. Everything after -- runs in the container.
- Check cluster events
kubectl get eventsget 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:80port-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=5scale changes how many pod replicas a deployment runs.
- Ship a new version
kubectl set image deployment/web nginx=nginx:1.27set image changes the container image, which triggers a rolling update with zero downtime.
- Watch the rollout
kubectl rollout status deployment/webrollout status waits until the new version is fully running (or tells you it's stuck).
- See release history
kubectl rollout history deployment/webEvery change creates a revision you can roll back to.
- Roll back!
kubectl rollout undo deployment/webrollout undo switches back to the previous revision - the fastest fix for a bad release.
- Clean up
kubectl delete deployment webkubectl 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-contextsA 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=prodA 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=s3cretA Secret holds passwords and tokens. generic makes one from key=value pairs.
- CPU & memory per pod
kubectl top podskubectl 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=70A HorizontalPodAutoscaler adds or removes pods based on CPU. You set min, max and the target CPU %.
- Check permissions
kubectl auth can-i delete podsRBAC controls who can do what. auth can-i answers yes or no for your current user.
- Drain a node
kubectl drain worker-2 --ignore-daemonsetsBefore 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 storageclassA 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.yamlA PersistentVolumeClaim (PVC) asks for storage, like 'give me 10Gi'. Kubernetes creates the disk and the pod mounts it.
- Check the claim
kubectl get pvcSTATUS 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 pvPersistentVolumes (PV) are the actual disks. Each Bound PVC points to one.
- Reload new config
kubectl rollout restart deployment/webPods 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 ingressAn Ingress routes outside HTTP traffic to Services by host name and path, through one load balancer.
- Read an ingress
kubectl describe ingress webdescribe shows each rule (host, path and backend service) and the TLS certificate in use.
- Is the Service connected to pods?
kubectl get endpoints webA 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 -- shA 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 networkpolicyNetworkPolicies 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-2cordon 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-2After maintenance, uncordon lets the scheduler use the node again.
- Reserve a node with a taint
kubectl taint nodes worker-1 gpu=true:NoScheduleA 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 deployerA 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:deployerA 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/nginxHelm 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 stagingA 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=stagingSet the namespace on your current context so you don't type -n every time.
- Switch clusters
kubectl config use-context prodA 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 stagingget 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=256MiRequests 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-1describe 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.livenessProbekubectl 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 wideReadiness 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 doneA Job runs a pod until the task finishes successfully, then stops.
- Did it finish?
kubectl get jobsCOMPLETIONS 1/1 means it succeeded.
- Read its output
kubectl logs job/backupYou can read logs straight from the job.
- Schedule it every night
kubectl create cronjob nightly --image=busybox --schedule="0 2 * * *" -- echo backupA 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/nightlyTest 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 statefulsetsA 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=3StatefulSet 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 pvcEach db pod gets its own PersistentVolumeClaim from the volumeClaimTemplate.
- One pod on every node
kubectl get daemonsets -n kube-systemA 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/bitnamiA Helm repo is a catalogue of charts (packaged apps).
- Update the catalogue
helm repo updateLike apt update: download the latest list of chart versions.
- Find a chart
helm search repo redisSearch the repos you added.
- See the settings
helm show values bitnami/redisshow 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=2upgrade changes a release. --set overrides one value. Each upgrade is a new revision.
- Roll back
helm rollback cache 1If 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-chartsprometheus-community has the official charts for Prometheus.
- Install the full stack
helm install monitoring prometheus-community/kube-prometheus-stack -n monitoring --create-namespacekube-prometheus-stack installs Prometheus, Alertmanager, Grafana, node-exporter and ready-made dashboards in one go.
- Check it's running
kubectl get pods -n monitoringYou 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 -dThe 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:80port-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 9090Prometheus 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.yamlA 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 podsRead the STATUS column first. Each status points to a different cause.
- Why does it crash?
kubectl logs api-5f7d9c8b6-x2k1 --previousCrashLoopBackOff: 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-m3n4bImagePullBackOff: 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.27Set 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=.lastTimestampPending: 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=podsA Role lists allowed verbs on resources in one namespace.
- Give it to a user
kubectl create rolebinding read-pods --role=pod-reader --user=alexA 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=restrictedPod 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.yamlA 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 -dSecrets 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 versionClient and server versions should be within one minor version of each other.
- Plan the upgrade
sudo kubeadm upgrade plankubeadm upgrade plan shows which versions you can upgrade to and checks the cluster first.
- Upgrade the control plane
sudo kubeadm upgrade apply v1.31.2Upgrade one minor version at a time, control plane first, then each worker.
- Empty a worker first
kubectl drain worker-1 --ignore-daemonsets --delete-emptydir-dataDrain 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.dbetcd 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=tableAlways 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/prodKustomize 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/prodkubectl 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.yamlSave what's running as a file to put in Git. Remove status and generated fields before committing.