Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 78 ยท Getting Started

kubectl Essentials

Learn the kubectl commands you use daily: contexts, get, describe, apply, delete, output formats, explain and dry-run, plus a JSONPath-style extractor in Python.

kubectl (say "cube-control" or "cube-cuttle", both are common) is the command-line client for the Kubernetes API. Everything it does is an HTTPS request to the API server described in Cluster Architecture: get is a read, apply is a create or update, delete is a delete. If you learn a dozen commands and a few output tricks you can handle most daily work.

All commands below are read-only examples because no cluster runs on this site. The runnable part is a Python stand-in for the -o jsonpath output format, which teaches you how to pull single values out of the big JSON documents the API returns.

The daily kubectl loop

get List objects quickly.
describe Details and recent events.
apply Create or update from a file.
delete Remove what you created.
1 / 2

kubeconfig and contexts

kubectl learns where the cluster is from a kubeconfig file, by default ~/.kube/config. It holds three lists: clusters (API server address and certificate authority), users (credentials) and contexts, each of which pairs a cluster with a user and an optional default namespace. The current context decides where your commands go.

Terminal
kubectl config get-contexts
kubectl config current-context
kubectl config use-context kind-lab
kubectl config set-context --current --namespace=shop

The last command makes shop your default namespace, so you can omit -n shop. Use --kubeconfig path or the KUBECONFIG environment variable to point at another file.

Reading things: get and describe

kubectl get lists objects of one kind. Add -n name for a namespace or -A for all of them.

Terminal
kubectl get nodes
kubectl get pods
kubectl get pods -n kube-system
kubectl get pods -A
kubectl get deployments,services
kubectl get pods --selector app=web
kubectl get pods --watch

kubectl describe prints a human-readable report about one object, and ends with the Events section, which is the first place to look when something is stuck:

Terminal
kubectl describe pod web-6d8f7c9b5-x2k4q
kubectl describe node kind-lab-worker

To see the live logs of a container or run a command inside it:

Terminal
kubectl logs web-6d8f7c9b5-x2k4q
kubectl logs web-6d8f7c9b5-x2k4q --previous
kubectl exec -it web-6d8f7c9b5-x2k4q -- sh

Resource names have short forms: po for pods, svc for services, deploy for deployments, ns for namespaces. kubectl api-resources lists all of them.

Changing things: apply, create and delete

The recommended way to change a cluster is to keep manifests in files and apply them. apply creates the object if it is missing and updates it otherwise, so repeating it is safe:

Terminal
kubectl apply -f web.yaml
kubectl apply -f manifests/
kubectl apply -k overlays/prod
kubectl delete -f web.yaml
kubectl delete pod web-6d8f7c9b5-x2k4q

kubectl create is the imperative cousin: it fails if the object already exists. It is handy for quick experiments, and for generating YAML (see dry-run below). Quick imperative helpers also exist:

Terminal
kubectl run tmp --image=busybox:1.36 --restart=Never -- sleep 3600
kubectl scale deployment web --replicas=5
kubectl set image deployment/web web=shop-web:1.1
kubectl rollout status deployment/web

Prefer files for anything you want to keep, because a file can be reviewed, versioned and re-applied.

Output formats

-o changes how get prints. This is one of the most useful flags in the tool.

Flag Result
-o wide Extra columns such as node and IP
-o yaml The full object as stored, including status
-o json The same as JSON, good for scripts and jq
-o name Only kind/name, good for loops
-o jsonpath='{...}' Extract specific fields
-o custom-columns=... Your own table
Terminal
kubectl get pod web-6d8f7c9b5-x2k4q -o yaml
kubectl get pods -o wide
kubectl get pods -o name
kubectl get pod web-6d8f7c9b5-x2k4q -o jsonpath='{.status.podIP}'
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
kubectl get pods -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName

Every API object is a JSON document. -o yaml shows you the real thing, and the paths you see there (status.podIP, spec.nodeName) are the paths you use in JSONPath.

explain and dry-run

You do not have to memorize every field. kubectl explain documents the schema straight from the API server you are connected to, so it always matches your cluster's version:

Terminal
kubectl explain pod
kubectl explain pod.spec.containers
kubectl explain deployment.spec.strategy --recursive

A dry run processes a request without saving it. With --dry-run=client nothing is sent; with --dry-run=server the API server validates and admits the object but does not persist it. Combined with -o yaml it becomes a manifest generator, a favourite trick for exams and for starting a file:

Terminal
kubectl create deployment web --image=nginx:alpine --replicas=3 --dry-run=client -o yaml > web.yaml
kubectl apply -f web.yaml --dry-run=server
kubectl diff -f web.yaml

kubectl diff shows what an apply would change, which is a good habit before touching a shared cluster.

A JSONPath extractor you can run

The real jsonpath implementation is built into kubectl. The stand-in below supports the most common pieces of the syntax: dotted fields, [0] indexes and [*] wildcards over a pod list. It shows why {.items[*].metadata.name} returns every name.

Python A tiny JSONPath-style extractor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Real kubectl JSONPath has more features (filters like ?(@.metadata.name=="web-1"), range/end loops), but the core idea is the same: walk a path through the JSON.

Filtering and counting

The following stand-in imitates --selector and -o name, the two flags you will use together most often. Selection by label is explained fully in Labels, Selectors and Annotations.

Python Selecting objects by label

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

kubectl delete acts immediately and kubectl delete pods --all deletes every pod in the current namespace. Confirm your context and namespace first, and prefer --dry-run=server or kubectl diff when you are unsure.

create, apply and replace

Three commands put an object from a file into the cluster, and they behave differently when the object already exists.

Command Style If it exists If it does not
kubectl create -f x.yaml Imperative Fails with AlreadyExists Creates it
kubectl apply -f x.yaml Declarative Merges your file into the live object Creates it
kubectl replace -f x.yaml Imperative Replaces the whole object with your file Fails with NotFound

apply remembers what you sent last time (in the kubectl.kubernetes.io/last-applied-configuration annotation, or in managed fields with --server-side). On the next apply it does a three-way merge: fields you removed from the file are removed from the object, fields in the file are set, and fields that someone else wrote (an autoscaler that changed replicas, a webhook that injected a sidecar) are left alone. That is why apply is the right default for files in Git. If two tools fight over a field, server-side apply reports a conflict (--force-conflicts takes ownership).

replace is blunt: whatever is in the file becomes the object, and anything not in the file is gone. It needs the object to exist, and you must send a current resourceVersion if you include one. Some fields are immutable (a Service's clusterIP, a Deployment's selector, most Pod fields), so a change to them fails. kubectl replace --force -f x.yaml works around that by deleting and recreating the object. That means downtime, a new UID, and for a Deployment the loss of its rollout history, so use it only when you accept that.

The stand-in below models the three semantics. Pay attention to what happens to replicas (changed by an autoscaler) and to the paused field that was removed from the file:

Python create vs apply vs replace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two more ways to change objects: kubectl edit deployment web opens the live object in your editor and applies the saved result, and kubectl patch changes a few fields (kubectl patch deployment web -p '{"spec":{"replicas":4}}'; --type=json and --type=merge choose the patch format). Both are quick for emergencies, but they leave no file behind, so the next apply from Git will overwrite them.

Terminal helpers and relatives of kubectl

A few small tools make daily work with many clusters and namespaces faster. They are separate programs (read-only here):

  • kubectx and kubens switch the current context and the default namespace with one short command (kubectx prod, kubens shop). They do the same as the krew plugins ctx and ns above and also work without krew.
  • kube-ps1 adds the current context and namespace to your shell prompt. It is a cheap protection against running a command on production while you believe you are on staging.
  • k9s is a full-screen terminal interface: browse pods, read logs, open a shell, edit and delete objects, all with keystrokes and live updates. It uses your kubeconfig and your permissions, so it can delete things just as kubectl can.
  • oc is the command-line client of Red Hat OpenShift, a Kubernetes distribution with extra features (projects, routes, built-in image builds, a stricter default security policy). Most kubectl commands work the same with oc, so what you learn here carries over.

Deleting in bulk

delete accepts names, files, labels and fields:

Terminal
kubectl delete pod web-1 web-2                      # by name
kubectl delete pods -l app=web                      # by label selector
kubectl delete pods --all -n dev                    # everything of one kind in a namespace
kubectl delete all --all -n dev                     # most workload kinds (not ConfigMaps, Secrets, PVCs)
kubectl delete pods --field-selector=status.phase=Succeeded -n jobs
kubectl delete -f manifests/ --ignore-not-found
kubectl delete namespace dev                        # the namespace and everything inside it

Remember that all is a category of common kinds, not "everything": ConfigMaps, Secrets, PersistentVolumeClaims, Ingresses and custom resources survive delete all. Deleting a Deployment also deletes its ReplicaSets and pods (cascading); a controller that owns pods will recreate them if you delete only the pods. Always check your context and namespace first (kubectl config current-context), and preview selectors with kubectl get ... -l ... before replacing get with delete.

By default delete is graceful: the pod receives SIGTERM, has terminationGracePeriodSeconds (30 s by default) to finish, and then gets SIGKILL (Pod Lifecycle). Useful variations:

Flag Effect
--grace-period=5 Shorter grace period for this delete
--now Same as --grace-period=1
--wait=false Return at once instead of waiting for the object to disappear
--force --grace-period=0 Force delete: remove the object from the API immediately without waiting for the kubelet to confirm. The containers may still be running.

Use a force delete only for pods stuck in Terminating on a node that is dead for good. On a node that is merely unreachable, it can leave two copies of a StatefulSet pod running (Nodes). If an object stays Terminating forever, look at metadata.finalizers: a finalizer is a promise some controller must clear before deletion completes, and the right fix is usually to repair that controller, not to remove the finalizer by hand.

Copying files with kubectl cp

Terminal
kubectl cp web-6d8f7c9b5-x2k4q:/var/log/app.log ./app.log          # pod -> laptop
kubectl cp ./config.json web-6d8f7c9b5-x2k4q:/tmp/config.json       # laptop -> pod
kubectl cp -n shop web-6d8f7c9b5-x2k4q:/data ./data -c sidecar      # other namespace, specific container

kubectl cp runs tar inside the container, so it does not work on images without tar (distroless and many minimal images). Use an ephemeral debug container or a shared volume instead (Debugging Applications in a Cluster). Files you copy in are lost when the pod is replaced, so cp is for investigation, not for deployment (use ConfigMaps, images or volumes for that).

Plugins and krew

Any executable on your PATH named kubectl-<name> becomes a plugin: running kubectl foo bar runs kubectl-foo bar. List what is installed with kubectl plugin list.

krew is the plugin manager (itself installed separately from its project page). It installs plugins from an index:

Terminal
kubectl krew update
kubectl krew search tree
kubectl krew install ctx ns tree
kubectl ctx                  # switch contexts quickly
kubectl ns shop              # switch the default namespace
kubectl tree deployment web  # show owned ReplicaSets and pods as a tree
kubectl krew upgrade

Plugins run with your credentials, so treat them like any other software you install: prefer well-known ones, read what they do, and keep them updated.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which command shows the Events section that usually explains why a pod is stuck?

    describe prints a detailed report that ends with recent events such as failed scheduling or image pull errors. get only shows a short status line.
  2. 2. What does kubectl apply -f web.yaml do when run twice with the same file?

    apply is declarative and idempotent: it creates what is missing and updates what differs, so repeating it with an unchanged file changes nothing.
  3. 3. Which command prints only the IP address of one pod?

    The jsonpath output format follows a path through the object's JSON, and status.podIP holds the address.
  4. 4. How can you generate a Deployment manifest without creating anything in the cluster?

    A client-side dry run builds the object locally and -o yaml prints it, so you can save and edit the file before applying.

Summary

  • kubectl reads cluster, user and namespace from the current context in your kubeconfig.
  • get lists, describe explains (with events), apply creates or updates, delete removes.
  • -o yaml/json/wide/name/jsonpath/custom-columns control the output; JSONPath follows paths through the object's JSON.
  • explain documents any field and --dry-run plus -o yaml generates manifests.
  • The Python programs imitate JSONPath and selectors; the kubectl commands themselves are read-only examples.

Next, write the files you apply: YAML and the Shape of a Manifest.