Kubectl Tricks

Run command in a pod

It can be useful to execute some command inside running pod, for example see generated nginx's config

# put found pod name in exec commnand
kubectl exec nginx-ingress-controller-j1xvs cat /etc/nginx/nginx.conf
# use "--" as separator for command with arguments
kubectl exec my-pod -- df -h

Use -it (interactive and tty) for interactive commands as bash, irb, top:

kubectl exec -it my-pod-name bash
# or
kubectl exec -it my-rails-app rails c

Update image version via cli

kubectl set image deployment <deployment-name> <container-name>=new_image:img_version --record
# example
kubectl set image deployment sample-app-deployment sample_app=midtrans/sample-app:$PKG_VERSION -n=my-namespace --record

Edit kubernete resources


kubectl edit my-deployment

It will open text editor with current definition of your resource, Default editor is vi, in case it's not your favorite one you may change it:

KUBE_EDITOR="nano" kubectl edit svc/my-service

Or make your choice permanent by adding to ~/.bashrc or ~/.zshrc

export KUBE_EDITOR="atom --wait" # for atom editor
export KUBE_EDITOR="mate -w" # for textmate
export KUBE_EDITOR="nano" # for nano
export KUBE_EDITOR="subl --wait" # sublime

Also can control it with system-wide editor setting $EDITOR

Save k8s objects to file

Save resource as yaml:

kubectl get deployment my-app -o yaml > my-app-deployment.yaml

Show resource as json with syntax highlight:

kubectl get deployment my-app -o yaml | jq

Show latest logs from pod

Show last 100 lines and add new lines in real time (similar to tail -f ...)

kubectl logs my-pod-name --tail 100 --follow

Show logs from previous container (eg when it was crashed and restarted)

kubectl logs my-pod-name --tail 100 --previous

Get running resources

Show all pods, services, deployments, replicasets, cronjobs, deamonsets and jobs

kubect get all

Kubectl auto-complete

Very useful, find it on kubectl page

Kubectl shell prompt

It can show you current k8s cluster and namespace, take it from here: https://github.com/jonmosco/kube-ps1

How to use it:

# ~/.zshrc or ~/.bashrc
source $ZSH/plugins/kube-ps1/kube-ps2.zsh


Watch pod changes

To make list of pods interactive, add -w: (it will add lines bellow for every change of pods' status)

kubectl get pods -w

To have top-like interactivity, we can use watch utility: (works with any command at all, e.g. date)

watch kubectl get pods

Set namespace for session

Save it as default namespace to current config fil and e

kubectl config set-context $(kubectl config current-context) --namespace=sample-app

Using kubectl proxy

It will run a local web-server and make services in cluster accessible, run it with:

kubectl proxy --port=8080

Then can access kubernetes dashboard in browser at

More tools: https://github.com/mhausenblas/kubectl-in-action#tips-and-tricks and https://github.com/ramitsurana/awesome-kubernetes#apicli-adaptors