Using Kubectl Effectively | Best Practices for Beginners
Tags: kubernetes, go, gke, eks
Published: 2022-02-16 00:33:40

[Kubectl](https://kubernetes.io/docs/tasks/tools/) is the most popular command-line tool for interacting with Kubernetes clusters. However, the tool comes with a slightly steep learning curve for absolute beginners. In this guide, I will help you understand the basics of kubectl and share some tips to get the best out of the command-line tool.

## What is Kubectl?

Kubernetes is one of the world’s most popular container orchestration platforms. It offers a dedicated container runtime and an API to interact with and manage the running containers. However, you need a tool to interact with its APIs. [kubectl fills this gap](https://www.containiq.com/post/kubectl-cheat-sheet) for you.

As mentioned before, kubectl is an open-source tool that enables you to interact with your Kubernetes cluster via the command line. You can manage and apply configurations to your Kubernetes clusters with the help of a few simple commands. 

Kubectl merely acts as an interface between your command line and the Kubernetes API. You can use it to view the state of your Kubernetes clusters and issue modifications as needed.

## The Basics of Kubectl | Use Cases

Before we get into this actionable set of tips for kubectl, let’s discuss some of its basic commands to understand how to get started with it. kubectl provides a short list of helpful commands that you can use to get nearly everything done with your Kubernetes cluster.

### kubectl apply

The apply command is probably the most used in this list. It lets you update a K8s resource using a file or your standard input, i.e., input via the command line.

Here’s how you can use it:
kubectl apply -f configuration_file.yaml

You can supply any file in the current directory as the configuration file to be used by the command. It will automatically modify the state of your K8s cluster to match that defined in the configuration file.

### kubectl describe

The describe command is used to display, in detail, the state of one of more K8s resources. You can use it to view the state of your nodes, pods, etc., and even apply basic filters to find the resource you are looking for.

Here’s how you can use it:

- when you know the name of the pod
kubectl describe pods <pod-name>

- when you need to view the details of all pods
kubectl describe pods

- when you are looking for pods created by a certain replication controller
kubectl describe pods <rc-name>

### kubectl get

The get command is quite straightforward—it enables you to list one or more K8s resources from your cluster. Here’s how you can use it in various scenarios:

- to print all pods on screen
kubectl get pods

- to print all services on screen
kubectl get services

- to list all pods running on server07
kubectl get pods --field-selector=spec.nodeName=server07

### kubectl exec

The exec command is used to execute a command against a resource in the K8s cluster. Here’s how you can use the command:

kubectl exec <pod-name> -- <command to be executed>

### kubectl delete
The delete command is an important method to delete resources from your K8s cluster. You can perform delete operations based on label selectors, names, resource selectors, etc., or via a file/stdin. Here’s how you can use the command:

- delete a pod based on details provided by the file
kubectl delete -f pod_details.yml

- delete all services from the cluster
kubectl delete services --all

## Kubectl Best Practices

Now that you understand how to get started with kubectl, here are a couple of tips you should keep in mind to get the most out of the popular command-line tool.

### Use the “record” option for easier rollbacks

A few kubectl commands allow you to add a record flag towards the end. Adding this flag enables you to record the deployment changes as resource annotations. You can then access these changes when needed and roll them back too. Here’s how you can do it:

kubectl apply -f config_file.yaml --record

And here’s how you can access the recorded changes:

kubectl rollout history deployments some-deployment

### Use Descriptive Labels

Labels are powerful when it comes to marking and querying K8s resources. They allow you to tag a resource based on its use/design/purpose etc. You can then query and filter across the list of the resources based on these tags.

kubectl also allows you to apply batch operations on a list of resources at once if you can find the right conditions to filter them out at once. Basic operations such as deletion can be carried out at once, reducing the manual work you’d have had to do otherwise.

### Prefer version-specific tags over :latest

Using the latest can result in unintended ambiguity since the latest version of the container images might not always contain the changes you need. Therefore it is best to tag each resource with their versions and use these version-specific tags whenever you need to access any of the resources in the future. A little extra effort spent in tagging can save you a lot of effort that you’d have to put in if you pull the wrong version of a resource accidentally.

### Apply a Set of Config Files by Passing the Directory Name
While this feature is defined quite clearly in the docs, most beginners often forget it when working with kubectl. Instead of applying one config file at a time using the kubectl apply command, you can choose to provide a directory that contains multiple configuration files and have them applied at once. Here’s how you can do that:

kubectl apply -f <directory-name>

### Use Full Version Names Wherever Possible

Whenever you try to set up a new resource in your Kubernetes cluster, always mention the complete version names wherever possible. If you resort to a shorthand version name or make a typo in the version name due to which K8s is unable to recognize the required version, it might revert to the default versions, which might not be what you’re looking for. Always be extra careful with your version names.

### Use the --sort-by Flag to Sort Output Data

When handling tabular outputs from kubectl commands, you can pass in a --sort-by flag to arrange the output as needed. This can come in handy when you are trying to find a specific row through a large pile of output without having to store it out in a file and run through it manually.

### Preview Deployment Object Before Sending Them to the Cluster

When running an image on a cluster, you can preview it using the --dry-run=client flag. This helps you test the image without spending resources by deploying it.

### When Formatting Output, Prefer Machine-oriented Formats
When generating outputs for later use, always prefer a machine-oriented format such as JSON or YAML. These formats can be easily processed using tools in any programming language to generate the desired results. They can also be fed back to Kubernetes-specific tools to create native visualizations and analysis.

## Final Thoughts

kubectl is one of the essential tools to know when working with Kubernetes clusters. In this guide, we walked you through the basics of this tool and shared with you some tips and tricks to get the best out of your Kubernetes cluster via kubectl. We hope that this guide helps you learn and use kubectl effectively in your day-to-day K8s endeavors!