Kubernetes Commands Cheatsheet
Version: 1.6
Contexts
kubectl config get-contexts
kubectl config delete-context CONTEXT_NAME
kubectl config set-context --current --namespace=NAMESPACE
kubectl config use-context CONTEXT_NAME
Run Pod from Image
kubectl run NAME --image=image [--env="key=value"]
Get Info
kubectl get pods [-o wide]
kubectl describe service SERVICE_NAME
kubectl get pods --all-namespaces -o wide --field-selector spec.nodeName=NODE_NAME
Delete Pods
By label:
kubectl delete pods -l label=value
By state (e.g., Evicted):
kubectl get pod | grep Evicted | awk '{print $1}' | xargs kubectl delete pod
Set Namespace for Session
kubectl config set-context --current -n=<NAMESPACE>
Validate Before Deployment
kubectl apply --dry-run=client -f deployment.yaml
Deploy and Watch
kubectl apply -f deployment.yaml
kubectl get service <SERVICE-NAME> [--watch]
Access Pod Shell
Standard exec:
kubectl exec -it <POD-NAME> -- /bin/bash
Ephemeral debug container:
kubectl debug <POD_NAME> -it --image=<IMAGE_NAME>
## Using busybox
kubectl debug <POD_NAME> -it --image=busybox
Network Testing Pods
Alpine with wget (curl not included):
kubectl run --rm -it --image=alpine disposable-curl-pod
## wget -qO- 10.0.1.34/health
Install curl in alpine:
apk --no-cache add curl
Or use busybox with curl built-in:
kubectl run disposable-curl-pod --image=radial/busyboxplus:curl -it --rm
Port Forwarding
kubectl port-forward service/[SERVICE_NAME] [HOST_PORT]:[POD_PORT]
kubectl port-forward pod/[POD_NAME] [HOST_PORT]:[POD_PORT]
DNS Service
kubectl get services kube-dns --namespace=kube-system
Troubleshoot Crashes
kubectl get pod [POD_NAME] --output=[yaml/json]
kubectl logs [POD_NAME]
kubectl describe [POD_NAME]
For exited pods:
kubectl logs [POD_NAME] -p
Specific container logs (e.g., initContainer):
kubectl logs [POD_NAME] -c [CONTAINER_NAME]
List Resources
kubectl api-resources --verbs=list --namespaced -o wide
Explain Resource Schema
kubectl explain <RESOURCE>.<PATH>.<TO>.<ITEM>
// e.g:
kubectl explain ingress.spec.rules.http
Cleanup Resources
Deleting a namespace removes everything under it (async operation):
kubectl delete namespace NAMESPACE_NAME
Service DNS Resolution
Services resolve at: service-name.namespace.svc.cluster.local
Within the same namespace, service-name is sufficient.
Details: https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/
AWS EKS
Set EKS connection:
aws eks update-kubeconfig --name <EKS_CLUSTER> --alias <CLUSTER_LOCAL_ALIAS> --profile <AWS_PROFILE>