Skip to content
Opsfolk
Kubernetes

kubectl cheat sheet

The kubectl commands you reach for every day, from switching context and reading a pod's logs to rolling back a Deployment and draining a node, checked on kubectl 1.36.

Names such as web, api, prod and node-1 are examples: put your own resource, namespace or node there. Every namespaced command takes -n <namespace>, or the context's default namespace when you leave it out; -A means every namespace. Many people alias k=kubectl; the code here spells it out.

Contexts and config

Which cluster, which user and which namespace each command goes to.

  • kubectl config current-context

    Print the context every command goes to now: a cluster, a user and a default namespace.

  • kubectl config get-contexts

    List the contexts in your kubeconfig; the current one is marked with *.

  • kubectl config use-context prod

    Switch to the context prod for every later command.

    Warning: It is written to the kubeconfig file, so every other terminal that reads it switches too.

  • kubectl config set-context --current --namespace=web

    Make web the default namespace of the current context, so you can leave out -n web.

  • kubectl --context staging -n api get pods

    Run one command against another context and namespace without switching.

    Tip: Scripts should always pass --context: they then never depend on what a person last switched to.

  • kubectl config view --minify

    Show only the current context's cluster, user and namespace, with credentials redacted.

    Tip: Add --raw to see the certificates and tokens as they are stored.

  • KUBECONFIG=~/.kube/config:~/.kube/staging.yaml kubectl config view --flatten > merged.yaml

    Merge several kubeconfig files into one, with their certificates inlined.

  • kubectl config delete-context old-cluster

    Remove a context from the kubeconfig; its cluster and user entries stay until you delete them too.

  • kubectl version

    Print the versions of kubectl and of the cluster's API server.

    Tip: kubectl is supported within one minor version of the API server, older or newer.

  • kubectl cluster-info

    Print the addresses of the control plane and of the cluster's core services, such as DNS.

Get and describe

List resources, pick the fields you need and read one in full.

  • kubectl get pods -o wide

    List pods with the node each runs on and its IP address.

  • kubectl get pods -A

    List pods in every namespace, with a column for the namespace.

  • kubectl get deploy,svc,ingress -n web

    List several kinds at once, separated by commas.

  • kubectl get pods -l 'app=api,tier!=cache'

    Select by labels: =, !=, and in (a,b) or notin (a,b) for sets.

  • kubectl get pods -L app,version

    Add a column for each of the labels app and version.

    Tip: --show-labels prints every label in one column instead.

  • kubectl get pods --field-selector status.phase!=Running

    Select by a field of the object, here every pod that is not running.

    Warning: Only a few fields can be selected on, such as metadata.name, status.phase and spec.nodeName.

  • kubectl get pod api-7d9f -o yaml

    Print the whole object as the API server holds it, status included.

  • kubectl get deploy api -o jsonpath='{.spec.template.spec.containers[0].image}'

    Print one field with a JSONPath expression, here the image of the first container.

  • kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.podIP}{"\n"}{end}'

    Print one line per pod, its name and its IP, with range over the list.

  • kubectl get pods -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName,IMAGES:.spec.containers[*].image

    Print a table of the columns you name, each a header and a field's path.

  • kubectl get pods --sort-by=.metadata.creationTimestamp

    Sort the list by a field, here the oldest pod first.

  • kubectl get pods -w

    Print the list, then a line for each change until you stop it with Ctrl+C.

  • kubectl describe pod api-7d9f

    Read a resource in full, in words: its containers, conditions, volumes and, at the foot, its recent events.

  • kubectl get all -n web

    List the common workload kinds in a namespace: pods, Services, Deployments, ReplicaSets, StatefulSets, Jobs.

    Warning: all is a fixed category: it leaves out ConfigMaps, Secrets, Ingresses, PersistentVolumeClaims and custom resources.

  • kubectl api-resources

    List every kind the cluster serves, with its short name, API group and whether it is namespaced.

  • kubectl explain deployment.spec.strategy --recursive

    Read the schema of a field from the cluster's own API, every field under it included.

Create and apply

Make resources from files, or generate their YAML to start from.

  • kubectl apply -f deploy.yaml

    Create the resources in a file, or update them to match it if they exist.

  • kubectl apply -R -f k8s/

    Apply every manifest in a directory and the directories under it.

  • kubectl apply -k overlays/prod

    Build a Kustomize directory and apply the result.

  • kubectl kustomize overlays/prod

    Print what a Kustomize directory builds, without applying it.

  • kubectl diff -f deploy.yaml

    Show what applying the file would change in the cluster, as a diff.

    Tip: It exits with 1 when there are differences and 0 when there are none, which a CI step can test.

  • kubectl apply -f deploy.yaml --dry-run=server

    Send the change through the API server's validation and admission, without saving it.

  • kubectl apply --server-side -f deploy.yaml

    Let the API server merge the file and record which fields you own.

    Tip: When another manager owns a field you set, the apply is refused; --force-conflicts takes it over.

  • kubectl create deployment api --image=ghcr.io/acme/api:1.4 --replicas=3 --dry-run=client -o yaml > deploy.yaml

    Write a Deployment's YAML to start from, without sending anything to the cluster.

  • kubectl create namespace web

    Create a namespace.

  • kubectl create job migrate --image=ghcr.io/acme/api:1.4 -- ./migrate up

    Run a command once to completion as a Job; what follows -- is the container's command.

  • kubectl create cronjob backup --image=ghcr.io/acme/backup:2.1 --schedule='0 3 * * *' -- /backup.sh

    Run a command on a cron schedule, here every day at 03:00 in the controller's time zone.

  • kubectl create job backup-now --from=cronjob/backup

    Run a CronJob's job now, once, without waiting for its schedule.

  • kubectl delete -f deploy.yaml

    Delete every resource the file names.

  • kubectl delete pod api-7d9f --grace-period=0 --force

    Remove a pod's object at once, without waiting for its node to confirm the containers stopped.

    Warning: Only for a pod stuck on a node that is gone: on a live node its containers may keep running beside the replacement.

Edit and patch

Change a live resource in place, from an editor or one command.

  • kubectl edit deploy api

    Open the live object in your editor; saving and closing applies the change.

    Tip: KUBE_EDITOR="code --wait" picks the editor; an editor that returns at once saves nothing.

  • kubectl set image deploy/api api=ghcr.io/acme/api:1.5

    Change the image of the container api, which starts a rollout.

  • kubectl set env deploy/api LOG_LEVEL=debug

    Set an environment variable on every container of the Deployment; LOG_LEVEL- removes it.

  • kubectl set env deploy/api --list

    List the environment variables the Deployment's containers are given.

  • kubectl set resources deploy/api -c api --requests=cpu=250m,memory=256Mi --limits=memory=512Mi

    Set the requests and limits of the container api.

  • kubectl patch deploy api -p '{"spec":{"replicas":5}}'

    Change fields with a strategic merge patch, the default: lists of containers merge by name.

  • kubectl patch svc api --type=merge -p '{"spec":{"type":"NodePort"}}'

    Change fields with a JSON merge patch, which replaces a list whole.

  • kubectl patch deploy api --type=json -p '[{"op":"remove","path":"/spec/template/spec/containers/0/args"}]'

    Change fields with a JSON patch: operations on paths, which can remove a field.

  • kubectl label pod api-7d9f env=prod --overwrite

    Add or change a label; env- in place of env=prod removes it.

  • kubectl annotate deploy api team=payments --overwrite

    Add or change an annotation, which tools read and selectors do not.

  • kubectl replace --force -f pod.yaml

    Delete the resource and create it again from the file, for a field that cannot change in place.

    Warning: Between the delete and the create the resource does not exist: a pod's work stops.

Deployments and rollouts

Roll out a new version, watch it, scale it and roll it back.

  • kubectl rollout status deploy/api --timeout=5m

    Wait until the rollout is done, and exit with an error if it is not within five minutes.

    Tip: Put it after the apply in a deploy job, so a rollout that never becomes ready fails the job.

  • kubectl rollout history deploy/api

    List the Deployment's revisions, each a ReplicaSet it kept.

  • kubectl rollout history deploy/api --revision=3

    Show the pod template of revision 3.

  • kubectl annotate deploy/api kubernetes.io/change-cause='image 1.5, fix login'

    Set the line the history shows in CHANGE-CAUSE for the current revision.

  • kubectl rollout undo deploy/api

    Roll back to the revision before the current one.

  • kubectl rollout undo deploy/api --to-revision=3

    Roll back to revision 3 of the history.

  • kubectl rollout restart deploy/api

    Replace every pod with a new one, by the rollout's rules, without changing the spec.

    Tip: It works on StatefulSets and DaemonSets too: kubectl rollout restart statefulset/db.

  • kubectl rollout pause deploy/api

    Stop the Deployment from rolling out, so several changes go out as one; rollout resume lets it.

  • kubectl scale deploy/api --replicas=5

    Set the number of pods.

  • kubectl scale deploy/api --current-replicas=2 --replicas=3

    Scale only if the count is still 2, so two people do not overwrite each other.

  • kubectl autoscale deploy/api --min=2 --max=10 --cpu=70%

    Create a HorizontalPodAutoscaler that keeps average CPU near 70% of what the pods request.

    Warning: It needs the metrics-server, and containers with a CPU request: a percentage is of the request.

  • kubectl get rs -l app=api

    List the Deployment's ReplicaSets: the current one and the old ones a rollback goes to.

Logs, exec and debug

Read what a pod prints, open a shell in it, or debug it from beside it.

  • kubectl logs api-7d9f

    Print what the pod's container has written to its standard output and error.

  • kubectl logs -f deploy/api

    Follow the logs of one pod of the Deployment, picked for you.

    Tip: --all-pods reads every pod of it, each line prefixed with the pod's name.

  • kubectl logs api-7d9f -c sidecar

    Read one container of a pod that has several; without -c you get the default one.

  • kubectl logs api-7d9f --previous

    Read the logs of the container's last run, the one that crashed before this restart.

  • kubectl logs api-7d9f --since=15m --timestamps

    Read only the last 15 minutes, each line with the time it was written.

  • kubectl logs -l app=api --all-containers --prefix --tail=100

    Read the last 100 lines of every container of every pod with the label, each line prefixed with its source.

  • kubectl exec -it api-7d9f -- sh

    Open a shell in the pod's container; what follows -- is the command to run.

  • kubectl exec api-7d9f -c api -- env

    Run one command in a given container and print what it prints.

  • kubectl exec -it deploy/api -- sh

    Open a shell in one pod of the Deployment, without looking up a pod's name.

  • kubectl debug -it api-7d9f --image=busybox:1.37 --target=api

    Add a debug container to the running pod, sharing the processes of its container api.

    Tip: For an image with no shell: the debug container brings the tools, and /proc/1/root shows the target's files.

  • kubectl debug api-7d9f -it --copy-to=api-debug --container=api -- sh

    Start a copy of the pod with the command of its container api replaced by a shell, for one that crashes at start.

  • kubectl debug node/node-1 -it --image=busybox:1.37

    Start a pod on a node in its host namespaces, with the node's file system at /host.

    Warning: The pod stays after you exit: delete it with kubectl delete pod and the name the command printed.

  • kubectl cp api-7d9f:/app/dump.json ./dump.json

    Copy a file out of a pod; swap the two arguments to copy one in.

    Warning: It runs tar in the container, so it fails on an image that has none.

  • kubectl run tmp --rm -it --image=busybox:1.37 --restart=Never -- sh

    Start a throwaway pod with a shell, which is deleted when you exit.

Services and networking

Expose a workload, reach it from your machine and check its endpoints.

  • kubectl expose deploy api --port=80 --target-port=8080

    Create a ClusterIP Service named api that sends its port 80 to the pods' port 8080.

  • kubectl expose deploy api --name=api-public --type=LoadBalancer --port=80 --target-port=8080

    Create a Service that asks the cloud for an external load balancer.

  • kubectl get svc api -o jsonpath='{.status.loadBalancer.ingress[0].ip}'

    Print the external address a LoadBalancer Service was given.

    Tip: Some clouds give a name, not an address: read .hostname in place of .ip.

  • kubectl port-forward svc/api 8080:80

    Reach the Service's port 80 at localhost:8080 while the command runs.

    Warning: It picks one pod behind the Service and forwards to it alone: there is no load balancing.

  • kubectl port-forward deploy/db 15432:5432

    Reach a pod of the Deployment's port 5432 at localhost:15432, such as a database.

  • kubectl port-forward --address 0.0.0.0 svc/api 8080:80

    Listen on every interface of your machine, not only on localhost.

    Warning: Anyone who can reach your machine then reaches the Service.

  • kubectl get endpointslices -l kubernetes.io/service-name=api

    List the pod addresses behind the Service api.

    Tip: No address means the Service's selector matches no ready pod: compare it with the pods' labels.

  • kubectl run dns-test --rm -it --image=busybox:1.37 --restart=Never -- nslookup api.web.svc.cluster.local

    Check from inside the cluster that a Service's name resolves.

  • kubectl run http-test --rm -it --image=busybox:1.37 --restart=Never -- wget -qO- http://api.web/healthz

    Call a Service by its name from a throwaway pod, as another pod would.

  • kubectl get ingress -A

    List every Ingress, with its hosts and the address it was given.

  • kubectl get networkpolicy -n web

    List the NetworkPolicies of a namespace, which can explain traffic that never arrives.

  • kubectl proxy --port=8001

    Serve the API server at localhost:8001 with your credentials, for curl or a browser.

ConfigMaps and Secrets

Configuration and credentials, from literals, files and env files.

  • kubectl create configmap api-config --from-literal=LOG_LEVEL=info --from-literal=REGION=eu-west-1

    Create a ConfigMap from keys and values given on the command line.

  • kubectl create configmap nginx-conf --from-file=nginx.conf

    Create a ConfigMap from a file, with the file's name as its key.

    Tip: --from-file=default.conf=./nginx.conf gives the key another name; a directory adds each file in it.

  • kubectl create configmap api-env --from-env-file=api.env

    Create a ConfigMap from a file of KEY=value lines, one key per line.

  • kubectl create configmap api-config --from-file=config/ --dry-run=client -o yaml | kubectl apply -f -

    Create a ConfigMap from files, or update it if it exists, which create alone refuses.

    Warning: A pod that reads it as environment variables sees the change only once it restarts.

  • kubectl create secret generic db-creds --from-file=username=./username.txt --from-file=password=./password.txt

    Create a Secret from files, so the values stay out of your shell's history.

  • kubectl get secret db-creds -o jsonpath='{.data.password}' | base64 -d

    Print one value of a Secret, decoded from the base64 it is stored in.

  • kubectl get secret db-creds -o go-template='{{range $k, $v := .data}}{{$k}}={{$v | base64decode}}{{"\n"}}{{end}}'

    Print every key of a Secret with its decoded value, one per line.

  • kubectl create secret tls api-tls --cert=tls.crt --key=tls.key

    Create a TLS Secret from a certificate and its key, for an Ingress to use.

  • kubectl create secret docker-registry ghcr --docker-server=ghcr.io --docker-username=acme --docker-password="$GHCR_TOKEN"

    Create the Secret a pod names in imagePullSecrets to pull from a private registry.

  • kubectl patch serviceaccount default -p '{"imagePullSecrets":[{"name":"ghcr"}]}'

    Give every pod that runs as the namespace's default service account the registry Secret.

Nodes and scheduling

Take a node out of service, put it back, and steer where pods land.

  • kubectl get nodes -o wide

    List the nodes with their roles, version, addresses, OS image and container runtime.

  • kubectl describe node node-1

    Read a node's conditions, capacity, taints and, under Allocated resources, what its pods request.

  • kubectl get pods -A --field-selector spec.nodeName=node-1

    List every pod that runs on one node.

  • kubectl cordon node-1

    Mark the node unschedulable: its pods keep running, and no new pod lands there.

  • kubectl drain node-1 --ignore-daemonsets --delete-emptydir-data

    Cordon the node and evict its pods, by their disruption budgets, before maintenance.

    Warning: --delete-emptydir-data loses what pods kept in emptyDir volumes: it is gone with the pod.

    Tip: --timeout=10m stops waiting on an eviction that never comes, instead of hanging.

  • kubectl uncordon node-1

    Let pods be scheduled on the node again after maintenance.

  • kubectl taint nodes node-1 dedicated=gpu:NoSchedule

    Keep off the node every pod that does not tolerate the taint; dedicated=gpu:NoSchedule- removes it.

  • kubectl get nodes -o custom-columns=NAME:.metadata.name,TAINTS:.spec.taints[*].key

    List the keys of each node's taints.

  • kubectl label nodes node-1 disktype=ssd

    Label a node, for a pod's nodeSelector or node affinity to choose it.

  • kubectl top nodes

    Show each node's CPU and memory use now.

    Warning: kubectl top reads the metrics API: it needs the metrics-server, or it answers that the API is not available.

  • kubectl top pods -A --sort-by=memory

    Show every pod's CPU and memory use, the largest memory first.

  • kubectl top pod api-7d9f --containers

    Show the use of each container of a pod.

Access and RBAC

Who you are to the cluster, what you may do, and granting access.

  • kubectl auth whoami

    Print the user name and groups the API server sees for your credentials.

  • kubectl auth can-i create deployments -n web

    Ask whether you may do something; it answers yes or no.

  • kubectl auth can-i --list -n web

    List everything you may do in a namespace.

  • kubectl auth can-i get secrets -n web --as=system:serviceaccount:web:api

    Ask the same for another identity, here the service account api of web.

    Tip: --as is impersonation: you need the impersonate permission yourself.

  • kubectl create serviceaccount deployer -n web

    Create an identity for a program, such as a CI job.

  • kubectl create role pod-reader --verb=get,list,watch --resource=pods,pods/log -n web

    Create a Role that may read pods and their logs in one namespace.

  • kubectl create rolebinding deployer-pods --role=pod-reader --serviceaccount=web:deployer -n web

    Give the Role to a service account, written as namespace:name.

  • kubectl create rolebinding devs-view --clusterrole=view --group=devs -n web

    Give a group the built-in read-only role, in one namespace only.

    Tip: The built-in roles are view, edit, admin and cluster-admin; view cannot read Secrets.

  • kubectl create token deployer -n web --duration=1h

    Print a short-lived token for a service account, to put in a kubeconfig or a CI secret.

    Warning: The API server can give a shorter life than you ask for.

  • kubectl get rolebindings,clusterrolebindings -A -o wide

    List every binding with its role and the users, groups and service accounts it names.

Troubleshooting

Events, conditions and the cluster's own health checks.

  • kubectl events -n web

    List a namespace's recent events, the oldest first, such as failed scheduling, pulls and probe failures.

    Tip: Events are kept for about an hour by default: look soon after the trouble.

  • kubectl events -n web --for pod/api-7d9f

    List only the events about one resource.

  • kubectl events -A --types=Warning -w

    Watch every warning in the cluster as it happens.

  • kubectl get pods -A --field-selector status.phase=Pending

    List the pods that are not scheduled or not started; describe one to read why.

  • kubectl get pod api-7d9f -o jsonpath='{.status.containerStatuses[*].lastState.terminated.reason}'

    Print why each container last stopped, such as OOMKilled or Error.

  • kubectl wait --for=condition=Ready pod -l app=api --timeout=2m

    Wait until every pod with the label is ready, or fail after two minutes.

  • kubectl wait --for=condition=complete job/migrate --timeout=10m

    Wait until a Job has finished, as a step before the next one.

  • kubectl wait --for=delete pod/api-7d9f --timeout=60s

    Wait until a resource is gone after a delete.

  • kubectl get --raw='/readyz?verbose'

    Print each of the API server's readiness checks, with ok or why it failed.

  • kubectl get pods -v=6

    Print the HTTP requests kubectl makes, with their status codes and timings.

    Tip: -v=8 also prints the bodies; mind what it shows before you paste it anywhere.

Manifests

YAML to start from, generated or written by hand.

  • deploy.yaml

    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: api
      labels:
        app: api
    spec:
      replicas: 3
      selector:
        matchLabels:
          app: api
      template:
        metadata:
          labels:
            app: api
        spec:
          containers:
            - name: api
              image: ghcr.io/acme/api:1.4
              ports:
                - containerPort: 8080
              resources:
                requests:
                  cpu: 250m
                  memory: 256Mi
                limits:
                  memory: 512Mi
              readinessProbe:
                httpGet:
                  path: /healthz
                  port: 8080
    ---
    apiVersion: v1
    kind: Service
    metadata:
      name: api
    spec:
      selector:
        app: api
      ports:
        - port: 80
          targetPort: 8080

    A Deployment and the Service in front of it: requests to schedule by, a memory limit, and a probe that keeps an unready pod out of the Service.

    Warning: spec.selector cannot change once the Deployment exists, and must match the template's labels.

  • kustomization.yaml

    apiVersion: kustomize.config.k8s.io/v1beta1
    kind: Kustomization
    namespace: web
    resources:
      - ../../base
    images:
      - name: ghcr.io/acme/api
        newTag: "1.5"
    patches:
      - target:
          kind: Deployment
          name: api
        patch: |-
          - op: replace
            path: /spec/replicas
            value: 5

    An overlay for kubectl apply -k: the base's resources in another namespace, with another image tag and replica count.

  • kubectl create deployment api --image=ghcr.io/acme/api:1.4 --port=8080 --dry-run=client -o yaml

    Print a Deployment to start a manifest from; create service, create job and the others do the same.

  • kubectl get deploy api -o yaml --show-managed-fields=false > api.yaml

    Save a live resource as YAML, without the bookkeeping of which manager set each field.

    Tip: Before you apply it elsewhere, remove status, uid, resourceVersion and creationTimestamp.

Pitfalls

What goes wrong with kubectl, and how to get out of it.

  • A command changed the wrong cluster: the terminal was still on the context of the day before.

    Fix: use-context is written to the kubeconfig file and holds in every shell. Pass --context in scripts, show the current context in your prompt, or keep production in a kubeconfig of its own that you name with KUBECONFIG.

  • A pod is in CrashLoopBackOff and kubectl logs shows nothing, or only the start of a run.

    Fix: Read the run that crashed with kubectl logs --previous, and kubectl describe pod for its last state: exit code 137 is a kill, often OOMKilled; 1 is the app's own error.

  • A pod stays in ImagePullBackOff or ErrImagePull.

    Fix: kubectl describe pod says why at the foot: a tag that does not exist, a registry that refused, or a private image with no pull Secret. Create one with create secret docker-registry and name it in imagePullSecrets.

  • A pod stays Pending and never starts.

    Fix: Its events say why: no node has the CPU or memory it requests, a taint it does not tolerate, a nodeSelector no node matches, or a PersistentVolumeClaim that is not bound. Lower the requests, or fix what the event names.

  • kubectl drain repeats "Cannot evict pod as it would violate the pod's disruption budget" and never ends.

    Fix: A PodDisruptionBudget allows no pod to go, as when minAvailable equals the replicas. Scale the workload up or relax the budget for the maintenance; --disable-eviction skips budgets and is the last resort.

  • A change made with kubectl edit pod is gone a few minutes later.

    Fix: A pod of a Deployment is replaced from its template, which your edit did not touch. Change the Deployment (kubectl edit deploy, set image, set env) and let it roll out.

  • kubectl apply fails with field is immutable on a Deployment's spec.selector.

    Fix: A Deployment's selector cannot change after it is created. Create the Deployment under a new name and move the Service to it, or delete it and apply again, which stops its pods meanwhile.

  • kubectl apply warns that the resource is missing the last-applied-configuration annotation.

    Fix: It was made with create or by another tool. The apply adds the annotation and goes on; from then on, change it with apply only, or use apply --server-side, which needs no annotation.

  • kubectl port-forward stops with lost connection to pod.

    Fix: It forwards to one pod, picked when it starts, and ends when that pod goes, in a rollout or a restart. Start it again; for something that lasts, reach the Service through an Ingress or a LoadBalancer.

  • A Secret's values are taken to be safe because they look encrypted.

    Fix: data is base64, an encoding: anyone who may get secrets reads them. Keep that permission narrow with RBAC, and turn on encryption at rest for etcd.

  • A namespace stays in Terminating long after kubectl delete namespace.

    Fix: Something in it has a finalizer whose controller is gone. kubectl get namespace web -o yaml names it under status.conditions; reinstall its controller, or, knowing what you lose, remove that resource's finalizer with kubectl patch.

  • kubectl logs -f -l app=api refuses: you are attempting to follow more log streams than the maximum allowed.

    Fix: It follows at most five at once by default. Raise it with --max-log-requests=10, or narrow the selector.

Every cheat sheet