My Kubernetes/Kubectl Cheat Sheet

Here are few commands that I find myself using a lot when I am working with Kubectl/Kubernetes

Validate a k8s yaml file
kubectl create --dry-run=true --validate=true -f <my-file>.yaml
Get shell in a running pod
kubectl exec -it <pod-name> -- /bin/bash
Get a shell in running container in a pod

Use bin/sh if you are running Alpine

kubectl exec -it <pod-name> --container <container-name> -- /bin/bash
Get logs from a running container in a pod
kubectl logs <pod-name> <container-name>
Get a file from running pod

pass --container <container-name> to connect to specific container when you have multiple containers in pod

kubectl cp <pod-name>:<file-path> <dest-path>
Switch to a cluster

See available contexts by running kubectl config get-contexts

kubectl config use-context <context_name_cluster-name>
Get pods ordered by creation timestamp
kubectl get pods --sort-by=.metadata.creationTimestamp

GKE specific commands

Get cluster list
gcloud container clusters list
Get credentials for a cluster
gcloud container clusters get-credentials <cluster name>
Pull docker image from gcr
gcloud docker -- pull gcr.io/my-project/my-image
Run pulled image locally
docker run -i -t gcr.io/my-project/my-image /bin/bash

Docker

Remove all local docker images
docker rmi -f $(docker images -a -q)

docker images -a -q will give IMAGE ID of all local images and docker rmi -f will remove images with force.

To remove single image, list all images using docker images -a and remove it using docker rmi -f <IMAGE ID>