Cheat Sheet - kubectl

Cheat Sheet - kubectl
kubectl Cheat Sheet
This page contains a list of commonly used kubectl commands and flags.Kubectl autocomplete BASH source <(kubectl completion bash) # set up autocomplete in bash into the current shell, bash-completion package should be installed first. echo “source <(kubectl completion bash)” >> ~/.bashrc # add auto…
The official cheat sheet

Pod Management

List all pods running on a specific node

kubectl get pods --all-namespaces -o wide --field-selector spec.nodeName=<nodeName>

See on which nodes the pods are running

kubectl get pods -n demo -o wide

Access pod terminal

kubectl exec --stdin --tty mysql-694d95668d-w7lv5 -- /bin/bash

Get pod logs

kubectl logs <pod>
kubectl logs --follow <pod>

# Or use labels
kubectl logs -l app=my-killer-app --follow 

Get environment variables of a running pod

kubectl exec -it <pod> -n <namespace> -- printenv

Watch restart of pods

kubectl get pod -w -n <namespace>

Restart a daemonSet

kubectl rollout restart daemonset <name> -n <namespace>

Secret Management

Read secret

kubectl get secrets/my-secret -o json

Adding secret from plain text

kubectl create -n <namespace> secret generic <object> --from-literal=<key>=<value-plain-text>

Config Management

Display content of configmap

kubectl describe cm my-configmap -n <namespace>

Network Management

Port forwarding

kubectl port-forward -n <namespace> <pod> <localport>:<podport>

# JVM remote debug
kubectl port-forward -n <namespace> <pod> 5005:5005

Volume Management

Forcefully remove a PVC & PV

kubectl patch pvc <pvc> -p '{\"metadata\":{\"finalizers\":null}}' -n <namespace>
kubectl delete pvc <pvc> --grace-period=0 --force -n <namespace>

Node Management

Remove a node

# Mark node as unschedulable.
kubectl cordon <node>
kubectl drain --ignore-daemonsets --delete-emptydir-data <node>
kubectl delete node <node>


View resource utilization

kubectl top [node|pod]

Quickly switch between contexts

alias devkube "kubectl config use-context kube-dev-context"
alias stgkube "kubectl config use-context kube-stg-context"
alias prdkube "kubectl config use-context kube-prd-context"

Set default namespace

kubectl config set-context --current --namespace=foobar

Get and switch current context

kubectl config get-contexts
kubectl config use-context ...

Use projection with jsonpath

kubectl get node/mynode -o jsonpath='[{}, {.status.allocatable}, {.status.capacity}]'

List events per namespace

kubectl get events -n demo

Create a throw-away interactive shell

kubectl run my-shell --rm -i --tty --image ubuntu -- bash