9 min read
Eyal Katz

The Complete kubectl Cheat Sheet

Kubectl provides a variety of methods for engaging with your Kubernetes cluster, making it a popular choice for developers and administrators when troubleshooting issues or implementing modifications to a cluster. Discover more with Control Plane.

The Complete kubectl Cheat Sheet

Command line clients (CLIs) allow users to execute a given set of operations quickly – yet there’s a steep learning curve and initial investment into training. Users need to memorize a given set of commands that can vary significantly from one command line client to another. Plus, like most things, mastery takes time and practice. 

Kubernetes has a significant role in today’s tech landscape, as evidenced by its adoption by over 50% of Fortune 100 companies. Yet, it can be incredibly complicated to manage this container orchestration platform. When wielded correctly, using a command line client can be an invaluable tool in a developer’s arsenal. The default tool for Kubernetes, kubectl, is no different. 

kubectl offers an array of ways to interact with your Kubernetes cluster. It is often the first tool developers and administrators reach for when trying to diagnose a problem or make changes to a cluster. 

What is Kubernetes?

To start with the basics, Kubernetes, often abbreviated to K8s, is a powerful orchestration tool designed to automate containerized application deployment, scaling, and management. At its core, Kubernetes acts as a container orchestrator, allowing users to manage clusters of containers efficiently. It operates based on a system of nodes, where each node can host multiple containers.

At the heart of Kubernetes lies its extensive use of APIs (Application Programming Interfaces). These APIs are the primary means of interaction and communication within the Kubernetes ecosystem. They enable users to manipulate and control various aspects of the cluster, from deploying applications to scaling resources and managing configurations.

Kubernetes cluster

What is kubectl?

kubectl is the command-line interface that enables users to communicate with Kubernetes clusters, even in multi-tenant environments. It acts as a bridge, facilitating direct communication between administrators or developers and the Kubernetes API server. 

kubectl translates user commands into API calls, abstracting the complexity of interacting directly with the API server. Doing so provides a much more user-friendly interface, and allows developers and administrators to execute actions and retrieve information from Kubernetes clusters without in-depth knowledge of underlying APIs.

What are some common kubectl use cases?

kubectl has many use cases, including cluster administration, debugging, and scaling deployments. Let’s discuss four in particular: 

  1. Deployment management: Deploying and managing applications within Kubernetes clusters becomes easier, as kubectl enables users to create, update, and delete deployments seamlessly. This ensures applications run smoothly.
  2. Resource scaling: Scaling resources is more efficient through kubectl. You can dynamically scale the number of pods or change the resources allocated to applications, optimizing performance and costs as demands fluctuate.
  3. Cluster inspection: kubectl facilitates comprehensive cluster inspection by allowing users to retrieve information about nodes, pods, services, and other Kubernetes objects. This feature aids in monitoring and debugging.
  4. Configuration and troubleshooting: Configuration and troubleshooting issues become more manageable with kubectl. Users can modify configurations and diagnose problems swiftly through its command-line interface.

kubectl is an essential foundational component of infrastructure management. To see more examples of kubectl in action, read our recent blog on orchestrating Kubernetes with Terraform

The complete kubectl cheat sheet

Let’s dive into time-saving tricks designed to help streamline your experience using kubectl, from shortcuts for quick navigation to handy commands for managing clusters and accessing vital information. 

1. Setup

The first step is to set up kubectl autocomplete in your terminal. Before starting, you need to make sure you have the bash-completion package installed. If not, you can install it with one of the following commands:

# For Debian based distro
sudo apt-get install -y bash-completion

# For Red-hat based distro
sudo yum install bash-completion

Once the package is installed, you can then set up autocomplete:

# Set up kubectl autocomplete in Bash (replace 'bash' with shell of choice)
source <(kubectl completion bash)

# add autocomplete permanently to your bash shell.
echo "source <(kubectl completion bash)" >> ~/.bashrc 

Configuring autocomplete can help you save time when typing out frequently used commands. A good example is running kubectl apply instead of typing out the entire command. You can type kubectl app + <tab> on your keyboard, and your shell will automatically complete with the most relevant command.

You can also set up custom kubectl aliases. Shell aliases aren’t new, and with kubectl, they can dramatically speed up your workflow by allowing you to assign short names to repetitive or complex commands, as you can see below. 

alias k=kubectl
alias kg='kubectl get'
alias kd='kubectl describe'
alias ka='kubectl apply'
alias kdelf='kubectl delete -f'
alias kl='kubectl logs'

2. Cluster management

Contexts in Kubernetes allow users to quickly switch between two or more clusters. It is useful when working with multiple clusters in different cloud environments or even when running more than one cluster locally. 

# Set your kube-context
kubectl config use-context <context-name>

# View available contexts
kubectl config get-contexts

# Show nodes in the cluster
kubectl get nodes

# Sort nodes by CPU
kubectl get nodes --sort-by=.status.capacity.cpu 

# Display detailed information about a node
kubectl describe node <node-name>

3. Namespace

The logical constructs of a Kubernetes deployment

Namespaces in Kubernetes allow administrators to isolate resources within a cluster; this isolation enables administrators to manage a group of shared resources independently. An excellent example is multiple teams using a single cluster; instead of creating a cluster per team, an administrator could create a namespace for each team. Below are some helpful kubectl commands to remember when working with namespaces. 

# List all namespaces
kubectl get namespaces

# Create a new namespace
kubectl create namespace <namespace-name>

# Watch for changes in a namespace
kubectl get all --watch --namespace=<namespace-name>

# Delete all resources within a namespace 
kubectl delete all --all --namespace=<namespace-name> 

4. Resource types 

Resource types refer to Kubernetes-specific objects – this can be anything from Pods, Deployments, or Services. Below are some essential commands to keep in mind when working with Kubernetes resources. 

# List specific resource type 
kubectl get <resource-type> 

# Display detailed information about a resource type 
kubectl get <resource-type> <resource-name> -o yaml

# Display resource utilization 
kubectl top <resource-type>

# Export resource definitions to yaml 
kubectl get <resource-type> <resource-name> -o yaml > <resource-definition.yaml>

Download your complete kubectl cheat sheet

5. Security

Proper access control and a Zero Trust approach is essential for any software, including the protection and management of Kubernetes secrets. With the following kubectl commands, you can view a resource’s permissions quickly, which will help you debug role-based access control errors faster.

# Display service account details 
kubectl get serviceaccount <service-account-name> -n <namespace> 

# Show role details 
kubectl get role <role-name> -n <namespace>

# Show clusterole details 
kubectl get clusterrole <cluster-role-name> 

6. Events 

Events in Kubernetes generally indicate the change in a resource in the cluster somewhere; this is great as it can quickly provide context to administrators about the state of the cluster.

# Filter events by a specific resource type
kubectl get events --field-selector involvedObject.kind=<resource-type>

# Describe an event in a specific namespace
kubectl describe event <event-name> -n <namespace> 

# Watch events as they occur 
kubectl get events --watch

# Filter events by a specific type, such as Normal or Warning
kubectl get events --field-selector type=<event-type>

7. Pods

Pods are the smallest deployable units of computing that you can create and manage in Kubernetes. Pods play a critical role in optimizing your Kubernetes workloads and ensuring optimal performance. When debugging, you might find yourself looking through logs from a pod or even trying to execute commands inside one. 

# Get detailed information about a pod 
kubectl describe pod <pod-name>

# Execute commands in a pod
kubectl exec -it <pod-name> -- <command>

# Enable port forwarding for pod access
kubectl port-forward <pod-name> <local-port>:<pod-port>

# Create debug container in a pod
kubectl debug -it <pod-name> --image=<debug-container-image>

8. Deployments 

Kubernetes deployment

Deployments manage a set of pods and ensure your application is running in the desired state. When you use Kubernetes, you’ll inevitably write a deployment at some point along the line. 

# List all deployments
kubectl get deployments

# Describe a specific deployment
kubectl describe deployment <deployment-name>

# Check the status of deployment rollout 
kubectl rollout status deployment/<deployment-name> 

# View history of deployment changes
kubectl rollout history deployment/<deployment-name>

# Rollback deployment to a previous revision 
kubectl rollout undo deployment/<deployment-name> --to-revision=<revision-number>

# Scale a deployment 
kubectl scale deployment/<deployment-name> --replicas=<replica-count>

See this guide for more advice on successfully pulling off a seamless Kubernetes deployment

Master and centralize Kubernetes usage with Control Plane

In the realm of Kubernetes, kubectl is a formidable tool for developers and administrators, allowing you to fine-tune clusters at your whim. However, it’s still easy for infrastructure to spiral out of control and for time and financial investments to be wasted on re-inventing the cloud-native maturity wheel. 

As your organization grows, the need for centralized mastery becomes pivotal. While Kubernetes allows you to orchestrate workloads within a single cluster, platforms like Control Plane manage your workloads to provide an unlimited number of hardened, security-isolated Kubernetes clusters anywhere you need them to be located.

Control Plane provides an Internal Developer Platform (IDP) that helps you maximize Kubernetes usage no matter your level of expertise, to intertwine clusters from various locations into a unified platform for your infrastructure. No prior experience in Kubernetes or tools like kubectl is necessary, and a best-of-breed CloudOps stack is included by default for rapid time-to-market without the stress.

Schedule a demo or get in touch with us today for more info.