RousselTMLEARNING

Containers

kubectl cheat sheet: the essential commands

All the kubectl commands you need day to day: contexts, resources, logs, exec, port-forward, rollouts, debug, JSONPath, labels, resources and troubleshooting.

1. Configuration and contexts #

Where am I connected?

Contexts and namespaces #

kubectl version --short 2>/dev/null || kubectl version
kubectl config get-contexts
kubectl config current-context
kubectl config use-context prod-eu
kubectl config set-context --current --namespace=production      # namespace par défaut
alias k=kubectl; source <(kubectl completion bash); complete -o default -F __start_kubectl k

# Utiliser un fichier kubeconfig spécifique
export KUBECONFIG=~/.kube/config:~/.kube/cluster2
kubectl --kubeconfig=./staging.yaml get nodes

2. Reading the cluster state #

get, describe, top, events.

Displaying resources #

Example output of kubectl get pods
A pod in CrashLoopBackOff calls for logs and describe.
kubectl get pods,svc,deploy,ing,pvc,cm -A          # plusieurs types séparés par des virgules ; -A = tous les namespaces
kubectl get nodes,ns                                # ressources non namespacées
kubectl get pods -o wide                       # IP et nœud
kubectl get pods -o yaml                       # manifeste complet
kubectl get pods --show-labels
kubectl get pods -l app=web,env=prod           # sélecteur de labels
kubectl get pods --field-selector status.phase!=Running -A
kubectl get pods --sort-by=.status.startTime
kubectl get all -n production

kubectl describe pod <pod>                     # événements, état, sondes
kubectl top nodes && kubectl top pods -A --sort-by=memory     # nécessite metrics-server
kubectl get events -A --sort-by=.lastTimestamp | tail -20

Extracting fields with JSONPath and custom-columns #

kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.podIP}{"\n"}{end}'
kubectl get nodes -o custom-columns=NOM:.metadata.name,CPU:.status.capacity.cpu,MEM:.status.capacity.memory
kubectl get secret db -o jsonpath='{.data.password}' | base64 -d
kubectl get pods -o json | jq -r '.items[] | select(.status.phase!="Running") | .metadata.name'

3. Creating, modifying, deleting #

Object life cycle.

Imperative and declarative commands #

kubectl apply -f deploy.yaml                 # déclaratif (recommandé)
kubectl apply -k overlays/prod/                # Kustomize
kubectl diff -f deploy.yaml                    # voir ce qui changerait
kubectl create deployment web --image=nginx:1.27 --replicas=2 --dry-run=client -o yaml > deploy.yaml
kubectl run debug --image=busybox -it --rm --restart=Never -- sh
kubectl expose deployment web --port=80 --target-port=8080 --type=ClusterIP
kubectl scale deployment web --replicas=5
kubectl set image deployment/web nginx=nginx:1.27.2
kubectl label pod <pod> env=prod --overwrite
kubectl annotate pod <pod> owner=equipe-a
kubectl edit deployment web                    # édition directe (à éviter en prod)
kubectl patch deployment web -p '{"spec":{"replicas":3}}'
kubectl delete -f deploy.yaml
kubectl delete pod <pod> --grace-period=0 --force     # dernier recours

Rolling updates #

kubectl rollout status deployment/web
kubectl rollout history deployment/web
kubectl rollout undo deployment/web                    # retour arrière
kubectl rollout undo deployment/web --to-revision=2
kubectl rollout restart deployment/web                 # redémarrage progressif
kubectl rollout pause deployment/web && kubectl rollout resume deployment/web

4. Debugging #

Logs, exec, port-forward, debug.

Diagnosing a pod #

kubectl logs <pod>                                  # logs du conteneur
kubectl logs <pod> -c <conteneur> -f --tail=100 --since=10m
kubectl logs <pod> --previous                       # logs avant le dernier crash
kubectl logs -l app=web --all-containers --prefix   # tous les pods d'un label
kubectl exec -it <pod> -- sh                        # shell dans le pod
kubectl exec <pod> -- env | sort
kubectl port-forward svc/web 8080:80                # http://localhost:8080
kubectl port-forward pod/<pod> 5432:5432
kubectl cp <pod>:/var/log/app.log ./app.log
kubectl debug -it <pod> --image=nicolaka/netshoot --target=<conteneur>    # conteneur éphémère de debug
kubectl debug node/<noeud> -it --image=busybox      # inspecter un nœud

Permissions and resources #

kubectl auth can-i create deployments -n production
kubectl auth can-i --list --as=system:serviceaccount:prod:app
kubectl api-resources --namespaced=true
kubectl explain pod.spec.containers.resources
kubectl get --raw /metrics | head                    # métriques de l'API server
Good practice: Enable completion and the k alias, and install kubectx/kubens to switch context and namespace in one command.

Related articles

Container network security and Kubernetes networking

Secure the container network: how Docker and Kubernetes networking works, CNI, default-deny NetworkPolicies, …

Container registry: choosing and securing your image registry (Docker Hub, Harbor, GHCR, ECR)

Understand container registries: Docker Hub, GitHub Container Registry, cloud registries (ECR, ACR, Artifact …

Kubernetes: architecture and components (control plane, nodes, objects)

Understand the Kubernetes architecture: API server, etcd, scheduler, controller manager, kubelet, kube-proxy,…

Keep learning

Support us

♥ SUPPORT US

Support RousselTM Learning

Courses, articles, labs and certificates stay free with no intrusive ads. A voluntary contribution, of any amount you choose, pays for hosting, lab environments and new content.

Contribute with PayPal Any amount · card or PayPal accountLearn more
QR code PayPal
Or scan this QR code with your phone

Thank you, every contribution counts!