kubectl Cheat Sheet: Install and Essential Commands for Kubernetes

· 1 min read · Kubernetes Tutorials

What is kubectl #

kubectl is the command line client of Kubernetes. It reads the cluster address and credentials from ~/.kube/config and sends your requests to the API server.

Install #

curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
kubectl version --client

On macOS use brew install kubectl. Rancher Desktop and K3s provide one already. Keep kubectl within one minor version of the cluster.

Contexts and namespaces #

kubectl config get-contexts
kubectl config use-context rancher-desktop
kubectl config set-context --current --namespace=dev
kubectl get ns

A mistake in the wrong context is the most common accident: check the current context before deleting anything.

Look at resources #

kubectl get pods                      # -A for all namespaces, -o wide for nodes and IPs
kubectl get deploy,svc,ing
kubectl get pod web-1 -o yaml
kubectl describe pod web-1            # events at the end explain most failures
kubectl get events --sort-by=.lastTimestamp
kubectl top pods                      # needs metrics-server

Create and change #

kubectl apply -f app.yaml             # create or update (use this)
kubectl apply -f ./manifests/ -R
kubectl create deployment web --image=nginx:stable --replicas=2
kubectl expose deployment web --port=80 --type=NodePort
kubectl scale deployment web --replicas=5
kubectl set image deployment/web nginx=nginx:1.27
kubectl rollout status deployment/web
kubectl rollout undo deployment/web
kubectl delete -f app.yaml

Add --dry-run=client -o yaml to any create command to generate a manifest without creating anything.

Debug #

kubectl logs web-1 -f --tail=100      # --previous after a crash, -c for a container
kubectl exec -it web-1 -- sh
kubectl port-forward svc/web 8080:80  # reach a service from your machine
kubectl run tmp --rm -it --image=busybox -- sh
kubectl debug -it web-1 --image=busybox --target=nginx

Typical states: ImagePullBackOff (wrong image name or no registry access), CrashLoopBackOff (the container exits: read the logs), Pending (not enough resources or an unbound volume: read describe).

Output tricks #

kubectl get pods -o jsonpath='{.items[*].metadata.name}'
kubectl get pods -l app=web
kubectl get pods --field-selector=status.phase=Running
kubectl api-resources
kubectl explain deployment.spec.strategy

Productivity #

alias k=kubectl
source <(kubectl completion bash)
complete -o default -F __start_kubectl k

Next steps #

Install the web interface with the Kubernetes Dashboard, package applications with Helm and deliver them with Argo CD.

#Kubernetes #Kubectl