kubectl is the command line client for Kubernetes. Under the hood it is a REST client: every command becomes an HTTP request to the API server, signed with the credentials in your kubeconfig file. Keep that in mind and kubectl stops being magic. Every verb maps to an HTTP method, anything you can write in a manifest you can do through the API, and a “Forbidden” error is simply an RBAC decision.
You can see the requests yourself by raising the verbosity:
$ kubectl get pods -v=6
I1030 10:12:04.118 loader.go:395] Config loaded from file: /home/jeff/.kube/config
I1030 10:12:04.201 round_trippers.go:553] GET https://127.0.0.1:41235/api/v1/namespaces/default/pods?limit=500 200 OK in 9 milliseconds
NAME READY STATUS RESTARTS AGE
web-7c5b8d9f6d-9hq7m 1/1 Running 0 2h
Where kubectl gets its configuration
kubectl reads ~/.kube/config (or the files listed in KUBECONFIG). The file holds three lists:
- clusters: API server addresses and their certificates.
- users: credentials such as tokens, client certificates or cloud login plugins.
- contexts: a pairing of one cluster, one user and a default namespace.
$ kubectl config get-contexts
CURRENT NAME CLUSTER AUTHINFO NAMESPACE
* kind-lab kind-lab kind-lab
prod-eu prod-eu sso-admin shop
$ kubectl config current-context
kind-lab
$ kubectl config use-context prod-eu
Switched to context "prod-eu".
Warning: kubectl never asks “are you sure you mean production?”. Running a delete against the wrong context is one of the most common serious mistakes. Show the current context in your shell prompt, or use tools like kubectx and kubens.
Imperative vs declarative
There are two styles of using kubectl.
Imperative commands say what to do right now: kubectl create deployment, kubectl scale, kubectl expose. They are fast and great for learning, but nothing records what you did, so you cannot review or repeat it.
Declarative use means you keep YAML files in Git and run kubectl apply -f. Changes are reviewable in pull requests, you can diff them and any teammate can recreate the same state. This is how real teams work.
The best of both: let an imperative command write the YAML for you, then edit it and commit it.
$ kubectl create deployment shop-api --image=ghcr.io/jeffxl/shop-api:1.2.0 --replicas=2 \
--dry-run=client -o yaml > shop-api.yaml
$ kubectl apply -f shop-api.yaml
deployment.apps/shop-api created
apply vs create vs replace vs patch
| Command | What it does | When to use it |
|---|---|---|
create | Creates the object, fails if it already exists | One-off objects |
apply | Creates or updates, merging your changes | Almost always |
replace | Overwrites the whole object, fails if it does not exist | Rarely |
patch | Changes only the fields you name | Scripts and quick targeted edits |
apply does a three-way merge between the configuration you applied last time, your current file and the live object. That lets it change one field without throwing away fields that controllers set. If you mix apply with kubectl edit on the same object, the two histories drift apart and the results become confusing, so pick one.
Before applying to anything important, preview the change:
$ kubectl diff -f shop-api.yaml
- replicas: 2
+ replicas: 4
$ kubectl apply -f shop-api.yaml --dry-run=server
deployment.apps/shop-api configured (server dry run)
--dry-run=server sends the object through validation and admission without saving it, so it catches errors a client-side check misses.
The commands you will run every day
Look around:
$ kubectl get pods
$ kubectl get pods -o wide # adds Pod IP and node
$ kubectl get pods -A # every namespace
$ kubectl get pods -w # watch changes live
$ kubectl get all # Pods, Services, Deployments, ReplicaSets
Find out what is wrong. kubectl describe is the most valuable command you have. The Events section at the bottom names most problems directly: failed scheduling, image pull errors, failing probes and volume problems.
$ kubectl describe pod shop-api-6d9f7b8c4-kq2xv
$ kubectl logs shop-api-6d9f7b8c4-kq2xv
$ kubectl logs shop-api-6d9f7b8c4-kq2xv --previous # the run that crashed
$ kubectl logs -f deployment/shop-api # follow
$ kubectl logs -l app=shop-api --tail=50 # all replicas
Get inside:
$ kubectl exec -it shop-api-6d9f7b8c4-kq2xv -- sh
$ kubectl port-forward service/shop-api 8080:80
Change things:
$ kubectl apply -f shop-api.yaml
$ kubectl scale deployment/shop-api --replicas=4
$ kubectl rollout restart deployment/shop-api
$ kubectl delete -f shop-api.yaml
Selecting and filtering
Labels are how Kubernetes connects objects, and most commands accept a label selector with -l:
$ kubectl get pods -l app=shop-api
$ kubectl get pods -l 'env in (staging,prod)'
$ kubectl get pods --field-selector status.phase=Running
$ kubectl get pods --sort-by=.metadata.creationTimestamp
$ kubectl get pods --show-labels
Output formats
-o yaml and -o json show the full object as the API server stores it, including the status. To pick out single values, use JSONPath or custom columns:
$ kubectl get pod shop-api-6d9f7b8c4-kq2xv -o jsonpath='{.status.podIP}'
10.244.1.17
$ kubectl get pods -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName,RESTARTS:.status.containerStatuses[0].restartCount
NAME NODE RESTARTS
shop-api-6d9f7b8c4-kq2xv lab-worker 0
shop-api-6d9f7b8c4-p8mzt lab-worker2 3
$ kubectl get pods -o jsonpath='{range .items[*]}{.spec.containers[*].image}{"\n"}{end}' | sort -u
ghcr.io/jeffxl/shop-api:1.2.0
Namespaces in kubectl
Without -n, kubectl uses the namespace from your context, usually default. Forgetting the namespace is the number one reason for a confusing No resources found.
$ kubectl get pods -n kube-system
$ kubectl config set-context --current --namespace=shop
Context "kind-lab" modified.
Making it fast
$ echo 'source <(kubectl completion bash)' >> ~/.bashrc
$ echo 'alias k=kubectl' >> ~/.bashrc
$ echo 'complete -o default -F __start_kubectl k' >> ~/.bashrc
$ kubectl explain deployment.spec.strategy
$ kubectl api-resources
kubectl explain documents every field for the exact API version your cluster runs, which is faster and more accurate than searching the web.
Quick reference
| Task | Command |
|---|---|
| Current cluster | kubectl config current-context |
| Switch cluster | kubectl config use-context <name> |
| Set default namespace | kubectl config set-context --current --namespace=<ns> |
| List with details | kubectl get pods -o wide |
| Diagnose | kubectl describe pod <name> |
| Logs from a crash | kubectl logs <name> --previous |
| Shell inside | kubectl exec -it <name> -- sh |
| Reach a Service locally | kubectl port-forward svc/<name> 8080:80 |
| Generate a manifest | kubectl create deployment x --image=y --dry-run=client -o yaml |
| Preview a change | kubectl diff -f file.yaml |
| Document a field | kubectl explain <resource>.<field> |
| Recent events | kubectl get events -A --sort-by=.lastTimestamp |
Exercise
Which command shows what kubectl apply -f app.yaml would change, without changing anything?
Show answer
Answer: D. kubectl diff compares the file with the live objects and prints the differences, like terraform plan. Add --dry-run=server to also run validation and admission.
Exercise
A script needs only the IP address of one Pod, with nothing else in the output. Which option do you use?
Show answer
Answer: B. JSONPath extracts exactly the fields you name. -o wide prints a table that a script would have to parse, and -o yaml prints the whole object.
Key takeaways
- kubectl is an API client: a “Forbidden” error is an RBAC decision.
- Check your context before anything destructive.
- Keep YAML in Git and use
apply; generate starting files with--dry-run=client -o yaml. - Reach for
kubectl describefirst when something is wrong. kubectl logs --previousshows why a container crashed.- Run
kubectl diffbefore applying changes to important objects. - Install shell completion and alias
k: you will type kubectl thousands of times.
FAQ
What is the difference between kubectl apply and kubectl create?
create makes a new object and fails if it already exists. apply creates the object or updates it with a three-way merge, so it is safe to run again and again from the same file.
How do I see why a Pod is failing?
Run kubectl describe pod <name> and read the Events. For crash loops add kubectl logs <name> --previous, and check the termination reason with kubectl get pod <name> -o jsonpath='{.status.containerStatuses[0].lastState.terminated.reason}', which shows values such as OOMKilled or Error.
How do I switch between clusters and namespaces?
Use kubectl config use-context <name> for clusters and kubectl config set-context --current --namespace=<ns> for the default namespace. The kubectx and kubens tools make both one short command.
What does kubectl diff do?
It compares your manifest with the live objects and prints what would change, much like terraform plan. Combine it with --dry-run=server to also catch validation and admission errors before you apply.