kubectl is the command-line tool that talks to a Kubernetes cluster. It sends your requests to the cluster's API server, which creates, changes and reads objects like pods, deployments and services. This page lists the commands you need most, with examples. Run kubectl <command> --help for every option, and kubectl explain <resource> to see the fields of any object.
Setup and Shortcuts
kubectl version # client and server versions
kubectl cluster-info # address of the API server
alias k=kubectl # save typing: k get pods
source <(kubectl completion bash) # tab completion in bash (zsh: completion zsh)Most resources have short names, so you can type less:
| Resource | Short name |
|---|---|
pods |
po |
services |
svc |
deployments |
deploy |
replicasets |
rs |
namespaces |
ns |
nodes |
no |
configmaps |
cm |
persistentvolumeclaims |
pvc |
ingresses |
ing |
serviceaccounts |
sa |
kubectl api-resources lists every resource type the cluster knows, with its short name.
Contexts and Namespaces
A context is a saved cluster, user and default namespace in your kubeconfig file (~/.kube/config by default). A namespace is a folder inside a cluster that groups resources, like dev and prod.
kubectl config get-contexts # list contexts, * marks the current one
kubectl config current-context # which cluster am I talking to?
kubectl config use-context staging # switch cluster
kubectl config set-context --current --namespace=shop # change the default namespace
kubectl get namespaces
kubectl create namespace shop
kubectl get pods -n shop # one namespace
kubectl get pods -A # all namespaces (--all-namespaces)Check the current context before you delete or apply anything. Running a command against production by mistake is one of the most common Kubernetes accidents.
Getting Information
kubectl get pods # pods in the current namespace
kubectl get pods -o wide # plus node and pod IP
kubectl get pods --show-labels
kubectl get pods -l app=web # filter by label
kubectl get pods --field-selector status.phase=Running
kubectl get pods -w # watch for changes
kubectl get deploy,svc,pods # several types at once
kubectl get all # common types (not config maps or secrets)
kubectl get nodes
kubectl describe pod web-7d4b9c-x2kfp # details and recent events
kubectl describe node worker-1
kubectl get events --sort-by=.metadata.creationTimestampdescribe is where to look first when something is wrong: the Events at the bottom say why a pod can't be scheduled, can't pull its image or keeps restarting.
Output Formats
| Flag | Shows |
|---|---|
-o wide |
Extra columns like node and IP |
-o yaml |
The full object as YAML |
-o json |
The full object as JSON |
-o name |
Only type/name, handy in scripts |
-o jsonpath='{.items[*].metadata.name}' |
Chosen fields |
-o custom-columns=NAME:.metadata.name,... |
Your own table |
--sort-by=.status.startTime |
Rows sorted by a field |
# Image of every pod
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.containers[*].image}{"\n"}{end}'
# Save a live object as a starting point for a file
kubectl get deploy web -o yaml > web.yamlCreating and Applying
Kubernetes works best declaratively: you write the state you want in YAML files and apply them. Kubernetes then makes the cluster match.
kubectl apply -f web.yaml # create or update from a file
kubectl apply -f k8s/ # every file in a folder
kubectl apply -k overlays/prod # a kustomize folder
kubectl diff -f web.yaml # what would change, before applying
kubectl delete -f web.yaml # delete what the file describescreate only creates and fails if the object already exists. apply creates or updates, so you can run it again and again. Use apply for files you keep in Git.
Quick objects without writing YAML first:
kubectl create deployment web --image=nginx:1.27 --replicas=3
kubectl expose deployment web --port=80 --target-port=8080 --type=ClusterIP
kubectl run tmp --image=busybox:1.36 --rm -it --restart=Never -- sh # throwaway pod
# Generate YAML instead of creating the object
kubectl create deployment web --image=nginx:1.27 --dry-run=client -o yaml > web.yamlA Minimal Deployment and Service
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
spec:
replicas: 3
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: web
image: nginx:1.27
ports:
- containerPort: 80
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
memory: 256Mi
---
apiVersion: v1
kind: Service
metadata:
name: web
spec:
selector:
app: web
ports:
- port: 80
targetPort: 80The service finds its pods through the labels: selector must match the labels in the pod template. When a service has no endpoints, a label that doesn't match is the usual cause.
Deployments, Rollouts and Scaling
kubectl set image deploy/web web=nginx:1.28 # container "web" gets a new image
kubectl rollout status deploy/web # wait until the rollout finishes
kubectl rollout history deploy/web
kubectl rollout undo deploy/web # back to the previous version
kubectl rollout undo deploy/web --to-revision=2
kubectl rollout restart deploy/web # restart every pod, one by one
kubectl rollout pause deploy/web
kubectl rollout resume deploy/web
kubectl scale deploy/web --replicas=5
kubectl autoscale deploy/web --min=2 --max=10 --cpu-percent=70 # creates an HPA
kubectl get hparollout restart is the clean way to make pods pick up a changed config map or secret that they read at startup.
Logs
kubectl logs web-7d4b9c-x2kfp # logs of a pod
kubectl logs -f web-7d4b9c-x2kfp # follow, like tail -f
kubectl logs web-7d4b9c-x2kfp -c sidecar # one container of the pod
kubectl logs web-7d4b9c-x2kfp --previous # the container that crashed before
kubectl logs deploy/web # one pod of the deployment
kubectl logs -l app=web --tail=50 # last 50 lines of every matching pod
kubectl logs web-7d4b9c-x2kfp --since=15mFor a pod in CrashLoopBackOff, the current container has often only just started: --previous shows the logs of the run that crashed.
Exec, Port-Forward and Copy
kubectl exec -it web-7d4b9c-x2kfp -- sh # shell inside the container
kubectl exec web-7d4b9c-x2kfp -- env # run one command
kubectl exec -it deploy/web -c web -- bash
kubectl port-forward pod/web-7d4b9c-x2kfp 8080:80 # localhost:8080 -> pod port 80
kubectl port-forward svc/web 8080:80 # through a service
kubectl port-forward svc/postgres 5432:5432 -n data
kubectl cp web-7d4b9c-x2kfp:/app/logs/app.log ./app.log # needs tar in the container
kubectl cp ./config.json web-7d4b9c-x2kfp:/tmp/config.jsonThe -- separates kubectl's own flags from the command to run in the container.
Config Maps and Secrets
kubectl create configmap app-config --from-literal=LOG_LEVEL=debug --from-file=settings.json
kubectl get cm app-config -o yaml
kubectl create secret generic db-pass --from-literal=password='s3cr3t'
kubectl create secret docker-registry regcred --docker-server=ghcr.io \
--docker-username=me --docker-password="$TOKEN"
kubectl get secret db-pass -o jsonpath='{.data.password}' | base64 -dSecret values are only base64-encoded, not encrypted: anyone who can read the secret can decode it. Limit access with RBAC and turn on encryption at rest in the cluster.
Labels and Annotations
kubectl label pod web-7d4b9c-x2kfp tier=frontend
kubectl label pod web-7d4b9c-x2kfp tier- # remove a label
kubectl annotate deploy web owner=team-shop
kubectl get pods -l 'env in (dev,staging),tier!=db'Labels are for selecting objects (services, deployments and -l use them). Annotations hold other notes, read by tools and people.
Editing and Patching
kubectl edit deploy/web # opens the live object in $EDITOR
kubectl patch deploy web -p '{"spec":{"replicas":2}}'
kubectl replace -f web.yaml # swap the whole objectChanges made with edit or patch aren't in your files. The next kubectl apply from Git can undo them, so change the files too.
Deleting
kubectl delete pod web-7d4b9c-x2kfp # the deployment creates a new one
kubectl delete deploy web
kubectl delete pods -l app=web
kubectl delete namespace shop # deletes everything inside it
kubectl delete pod stuck-pod --grace-period=0 --force # last resortDeleting a pod that a deployment owns doesn't get rid of it: the deployment starts a replacement. Delete or scale the deployment instead.
Nodes and Resource Use
kubectl top nodes # CPU and memory (needs metrics-server)
kubectl top pods --sort-by=memory
kubectl cordon worker-1 # no new pods on this node
kubectl drain worker-1 --ignore-daemonsets --delete-emptydir-data # move pods away
kubectl uncordon worker-1 # back in service
kubectl taint nodes worker-1 gpu=true:NoScheduleDebugging Pods
| Status | Usual cause | Look at |
|---|---|---|
Pending |
No node has enough CPU or memory, or a PVC waits | describe pod events, top nodes |
ImagePullBackOff |
Wrong image name or tag, or a private registry | describe pod, the image name, pull secret |
CrashLoopBackOff |
The app starts, then exits again and again | logs --previous, command and env vars |
OOMKilled |
The container used more memory than its limit | describe pod (Last State), memory limit |
Running but not ready |
The readiness probe fails | describe pod, the probe's path and port |
CreateContainerConfigError |
A config map or secret it needs doesn't exist | describe pod, get cm,secret |
kubectl debug -it web-7d4b9c-x2kfp --image=busybox:1.36 --target=web # add a debug container
kubectl debug node/worker-1 -it --image=busybox:1.36 # shell on a node
kubectl run net --image=nicolaka/netshoot --rm -it --restart=Never -- bash # test DNS and network
kubectl get endpoints web # which pod IPs a service sends traffic to
kubectl auth can-i delete pods # check your permissions
kubectl auth can-i list secrets --as=system:serviceaccount:shop:defaultkubectl debug with an ephemeral container helps with small images that have no shell. It needs Kubernetes 1.25 or newer.
Common Mistakes
- Wrong context. Show the current context in your shell prompt, or check
kubectl config current-contextbefore risky commands. - Forgetting the namespace. Without
-n, kubectl uses the context's default namespace, soget podscan look empty when your pods are elsewhere. - Using
latestas the image tag. You can't tell which version runs, and rollbacks don't help. Use a fixed tag or a digest. - No resource requests. The scheduler can't place pods well, and a busy pod can starve its neighbors. Set
requestsfor CPU and memory, and a memorylimit. - Editing live objects only.
kubectl editfixes it now, and the next deploy from Git puts the old values back.
