Wiki

Kubernetes Commands

API resources

List all API objects in a namespace

1
2
kubectl api-resources --verbs=list --namespaced -o name \
  | xargs -n 1 kubectl get --show-kind --ignore-not-found -n ${NAMESPACE}

because kubectl get all does not really give you all the resources.

Events

List events in the last hours and sort by time.

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

Traffic

Port-forwarding

Listen on port 8888 locally, forwarding connection to 5000 on ${POD_NAME}

1
kubectl -n ${NAMESPACE} port-forward pod/${POD_NAME} 8888:5000

Note that pod/mypod can also be svc/ or deployment/.

This is useful to troubleshoot in-cluster services without exposing them. Port-forwarding works only for TCP traffic at the moment.

Pods and Shells

Execute a command in a Pod

1
2
3
kubectl exec ${POD_NAME} -- echo hello world

kubectl exec ${POD_NAME} -c ${CONTAINER_NAME} -- curl https://www.example.org

By label

1
2
3
kubectl exec -it \
  $(kubectl get pod -n ${NAMESPACE} -l key=value --output=jsonpath={.items..metadata.name}) \
  -n ${NAMESPACE} -c ${CONTAINER_NAME} -- bash

Open a shell to a Pod

1
kubectl exec -it ${POD_NAME} -- bash

Spin up a debug Pod and open a shell to it

1
kubectl run -it ${POD_NAME} --image=debian --rm --command -- sh

This is useful when the application Pod is super stripped down, such as using distroless base image that makes troubleshooting difficult due to the lack to tooling.

Find all unhealthy Pods

1
kubectl get po -A | grep -v Running | grep -v Completed

Get Pod name by label

1
kubectl get po -n ${NAMESPACE} -l key=value --output=jsonpath={.items..metadata.name}

Logs

Get last 20 lines of logs

1
kubectl logs --tail=20 ${POD_NAME}

Get logs in the last 3 hours

1
kubectl logs --since=3h ${POD_NAME}

Get tail logs and stream new logs

1
kubectl logs --tail=20 ${POD_NAME} -f

####Aggregate logs from multiple Pods using label selector

1
kubectl logs -l app=server --tail=20 -f

Nodes

List all used NodePorts in a cluster

1
2
$ TEMPLATE='{{range .items}}{{range.spec.ports}}{{if .nodePort}}{{.nodePort}}{{.}}{{"\n"}}{{end}}{{end}}{{end}}'
$ kubectl get svc --all-namespaces -o go-template="${TEMPLATE}"

List all Nodes by creation time

1
kubectl get node --sort-by=.metadata.creationTimestamp

Get Pod Count per Node

1
2
3
for n in $(kubectl get nodes --no-headers | cut -d " " -f1); do
    echo -n "${n}: "; kubectl get pods --all-namespaces  --no-headers --field-selector spec.nodeName=${n} | wc -l
done

Useful kubectl plugins

Namespace-wide rolling restart

Repo: LifeWay/kubectl-roll-plugin

kubectl roll -n ${NAMEPSACE} will trigger a rolling restart of all StatefulSets, DaemonSets, and Deployments in a given namespace