kubectl

On this page 7

kubectl is the official command-line client for Kubernetes. It translates commands typed by an operator into requests to the cluster’s API server, which lets users inspect, create, update and delete Kubernetes resources such as Pods, Deployments, Services and ConfigMaps, and debug running workloads by reading logs, opening shells and forwarding ports.

kubectl does not manage containers directly and does not talk to nodes on its own. Every action goes through the Kubernetes API, so kubectl has exactly the power that the user’s credentials and role-based access control (RBAC) permissions allow. The same API is used by dashboards, CI pipelines and GitOps controllers, which makes kubectl the most direct, transparent window into a cluster.

How kubectl communicates with a cluster

kubectl reads its connection settings from a kubeconfig file, by default ~/.kube/config, or from the path in the KUBECONFIG environment variable. The file defines clusters (API server address and certificate authority), users (client certificates, tokens or authentication plugins) and contexts, which combine a cluster, a user and a default namespace.

For each command, kubectl builds an HTTPS request to the REST API, for example a GET on the list of Pods in a namespace, and formats the JSON response as a table, YAML or JSON. Mutating commands send the desired object, and the API server validates it, applies admission policies and stores the result in etcd. Controllers in the cluster then act on the change asynchronously, which is why a successful kubectl command means the request was accepted, not that the workload is already running.

Version compatibility matters. kubectl is supported within one minor version of the API server, older or newer, so a 1.30 client works with 1.29, 1.30 and 1.31 servers. Larger gaps can cause missing fields or rejected requests.

Imperative and declarative styles

kubectl supports two fundamentally different ways of managing resources. Understanding the difference is essential, because mixing them carelessly causes configuration drift.

StyleExample commandStrengthWeakness
Imperative commandskubectl create deployment web --image=nginxFast for experiments and learningNo record of desired state
Imperative object configurationkubectl create -f web.yamlFiles can be reviewed and versionedFails if the object already exists
Declarative configurationkubectl apply -f manifests/Idempotent, suits version controlMerge behavior needs understanding
Server-side applykubectl apply --server-side -f web.yamlTracks field ownership between toolsConflicts must be resolved explicitly
Ways of managing resources with kubectl

Production teams generally rely on declarative manifests stored in Git, applied by a pipeline or a GitOps controller, and use imperative commands mainly for inspection and emergencies. The command kubectl diff -f shows what an apply would change before anything is modified, which is a valuable safety step.

Essential commands by task

Most daily work uses a small set of commands. The table below groups them by purpose.

TaskCommandWhat it does
List resourceskubectl get pods -n shop -o wideShows Pods with node and IP information
Inspect detailskubectl describe pod web-7d9fShows configuration, status and recent events
Read logskubectl logs deploy/web --previousPrints output, including the last crashed container
Open a shellkubectl exec -it web-7d9f -- shRuns a command inside a running container
Reach a Pod locallykubectl port-forward svc/web 8080:80Tunnels a local port to a Service or Pod
Roll out changeskubectl rollout status deploy/webFollows or undoes a Deployment update
Scale a workloadkubectl scale deploy/web --replicas=5Changes the replica count
Debug a Podkubectl debug -it web-7d9f --image=busyboxAdds an ephemeral debugging container
Frequently used kubectl commands

Output can be shaped precisely. Options such as -o yaml, -o jsonpath and --sort-by turn kubectl into a scripting tool, while label selectors such as -l app=web restrict commands to matching objects. The command kubectl explain documents every field of every resource type directly from the cluster’s API schema.

kubectl is the foundation, but other tools build on the same API for packaging, automation and visualization. The comparison below shows how they relate.

ToolMain purposeRelationship to kubectl
kubectlDirect resource management and debuggingReference client for the API
HelmPackaging and templated releasesReplaces raw apply for packaged applications
KustomizeOverlay-based manifest customizationBuilt into kubectl as apply -k
GitOps controllersContinuous sync from Git to the clusterAutomate what kubectl apply does manually
Terminal and web dashboardsVisual navigation of resourcesUse the same API and kubeconfig
kubectl and neighboring Kubernetes tools

kubectl can also be extended with plugins: any executable named kubectl-something on the path becomes the command kubectl something. Plugin managers distribute hundreds of such extensions, for example for switching contexts or inspecting RBAC permissions.

Safety practices and common mistakes

Because kubectl acts directly on live clusters, a single command can cause an outage. Experienced operators adopt habits that make mistakes less likely.

  • Running a command against the wrong context is the classic error; showing the current context in the shell prompt prevents it.
  • Deleting by broad selectors such as kubectl delete pods --all in the wrong namespace removes far more than intended; --dry-run=server previews the effect.
  • Editing live objects with kubectl edit creates drift from the manifests in Git, which the next deployment silently overwrites.
  • Over-privileged kubeconfig files shared among people or stored in pipelines widen the impact of a leaked credential.
  • Assuming apply means success; kubectl rollout status and events confirm whether Pods actually became ready.

Understanding it simply

kubectl is the remote control for a Kubernetes cluster. Kubernetes runs applications across many machines. kubectl is the tool people type commands into to see what is running and to tell the cluster what to change.

It works like a phone call to a control tower. You do not fly the planes yourself. You ask the tower for information or give it instructions, and the tower makes it happen. Whether you may give an instruction depends on your access rights.

Applied in practice

On a Friday afternoon, an online store’s checkout service starts returning errors. The on-call engineer switches to the production context and runs kubectl get pods -n checkout. Two of six Pods show CrashLoopBackOff.

kubectl logs --previous reveals that the new release fails to read a missing configuration key. kubectl rollout history shows that the release went out 20 minutes earlier, so the engineer runs kubectl rollout undo deploy/checkout and follows it with kubectl rollout status. Within about two minutes all six Pods are ready again. The fix is then added to the manifests in Git, so the cluster and the repository stay in agreement, and the incident ends with less than half an hour of degraded checkout.