Kubectl Basic Tips

If you just started using kubectl  tool there are some must-have things to ease your work. They are tested on Linux and Mac, and may work on Windows in MinGW or WSL but I can’t test it.

Alias to k

Because writing kubectl is too much effort and you have a chance for a typo. The trick is to change it to k.

Add to your ~/.bashrc (or if you prefer zsh then to ~/.zshrc ):

alias k="kubectl"

Restart the shell. After that you can write all the basic commands:

$ k get pods
$ k get nodes
$ k config get-contexts


Completion in kubectl helps you to find the right pods, nodes and works pretty much like completion for filenames in shell.

For the latest guide refer to the official docs. The guide depends on which OS you use.

You will need again to edit the .bashrc  or .zshrc  config file and restart the shell.

# do OS-specific stuff to include bash-completion 
source <(kubectl completion bash)

For some reason bash-completion didn’t work for me on MacOS Mojave. The solution was a bit radical: switch from bash to zsh.

In this example I list all my contexts (contexts are essentially different clusters). There are 3 of them. One is from Google Cloud (gke- prefix), and I want to switch to it

$ k config get-contexts
CURRENT   NAME                                      CLUSTER                                   AUTHINFO                                        NAMESPACE
          gke_jonsnow-245010_europe-west1-b_kubia   gke_jonsnow-245010_europe-west1-b_kubia   gke_jonsnow-245010_europe-west1-b_kubia
*         kube-aws-ruslanbes-5678109-d1-kub         kube-aws-ruslanbes-5678109-d1-kub         kube-aws-ruslanbes-5678109-d1-kub-admin
          kube-aws-ruslanbes-5678109-s1-kub         kube-aws-ruslanbes-5678109-s1-kub         kube-aws-ruslanbes-5678109-s1-kub-admin
$ k config use-context nc<tab> ⤵
$ k config use-context ncpltws-c-env6-k8s
Switched to context "ncpltws-c-env6-k8s".


Sometimes you’d like to monitor what’s going on with your cluster, most often – the status of your pods.

$ watch kubectl get pods

To make watch  also work with k  you need to add one line to your .bashrc  or .zshrc  config file and restart the shell.

alias watch='watch -c '

Notice the space between -c  and the quote. This is specifically to handle aliased commands. You can also omit -c  – this parameter tells to colorize output if possible.

$ watch k get pods
Every 2.0s: kubectl get pods
dnsutils      1/1     Running   0          6d4h
kubia-5g6x8   1/1     Running   0          6d3h
kubia-drkm8   1/1     Running   0          18d
kubia-sd4g7   1/1     Running   0          6d3

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.