Kubernetes Cheat Sheet

Cheet says: k8s is just fancy container orchestration!

Context & Config


kubectl config get-contexts        # List contexts
kubectl config use-context prod    # Switch context
kubectl config current-context     # Current context

Namespace shortcuts

alias k='kubectl' alias kn='kubectl -n'

Getting Info


kubectl get all                    # Everything in namespace
kubectl get pods -A                # All pods, all namespaces
kubectl get pods -o wide           # More columns
kubectl get pods -w                # Watch mode

kubectl describe pod         # Full details
kubectl logs                  # Container logs
kubectl logs -f               # Follow logs
kubectl logs  -c   # Specific container

Running & Debugging


Quick pod

kubectl run debug --image=busybox -it --rm -- sh

Exec into pod

kubectl exec -it -- /bin/sh kubectl exec -it -c -- bash

Port forward

kubectl port-forward pod/ 8080:80 kubectl port-forward svc/ 8080:80

Copy files

kubectl cp :/path/file ./local kubectl cp ./local :/path/file

Creating Resources


From file

kubectl apply -f deployment.yaml kubectl apply -f ./manifests/

Quick deployments

kubectl create deployment nginx --image=nginx kubectl expose deployment nginx --port=80 --type=LoadBalancer

Scale

kubectl scale deployment nginx --replicas=3

Editing & Patching


kubectl edit deployment      # Opens in editor
kubectl set image deployment/ =

Patch

kubectl patch deployment -p '{"spec":{"replicas":5}}'

Rollout

kubectl rollout status deployment/ kubectl rollout history deployment/ kubectl rollout undo deployment/

Deleting


kubectl delete pod 
kubectl delete -f deployment.yaml
kubectl delete pods --all
kubectl delete namespace     # Careful!

Force delete stuck pod

kubectl delete pod --grace-period=0 --force

Labels & Selectors


kubectl get pods -l app=nginx
kubectl get pods -l 'env in (prod,staging)'
kubectl label pod  env=prod
kubectl label pod  env-         # Remove label

Resources & Limits


resources:
  requests:
    memory: "64Mi"
    cpu: "250m"
  limits:
    memory: "128Mi"
    cpu: "500m"

Secrets & ConfigMaps


Create secret

kubectl create secret generic my-secret --from-literal=key=value kubectl create secret generic my-secret --from-file=./secrets/

Create configmap

kubectl create configmap my-config --from-literal=key=value kubectl create configmap my-config --from-file=config.properties

View (decoded)

kubectl get secret my-secret -o jsonpath='{.data.key}' | base64 -d

Debugging


Events

kubectl get events --sort-by='.lastTimestamp'

Resource usage

kubectl top pods kubectl top nodes

Explain fields

kubectl explain deployment.spec.replicas

Dry run

kubectl apply -f file.yaml --dry-run=client kubectl apply -f file.yaml --dry-run=server

Useful Aliases


alias k='kubectl'
alias kgp='kubectl get pods'
alias kgs='kubectl get svc'
alias kgd='kubectl get deployments'
alias kl='kubectl logs'
alias ke='kubectl exec -it'