Most of the tips given below are using kubectl, a powerful command-line tool that allows you to execute commands against Kubernetes clusters.
Industry newsletter
Stay up to date on the most important—and intriguing—industry trends on AI, automation, data and beyond with the Think newsletter. See the IBM Privacy Statement.
Your subscription will be delivered in English. You will find an unsubscribe link in every newsletter. You can manage your subscriptions or unsubscribe here. Refer to our IBM Privacy Statement for more information.
If you need some background on Kubernetes before jumping into these tips, see the following resources:
You can divide a Kubernetes cluster into multiple environments by using namespaces (e.g., Dev1, Dev2, QA1, QA2, etc.), and each environment can be managed by a different user. One of the inconveniences of writing kubectl commands is that every time you write a command, you need the --namespace
option at the end. People often forget this and end up creating objects (pods, services, deployments) in the wrong namespace.
With this trick, you can set the namespace preference before running kubectl commands. Run the following command before executing the kubectl commands, and it will save the namespace for all subsequent kubectl commands for your current context:
kubectl config set-context $(kubectl config current-context) --namespace=mynamespace
Some of the most common and useful commands with namespace are listed below:
Kubernetes commands can be quite lengthy, so setting up some aliases for running kubectl is very helpful. You will no longer need to spell out the full command over and over again, making your life a lot easier when you want to execute multiple Kubernetes commands in one session.
We have listed aliases for some frequently used commands below. Run these before executing kubectl commands to save yourself some time. Example: You just need to type k instead of typing kubectl:
There are many different editors available to write YAML files, but there are many times where you may need to quickly tweak a generated YAML and while working on a terminal. This is a great place to use our trusty vi, the text editor originally created for the Unix operating system.
The vi editor is well documented and has support from a vibrant open source community. One of the problems with the vi editor while creating YAML files, however, is the space issue. We need a way to indent with tabs and align with spaces. Using tabs vs. spaces for whitespace has always created syntax issues while writing YAML files (e.g., getting the 2-space YAML as the default when hitting carriage return).
The solution? Create a ~/.vimrc file with these lines before creating YAML files with the vi editor to make editing easier:
We can create complex YAML files from the command line using kubectl commands.
Most people would agree that working with YAML files is no fun, and Kubernetes YAML files can be very verbose and hard to create from scratch. It is much easier to create the YAML file from kubectl commands instead of from a blank page using an editor.
The following commands will create a YAML file with name yamlfile . Once you create the YAML file from these kubectl commands, you can modify it based on your requirements and use it instead of writing from scratch:
kubectl run busybox --image=busybox --dry-run=client -o yaml -- restart=Never > yamlfile.yaml
kubectl create job my-job --dry-run=client -o yaml --image=busybox -- date>yamlfile.yaml
kubectl get -o yaml deploy/nginx > 1.yaml(Ensure that you have a deployment named as nginx)
kubectl run busybox --image=busybox --dry-run=client -o yaml --restart=Never -- /bin/sh -c "while true; do echo hello; echo hello again;done" > yamlfile.yaml
kubectl run wordpress --image=wordpress –-expose –-port=8989 - -restart=Never -o yaml
kubectl run test --image=busybox --restart=Never --dry - run=client -o yaml -- bin/sh -c 'echo test;sleep 100' > yamlfile.yaml(Notice that --bin comes at the end. This will create yaml file.)
(Notice that --bin comes at the end. This will create yaml file.)
Another good idea for creating the YAML file is obtaining the file directly from the internet using the wget command.
In Tip 1, we learned some useful commands to use Kubernetes namespaces and save them so that you don’t have to add to every command. Let’s expand the tip to make it easier to switch between namespaces and kubectl contexts.
There are several tools that can help, but we like kubectx and kubens for managing contexts and namespaces, respectively. You can find details of kubectx and kubens here.
Here is how to download the Linux binaries for kubectx and kubens utility:
wget https://github.com/ahmetb/kubectx/releases/download/v0.9.0/kubectx_v0.9.0_linux_x86_64.tar.gz
wget https://github.com/ahmetb/kubectx/releases/download/v0.9.0/kubens_v0.9.0_linux_x86_64.tar.gz
Then you extract them with the following commands:
tar -xvf kubectx_v0.9.0_linux_x86_64.tar.gz
tar -xvf kubens_v0.9.0_linux_x86_64.tar.gz
Finally, you move them to your PATH:
Once installed, you can simply use kubens to list the namespaces and switch between them:
When working with multiple clusters, kubectx makes switching between contexts a breeze:
Did you know that kubectl provides auto-completion for BASH and ZSH? This is an optional configuration.
Let’s say you understand the concepts of Kubernetes and have some experience with kubectl, but perhaps you aren’t so good at memorizing commands. First you install bash-completion, and then you enable kubectl autocompletion. You can find all the details in the “Install and Set Up kubectl“ documentation page for your environment.
Below are the config options with the autocompletion feature:
Now, just tab away!
The top command is probably one of the most popular tools to monitor processes and system resources. It provides a simple character-based interface and quick access to crucial information.
You can see resource utilization per node:
Resource utilization per pod:
And the handy watch command can help you display the command in a desirable interval without having to run it over and over again. The following example makes it run every five seconds (the default is two seconds):
watch kubectl top node -n 5
Note: The watch command needs to be downloaded for your environment.
Your Kubernetes cluster also needs to be running heapster in order for the top command work, otherwise you’ll get the following error: “Error from server (NotFound): the server could not find the requested resource (get services http:heapster:)”
The kubectl command provides a summarized view of the resources stored by the apiserver. There are many more fields stored by the apiserver that are not shown. You can use the kubectl get command with the raw resource output to create your own visualization and commands.
You can print the raw resources in JSON with the following command:
kubectl get deployments -o json
You can also call the resource directly using the api call:
kubectl get --raw=/apis/apps/v1/deployments
You can even combine the output with tools like jq to provide different visualizations, filter the output, or feed the output to other tools for advance automation.
For example, it can be hard to find issues on clusters with multiple namespaces and deployments, but the example below uses the raw API to scan all deployments in the cluster and filter only the deployments with failing replicas:
kubectl get --raw=/apis/apps/v1/deployments | jq '.items[]
| {name: .metadata.name, replicas: .status.replicas, available:
(.status.availableReplicas // 0), unavailable:
(.status.unavailableReplicas // 0)} | select (.unavailable > 0)'
The following is a quick explanation of the command above:
kubectl get --raw=/apis/apps/v1/deployments | jq .
kubectl get --raw=/apis/apps/v1/deployments | jq '.items[] |
{name: .metadata.name, replicas: .status.replicas, available:
(.status.availableReplicas // 0), unavailable:
(.status.unavailableReplicas // 0)}'
kubectl get --raw=/apis/apps/v1/deployments | jq '.items[] |
{name: .metadata.name, replicas: .status.replicas, available:
(.status.availableReplicas // 0), unavailable:
(.status.unavailableReplicas // 0)} | select (.unavailable > 0)'
We hope you find some of these tips and tricks useful as you work with Kubernetes. Let us know if you have a favorite tip or a tip of your own that you would like to share.
Don’t forget to check out the IBM Cloud Kubernetes Service and put these tips and tricks to use.
Want to get some free, hands-on experience with Kubernetes? Take advantage of IBM CloudLab, a new interactive platform that offers Kubernetes tutorials with a certification—no cost or configuration needed.
Red Hat OpenShift on IBM Cloud is a fully managed OpenShift Container Platform (OCP).
Container solutions run and scale-up containerized workloads with security, open source innovation, and rapid deployment.
Unlock new capabilities and drive business agility with IBM’s cloud consulting services. Discover how to co-create solutions, accelerate digital transformation, and optimize performance through hybrid cloud strategies and expert partnerships.