Can I?

Check to see if you can execute a command based on current permissions (RBAC):

kubectl auth can-i get pods

Contexts

I have multiple clusters, let’s switch!

What contexts are available?

$ kubectl config get-contexts

Switch to a specific context

$ kubectl config use-context gke_matthewdavis-byexamples_us-central1-a_cluster-1

Create a new context and switch to it

$ kubectl config set-context new-content --user=cluster-admin
$ kubectl config use-content new-context

Managing Workloads

Validate first!

$ kubectl create -f my.yaml --dry-run --validate=true

Scaling Replicas

$ kubectl scale --replicas=2 deployment nginx

Editing Objects

$ kubectl edit deployment/ingress-controller
$ KUBE_EDITOR=nano kubectl edit deployment/ingress-controller

Mark a node as “un-schedulable”

$ kubectl cordon

Remove all workloads from a node

$ kubectl drain

Managing Node

Adding a taint

$ kubectl taint node <node> <key>=<value>:NoSchedule

Removing a taint

$ kubectl taint node <node> <key>:NoSchedule-

 

Showing Utilization

Show utilization per node:

$ kubectl top node

Show utilization per pod:

$ kubectl top pod

Watch utilization per pod (repeatedly reload the command):

$ watch kubectl top pod

Sort pod usage from lowest to highest:

$ kubectl top pod | sort -k2 -n

 

Scripting

Store the name of a pod by label:

$ MY_POD=$(kubectl get pods --all-namespaces -lapp=my-awesome-app -o jsonpath='{.items[0].metadata.name})

Using the stored name:

$ kubectl logs -f -p $MY_POD
$ kubectl exec -it $MY_POD sh

Querying

Listing nodes with taints:

$ kubectl get nodes -o custom-columns=NAME:.metadata.name,TAINTS:.spec.taints

Sorting by a field and reversing the results (creationTimestamp — thanks to hubt)

kubectl get pods --sort-by .metadata.creationTimestamp | tac

Troubleshooting

Get event logs

$ kubectl get events -f

Get logs from a terminated pod

$ kubectl logs  -p -f

Show utilization per pod

$ kubectl top pod

Port scan a service using nmap

$ kubectl run --image=mateothegreat/docker-alpine-nmap \
              --rm -i -t nm -- \
              -Pn -p9200,9300 elasticsearch

See: https://github.com/mateothegreat/docker-alpine-nmap

Additional tools/utilities

Have a handy shortcut or tool?

Post a comment and I’ll get it added to the list!