Filters
How to search
  • Plain words find names, texts and examples.
  • "two words" finds the exact phrase.
  • --name or -x finds an option.
  • #word looks only inside commands.
  • @grep finds lessons and labs that use grep.
  • Filters: cat:network · in:labs · in:notes · level:rhcsa · ch:8 · root:yes. Put ! before a word to leave it out. OR between words means one of them.
  • ↑ ↓ to move · Enter to open · Esc to close · / to search

kubectl

The command-line client for Kubernetes: create, inspect, change, debug and delete everything in a cluster.

Level
DevSecOps service
Group
Containers and Kubernetes
Needs root
No
Package
kubernetes-client

What it does

kubectl sends requests to the Kubernetes API server. It reads the cluster address and your credentials from a kubeconfig file (~/.kube/config or $KUBECONFIG). One file can hold several contexts (cluster + user + namespace).

You work in two styles: imperative (kubectl create, run, scale, expose — fast, great in the CKA exam) and declarative (kubectl apply -f with YAML in Git — the GitOps way). --dry-run=client -o yaml turns an imperative command into YAML you can edit.

How to write it

kubectl [COMMAND] [TYPE] [NAME] [flags]
kubectl apply -f FILE|DIR|URL

Main parts

Common commands

get TYPE [NAME]
List resources.
describe TYPE NAME
Details and events (first step of debugging).
apply -f FILE
Create or update from YAML.
create / run / expose
Create resources imperatively.
delete TYPE NAME / -f FILE
Delete resources.
logs POD [-c C] [-f] [--previous]
Container logs.
exec -it POD -- sh
Run a command in a container.
edit TYPE NAME
Edit a live object in your editor.
scale / autoscale
Change replicas / create an HPA.
rollout status|history|undo|restart
Manage deployments.
port-forward POD|svc/NAME L:R
Forward a local port into the cluster.
top nodes|pods
CPU and memory use (needs metrics-server).
cordon / uncordon / drain NODE
Node maintenance.
taint / label / annotate
Change metadata.
auth can-i VERB RES [--as USER]
Check RBAC rights.
config get-contexts | use-context | set-context
Work with kubeconfig.
explain TYPE.FIELD
Built-in docs for YAML fields.
debug
Start a debug container in a pod or on a node.
diff -f FILE
Show what apply would change.

Options 10

Most used

Global flags

-n NS / -A
Namespace / all namespaces.
-o wide|yaml|json|name|jsonpath=…
Output format.
-l KEY=VAL
Select by label.
--dry-run=client -o yaml
Print YAML, create nothing.
--context NAME
Use another context.
-w
Watch for changes.
--sort-by=.metadata.creationTimestamp
Sort the list.
--field-selector status.phase=Running
Filter by fields.
--force --grace-period=0
Delete at once (careful).
--kubeconfig FILE
Use another kubeconfig.

Examples 11

$ run as a normal user# run as root (or with sudo)

  1. 1See the cluster

    kubectl cluster-info
    kubectl get nodes -o wide
    kubectl get pods -A
  2. 2Create a deployment and a service fast (CKA style)

    kubectl create deployment shop --image=ghcr.io/s0sta/shop:1.4.0 --replicas=3 -n shop
    kubectl expose deployment shop --port=80 --target-port=8080 -n shop
    kubectl get deploy,rs,pods,svc -n shop
  3. 3Generate YAML, edit, apply

    kubectl create deployment api --image=nginx:1.27 --dry-run=client -o yaml > api.yaml
    vim api.yaml
    kubectl apply -f api.yaml
    kubectl diff -f api.yaml
  4. 4Debug a pod that does not start

    kubectl describe pod shop-7c9d6b8f5-x2k4p -n shop
    kubectl logs shop-7c9d6b8f5-x2k4p -n shop --previous
    kubectl get events -n shop --sort-by=.lastTimestamp
    kubectl debug -it shop-7c9d6b8f5-x2k4p -n shop --image=busybox:1.36 --target=shop
  5. 5Roll out a new version and roll back

    kubectl set image deployment/shop shop=ghcr.io/s0sta/shop:1.5.0 -n shop
    kubectl rollout status deployment/shop -n shop
    kubectl rollout history deployment/shop -n shop
    kubectl rollout undo deployment/shop -n shop
  6. 6Reach a service from your laptop

    kubectl port-forward svc/shop 8080:80 -n shop
    curl http://localhost:8080/health
  7. 7Check and test RBAC

    kubectl auth can-i create deployments -n shop --as=system:serviceaccount:shop:ci
    kubectl create role reader --verb=get,list,watch --resource=pods -n shop
    kubectl create rolebinding ci-reader --role=reader --serviceaccount=shop:ci -n shop
  8. 8Read values with jsonpath

    kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="InternalIP")].address}'
    kubectl get secret db -n shop -o jsonpath='{.data.password}' | base64 -d
  9. 9Maintain a node

    kubectl cordon worker2
    kubectl drain worker2 --ignore-daemonsets --delete-emptydir-data
    kubectl uncordon worker2
  10. 10Switch cluster and namespace

    kubectl config get-contexts
    kubectl config use-context home-k3s
    kubectl config set-context --current --namespace=shop
  11. 11Learn a field

    kubectl explain pod.spec.securityContext --recursive | head -30

Watch out

  • Check the context before delete or apply: kubectl config current-context.
  • kubectl get secret -o yaml shows base64 — that is not encryption.
  • A kubeconfig is a credential. Keep it chmod 600, never in Git.

Files

~/.kube/config
Default kubeconfig (clusters, users, contexts).
/etc/kubernetes/admin.conf
kubeadm admin kubeconfig on control-plane nodes.

Tips to remember

Exit codes

0Success.
1Error (not found, forbidden, invalid YAML …).

Full manual

This page explains the command in simple words. The original manual has every detail.

In your terminal: man kubectl