kubectl cheat sheet

kubectl cheat sheet

Run from support01 with ~/.kube/config in place (Lab 01). No sudo.

Setup that saves hours

alias k=kubectl
source <(kubectl completion bash)
complete -o default -F __start_kubectl k
export do="--dry-run=client -o yaml"      # then: kubectl run x --image=nginx $do
kubectl config set-context --current --namespace=dev

Ask the cluster instead of the internet

QuestionCommand
Which kinds exist? short names? namespaced?kubectl api-resources
Which kinds are cluster-scoped?kubectl api-resources --namespaced=false
Which fields does this kind have?kubectl explain ingress.spec.rules
All fields at oncekubectl explain deploy.spec --recursive
What can this command do?kubectl create --help (examples at the bottom)
Global flagskubectl options
Client / server versionkubectl version
Can I do this?kubectl auth can-i create deployments -n dev

Look around

TaskCommand
Cluster reachable?kubectl cluster-info
Nodes with IPs and versionskubectl get nodes -o wide
Everything in a namespacekubectl get all -n dev
All namespaceskubectl get pods -A
Watch changes livekubectl get pods -w
Sorted eventskubectl get events --sort-by=.lastTimestamp
Warnings only, everywherekubectl get events -A --field-selector type=Warning
Resource usagekubectl top nodes / kubectl top pods
By labelkubectl get pods -l app=web
Custom columnskubectl get pods -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName

Create and change

TaskCommand
Apply a manifest (or a dir)kubectl apply -f pod.yaml / -f ./manifests/
Generate YAML without creatingkubectl run web --image nginx --dry-run=client -o yaml > web.yaml
Deployment YAMLkubectl create deploy web --image nginx --dry-run=client -o yaml
Service for a deploymentkubectl expose deploy web --port 80 --type NodePort
Ingress (legacy)kubectl create ingress web --rule="web.k8s.lab/*=web-svc:80"
Edit a live objectkubectl edit deploy web
Patch a fieldkubectl patch svc web -p '{"spec":{"type":"NodePort"}}'
Scalekubectl scale deploy web --replicas=3
Change an imagekubectl set image deploy/web nginx=nginx:1.28
Env from a ConfigMapkubectl set env deploy/web --from=configmap/app-cfg
Label / annotatekubectl label pod web tier=frontend
Deletekubectl delete -f web.yaml / kubectl delete pod web

Inspect and debug

TaskCommand
Everything about an object + eventskubectl describe pod web
Live object as YAMLkubectl get pod web -o yaml
One fieldkubectl get pod web -o jsonpath='{.status.podIP}'
Logs, follow, previous crashkubectl logs -f web / kubectl logs web --previous
Logs of one containerkubectl logs web -c sidecar
Logs by label / via controllerkubectl logs -l app=web --tail=50 / kubectl logs deploy/web
Shell insidekubectl exec -it web -- sh
Throwaway debug Podkubectl run tmp --image busybox --restart=Never -it --rm -- sh
Port-forwardkubectl port-forward svc/web 8080:80
Copy fileskubectl cp web:/etc/nginx/nginx.conf ./nginx.conf
Service endpointskubectl get endpointslices -l kubernetes.io/service-name=web

Workloads

kubectl rollout status  deploy/web
kubectl rollout history deploy/web
kubectl rollout undo    deploy/web
kubectl rollout restart deploy/web
kubectl get rs -l app=web              # which ReplicaSet is active
kubectl get ds -A                      # DaemonSets
kubectl get sts                        # StatefulSets

Storage

kubectl get pv                                   # cluster-scoped
kubectl get pvc -A
kubectl describe pvc data                        # why is it Pending?
kubectl get sc                                   # StorageClasses
kubectl get csidrivers                           # installed CSI drivers
kubectl get pv -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,CLAIM:.spec.claimRef.name,POLICY:.spec.persistentVolumeReclaimPolicy
kubectl patch pv <pv> -p '{"spec":{"claimRef":null}}'   # reuse a Released PV

Gateway API

kubectl get gatewayclass
kubectl get gateway,httproute -A
kubectl describe gateway web-gw          # PROGRAMMED + conditions
kubectl describe httproute shop          # Accepted + ResolvedRefs
kubectl explain httproute.spec.rules.backendRefs

The CRDs must be installed first - Gateway API is not part of Kubernetes.

Custom resources

kubectl get crd
kubectl api-resources --api-group=postgresql.cnpg.io
kubectl explain cluster.spec
kubectl get clusters -A

Nodes

kubectl cordon   worker01
kubectl drain    worker01 --ignore-daemonsets --delete-emptydir-data
kubectl uncordon worker01
kubectl describe node worker01 | grep -A6 'Allocated resources'

Short names

po pods, deploy deployments, rs replicasets, svc services, ing ingresses, ds daemonsets, sts statefulsets, ns namespaces, cm configmaps, no nodes, gtw gateways, httproute httproutes, pv/pvc volumes, sa serviceaccounts, crd customresourcedefinitions.

Reference

kubernetes.io/docs/reference/kubectl/quick-reference