Cheatsheets

kubectl

Cheatsheet

kubectl

kubectl is the command-line tool for talking to a Kubernetes cluster. Use it to deploy apps, inspect and manage resources, stream logs, and debug running pods.

7 Categories 18 Sections 26 Examples
kubectl Kubernetes K8s CLI kubeconfig Pods Container Orchestration DevOps

Getting Started

Check your setup, switch between clusters, and find your way around the API.

Setup and Version

Confirm kubectl can reach your cluster, then make the tool faster to type.

Check the client and cluster versions

If the server version is missing, kubectl can't reach the cluster yet. Check your kubeconfig before anything else.

Code
Terminal window
# Show both the kubectl (client) and cluster (server) versions
kubectl version
# Just the client, formatted as YAML
kubectl version --client -o yaml

Turn on autocomplete and a short alias

Autocomplete works for resource names too, not just flags, so you tab-complete pod names. It's the single biggest quality-of-life win.

Code
Terminal window
# Load completion for the current shell (add to ~/.bashrc to keep it)
source <(kubectl completion bash) # use 'zsh' for zsh
# Most people alias kubectl to 'k' since you type it all day
alias k=kubectl

Contexts and Namespaces

A context bundles a cluster, a user, and a namespace. Switching contexts is how you move between clusters.

See where you're pointed and switch clusters

Every command runs against the current context. When something looks wrong, check this first. You might be on the wrong cluster.

Code
Terminal window
# Which contexts exist, and which one is active?
kubectl config get-contexts
kubectl config current-context
# Switch to another cluster/context
kubectl config use-context staging

Set a default namespace so you stop typing -n

Code
Terminal window
# Pin the current context to a namespace
kubectl config set-context --current --namespace=payments
# Override per-command when you need to
kubectl get pods -n kube-system
kubectl get pods -A # -A means all namespaces

Discovering the API

When you forget a field name or a resource's short name, ask the cluster instead of guessing.

Look up resource types and their fields

api-resources is how you learn that 'deployments' is 'deploy' for short and 'services' is 'svc'. explain saves a trip to the docs.

Code
Terminal window
# List every resource type, its short name, and API group
kubectl api-resources
# Read the schema for a field, drilling down with dots
kubectl explain pod.spec.containers

Creating and Applying Resources

Two styles ship work to the cluster, declarative (apply a file) and imperative (run a command). Lean on declarative.

Apply Manifests

Declarative management. You describe the desired state in YAML and let Kubernetes reconcile.

Apply a file, a folder, or a URL

apply creates resources that don't exist and updates the ones that do, so the same command works for the first deploy and every change after.

Code
Terminal window
# A single manifest
kubectl apply -f deployment.yaml
# Every manifest in a directory (great for a whole app)
kubectl apply -f ./k8s/
# Straight from a URL
kubectl apply -f https://example.com/app.yaml

Preview changes before you apply them

diff is your safety net. Run it in CI and in code review so nobody is surprised by what apply actually does.

Code
Terminal window
# Show exactly what would change against the live cluster
kubectl diff -f deployment.yaml
# Validate without touching anything (server-side)
kubectl apply -f deployment.yaml --dry-run=server

Imperative Create

Quick, one-off commands for prototyping or generating starter YAML.

Spin up common resources from the command line

Code
Terminal window
# A deployment from an image
kubectl create deployment web --image=nginx:1.27
# A one-shot job and a scheduled cronjob
kubectl create job backup --image=postgres -- pg_dump mydb
kubectl create cronjob nightly --image=busybox \
--schedule="0 2 * * *" -- /bin/sh -c 'echo run'

Let kubectl write the YAML for you

This is the fastest way to get a correct starting manifest. Generate it, tweak it, and from then on manage it with apply.

Code
Terminal window
# Generate a manifest without creating anything, then edit and commit it
kubectl create deployment web --image=nginx \
--dry-run=client -o yaml > deployment.yaml

Viewing and Finding Resources

get for the quick list, describe for the full story, and output formats for scripting.

Get and Describe

The two commands you'll run more than any other.

List resources, then dig into one

describe is where you find out WHY a pod is stuck. Scroll to the Events section at the bottom first.

Code
Terminal window
# A quick list, then the same list with node and IP columns
kubectl get pods
kubectl get pods -o wide
# The full picture: events, conditions, and recent state changes
kubectl describe pod web-7d9f

Watch resources change in real time

Code
Terminal window
# Refresh the list as things change (Ctrl-C to stop)
kubectl get pods -w
# Combine resource types in one call
kubectl get deploy,svc,pods

Output Formats

Reshape output for humans or for scripts with -o.

Pull out exactly the fields you need

JSONPath and custom-columns let you script against kubectl without piping through jq. Great for CI checks and quick reports.

Code
Terminal window
# The whole object as YAML (handy for copying spec fields)
kubectl get pod web -o yaml
# Just the names, one per line, via JSONPath
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
# Your own table with custom columns
kubectl get pods \
-o custom-columns='NAME:.metadata.name,NODE:.spec.nodeName'

Filtering and Sorting

Narrow a long list down to the resources you actually care about.

Filter by label, field, and sort the results

Label selectors are the same ones your Services and Deployments use, so filtering with -l mirrors how Kubernetes wires things together.

Code
Terminal window
# Only pods with a matching label
kubectl get pods -l app=web,tier=frontend
# Only pods that are actually running
kubectl get pods --field-selector=status.phase=Running
# Sort by how many times each pod has restarted
kubectl get pods \
--sort-by='.status.containerStatuses[0].restartCount'

Updating Resources

Roll out new versions, scale up and down, and tweak live objects.

Rollouts

Ship a new image and control or undo the rollout if it goes wrong.

Update an image and watch the rollout

A Deployment rolls out gradually, replacing old pods with new ones, so users keep getting served while the update happens.

Code
Terminal window
# Change the container image, which triggers a rolling update
kubectl set image deployment/web web=nginx:1.27.1
# Follow the rollout until it finishes (or fails)
kubectl rollout status deployment/web

Roll back a bad release

undo is your fast path out of a broken deploy. It's much quicker than editing the image back by hand under pressure.

Code
Terminal window
# See past revisions
kubectl rollout history deployment/web
# Go back to the previous version
kubectl rollout undo deployment/web
# Or jump to a specific revision
kubectl rollout undo deployment/web --to-revision=3

Scaling

Add or remove replicas, by hand or automatically.

Scale manually or set up autoscaling

autoscale creates a HorizontalPodAutoscaler. It needs the metrics-server running in the cluster to read CPU usage.

Code
Terminal window
# Run four copies of the app
kubectl scale deployment/web --replicas=4
# Or let Kubernetes scale on CPU between 2 and 10 replicas
kubectl autoscale deployment/web --min=2 --max=10 --cpu-percent=70

Labels and Patches

Make small, targeted changes to a live resource without re-applying the whole file.

Add labels and patch a single field

Use patch for scripted, surgical edits. Use 'kubectl edit' when you'd rather open the live object in your editor and change it by hand.

Code
Terminal window
# Tag a pod with a label (use --overwrite to change an existing one)
kubectl label pod web-7d9f environment=prod
# Change one field with a strategic merge patch
kubectl patch deployment/web \
-p '{"spec":{"replicas":5}}'

Interacting With Pods

Read logs, run commands inside containers, reach a pod from your laptop, and debug.

Logs

The first place to look when an app misbehaves.

Read and stream logs

--previous is the one people forget. After a crash loop, it shows the logs from the container that just died, which is exactly what you need.

Code
Terminal window
# Stream logs live (-f), only the last 100 lines to start
kubectl logs -f web-7d9f --tail=100
# Pick a container in a multi-container pod
kubectl logs web-7d9f -c sidecar
# Logs from the previous container after a crash/restart
kubectl logs web-7d9f --previous

Exec and Debug

Get a shell or a one-off command inside a container, or attach a debug container.

Run a command or open a shell inside a pod

Everything after -- runs inside the container. Use /bin/sh if /bin/bash isn't there, since slim images often ship without bash.

Code
Terminal window
# One-off command
kubectl exec web-7d9f -- env
# Interactive shell (-it = interactive + TTY)
kubectl exec -it web-7d9f -- /bin/sh

Debug a pod that has no shell at all

kubectl debug adds an ephemeral container that shares the target's namespaces, so you can inspect a distroless image that has no shell of its own.

Code
Terminal window
# Attach a temporary debug container with full tools
kubectl debug -it web-7d9f \
--image=busybox --target=web
# Or launch a throwaway pod to poke the network
kubectl run tmp --rm -it --image=busybox -- sh

Port-Forward and Copy

Reach a pod directly from your machine and move files in or out.

Tunnel a local port and copy files

port-forward is perfect for poking an internal service or a database without exposing it to the world.

Code
Terminal window
# Open localhost:8080 straight to the pod's port 80
kubectl port-forward pod/web-7d9f 8080:80
# Forward to whatever pod a Service points at
kubectl port-forward svc/web 8080:80
# Copy a file out of a pod (tar must exist in the container)
kubectl cp default/web-7d9f:/var/log/app.log ./app.log

Resource Usage

See which pods and nodes are actually using CPU and memory.

Check live CPU and memory

top needs the metrics-server add-on. If it errors out, that component probably isn't installed in the cluster.

Code
Terminal window
# Usage per node and per pod
kubectl top nodes
kubectl top pods --all-namespaces

Cluster and Node Management

Inspect the cluster as a whole and safely take nodes out of service for maintenance.

Cluster Info

A quick health read on the control plane and nodes.

Look at the cluster and recent events

A cluster-wide events list is gold during an incident. It often points straight at the failing component.

Code
Terminal window
# Control plane endpoints
kubectl cluster-info
# Node list with readiness and versions
kubectl get nodes -o wide
# Recent events across the cluster, newest last
kubectl get events --sort-by=.metadata.creationTimestamp

Node Maintenance

Drain a node before you patch or reboot it, then bring it back.

Safely take a node down and bring it back

drain moves pods off the node gracefully so workloads keep running elsewhere. Always cordon or drain before a reboot.

Code
Terminal window
# Stop scheduling new pods here
kubectl cordon node-1
# Evict the existing pods (skip DaemonSet-managed ones)
kubectl drain node-1 --ignore-daemonsets --delete-emptydir-data
# ...do your maintenance, then allow scheduling again
kubectl uncordon node-1

Handy One-Liners

A few commands worth keeping in your back pocket.

Useful Patterns

Small recipes that come up again and again.

Decode a Secret without leaving the terminal

Secret values are only base64-encoded, not encrypted at rest by default, so anyone with get access can read them. Lock down RBAC accordingly.

Code
Terminal window
# Secrets are base64-encoded; decode one value
kubectl get secret db-creds \
-o jsonpath='{.data.password}' | base64 -d

Force-delete a pod stuck in Terminating

Use this sparingly. It tells the API to forget the pod immediately even if the node never confirmed it stopped, which can leave orphaned processes if the node is actually alive.

Code
Terminal window
# Last resort when a pod won't go away
kubectl delete pod web-7d9f --grace-period=0 --force
Related Posts

You might also enjoy

Check out some of our other posts on similar topics

Kubernetes

Kubernetes Kubernetes is the de facto standard for container orchestration. It automates deployment, scaling, and management of containerized applications across clusters of machines, providing dec

Helm

Helm Helm is the package manager for Kubernetes that simplifies the deployment, management, and upgrade of applications. It uses charts templated Kubernetes manifests to enable reusable, configurab

Docker Swarm

Docker Swarm Cheatsheet This cheatsheet provides a comprehensive reference for managing Docker Swarm clusters, services, and stacks. It covers essential commands and best practices for scaling, upd

Docker

Docker Docker is a containerization platform that packages applications with their dependencies into isolated, portable environments called containers. It enables developers to build, ship, and run

Terraform Cheatsheet

Terraform Cheatsheet A practical cheatsheet covering the Terraform CLI commands engineers reach for constantly — init, plan, apply, import, taint, and state operations — alongside essential HCL pat

YAML

YAML YAML (YAML Ain't Markup Language) is a human-friendly data serialization language widely used for configuration files, data exchange, and infrastructure-as-code. It emphasizes readability and

6 related posts