The Essential Kubectl Commands: Handy Cheat Sheet

As Kubernetes continues to gain popularity as a container orchestration system, mastering its command-line interface becomes increasingly vital for DevOps engineers and developers alike.

Kubectl, the Kubernetes command-line tool, is an essential component in managing and deploying applications in a Kubernetes cluster. This tool allows you to interact directly with the Kubernetes API server and control the state of your cluster.

It allows you to manage and control Kubernetes resources, deploy applications, troubleshoot issues, and perform various administrative tasks within a Kubernetes environment.

As the primary interface for managing Kubernetes clusters and resources, kubectl is a versatile and powerful tool that is integral to the Kubernetes ecosystem.

kubectl enables you to create, modify, and delete Kubernetes resources such as pods, deployments, services, config maps, and more. It provides commands to retrieve and follow logs of running pods, aiding in troubleshooting and diagnosing application issues.

This blog post aims to provide you with a comprehensive guide on the most important Kubectl commands and examples, so you can easily manage and monitor your Kubernetes clusters.

Table Of Contents

Setting Up Kubectl in Linux

To set up kubectl, you need to install the kubectl command-line tool and configure it to connect to your Kubernetes cluster. Follow these steps to set it up:

1. To prepare for using the Kubernetes apt repository, you need to update the apt package index and install the required packages.

sudo apt-get update
sudo apt-get install -y ca-certificates curl

For Debian 9 (stretch) or earlier versions, it is necessary to install apt-transport-https in addition to the other packages to use the Kubernetes apt repository.

2. Download the Google Cloud public signing key:

curl -fsSL https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo gpg --dearmor -o /etc/apt/keyrings/kubernetes-archive-keyring.gpg

3. Incorporate the Kubernetes apt repository

echo "deb [signed-by=/etc/apt/keyrings/kubernetes-archive-keyring.gpg] https://apt.kubernetes.io/ kubernetes-xenial main" | sudo tee /etc/apt/sources.list.d/kubernetes.list

4. Retrieve the latest package information from the apt package index, which includes the new repository, and proceed with installing kubectl.

sudo apt-get update
sudo apt-get install -y kubectl
Note: In releases older than Debian 12 and Ubuntu 22.04, /etc/apt/keyrings does not exist by default. You can create this directory if you need to, making it world-readable but writeable only by admins.

To explore detailed guidance on installing kubectl on various operating systems or exploring alternative approaches like different package managers or downloading the binary using the curl command, I suggest referring to the official Kubernetes documentation.

Basic Kubectl Commands

1. kubectl create

The kubectl create command is used to create resources in a Kubernetes cluster. The basic syntax for the kubectl create command is:

Example: kubectl create -f <file.yaml> (Creates a resource from a YAML file)

Here are two coding examples that utilize the kubectl create command, along with a brief explanation:

Example 1: Creating a resource from a YAML file

kubectl create -f deployment.yaml

This command creates a Kubernetes resource, such as a Deployment, based on the configuration provided in the deployment.yaml file. It is a convenient way to deploy resources defined in a YAML file to your Kubernetes cluster.

The contents of the deployment.yaml file should follow the YAML syntax and describe the desired Kubernetes resource.

Here's an example of a deployment.yaml file that creates a Deployment:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:latest
        ports:
        - containerPort: 80

Save the above content in a file named deployment.yaml, and then run the above kubectl create command.

This will create a Deployment named nginx-deployment with three replicas running the nginx:latest image.

Similarly, you can create other types of resources like Services, ConfigMaps, etc., using their respective YAML definitions and the kubectl create -f command.

Example 2: Creating a resource using inline configuration

kubectl create deployment my-deployment --image=nginx:latest --replicas=3

In this example, the kubectl create command is used to create a Deployment named my-deployment with an image nginx:latest and three replicas. The resource configuration is specified directly in the command without using a separate YAML file.

The kubectl create command is useful for creating Kubernetes resources from either YAML files or inline configuration. It allows you to define and deploy resources quickly, such as Deployments, Services, ConfigMaps, etc., either by providing the resource configuration in a file or by specifying it directly in the command. This command provides a convenient way to create resources without manually writing complex YAML configurations.

2. kubectl apply

Kubectl apply creates or updates a resource from a file or stdin.

Example: kubectl apply -f <file.yaml> (Creates or updates a resource from a YAML file)

Here are two coding examples that utilize the kubectl apply command, along with a brief explanation:

Example 1: Applying a resource from a YAML file

kubectl apply -f deployment.yaml

This command applies the configuration defined in the deployment.yaml file to create or update the corresponding Kubernetes resource. It is useful for deploying and managing resources like Deployments, Services, ConfigMaps, etc., by providing the desired configuration in a YAML file.

If you are using tools like Terraform, which is an IaaS, primarily used to automate various infrastructure tasks along with your Kubernetes setup, use the following kubectl command to manage the cluster:

terraform apply -auto-approve && kubectl apply -f deployment.yaml

Example 2: Applying inline configuration

kubectl apply -f - <<EOF
apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  containers:
  - image: nginx:latest
    name: my-container
EOF

In this example, the -f flag is used to apply the inline configuration directly from the command line. The resource configuration is specified within the <<EOF and EOF delimiters. This is useful for quickly creating or updating resources without using a separate YAML file.

The kubectl apply command is powerful for managing Kubernetes resources. It allows you to apply the desired configuration to create or update resources in your cluster, whether by using a YAML file or by providing the configuration inline. This command is commonly used for deploying and managing resources in a declarative manner, ensuring that the desired state of the resources is maintained.

3. kubectl get pods

kubectl get pods lists all pods in the current namespace.

Example: kubectl get pods

Here are two coding examples that utilize the kubectl get pods command, along with an explanation of their usage:

Example 1: Listing all pods in the current namespace

kubectl get pods

This command is used to retrieve a list of all pods running in the current namespace. When executed, it returns a table displaying information such as the pod name, status, age, and other relevant details. This is useful for getting an overview of the pods in your cluster and their current state.

Example 2: Filtering pods based on labels

kubectl get pods -l app=nginx

In this example, the -l flag is used to filter the pods based on a specific label. Here, the label app=nginx is used to narrow down the results to pods that have the label app with a value of nginx. This is particularly useful when you want to target specific pods for further operations or monitoring.

The kubectl get pods command is an essential tool for managing and monitoring pods in Kubernetes. It allows you to quickly obtain information about the pods in your cluster, such as their status, resource utilization, and labels. By default, it fetches information about all pods in the current namespace, but you can apply filters to narrow down the results based on specific criteria.

Using the kubectl get pods command helps administrators and developers gain visibility into the state of their pods, identify any issues, and perform further operations such as describing a pod in detail, accessing pod logs, or executing commands within a pod. It serves as a fundamental command for interacting with Kubernetes pods and is an integral part of troubleshooting, monitoring, and managing containerized applications.

4. kubectl delete

Kubectl delete deletes a resource.

Example: kubectl delete pod <pod-name>

Here are two coding examples that utilize the kubectl delete command, along with a brief explanation:

Example 1: Deleting a specific pod

kubectl delete pod my-pod

This command deletes a specific pod named my-pod. It is useful when you want to remove a specific pod from your cluster, either to clean up resources or to recreate the pod with updated configurations.

Example 2: Deleting resources using label selectors

kubectl delete pods -l app=nginx

In this example, the -l flag and the app=nginx label selector are used to delete all pods that have the label app with a value of nginx. This is helpful when you want to delete multiple pods that match a specific label, such as when removing pods associated with a particular application.

The kubectl delete command is essential for removing Kubernetes resources from your cluster. It allows you to delete specific pods, deployments, services, or other resources based on their names or label selectors. This command is valuable for resource management, cleanup, and updating configurations by deleting existing resources and allowing new ones to be created in their place.

Managing Pods

1. kubectl describe pod

kubectl describe pod provides detailed information about a specific pod.

Example: kubectl describe pod <pod-name>

Here are two coding examples that utilize the kubectl describe pod command, along with a brief explanation:

Example 1: Describing a specific pod

kubectl describe pod my-pod

This command provides detailed information about a specific pod named my-pod. It displays information such as pod status, IP address, container details, events, and more. It is useful for troubleshooting pod-related issues, understanding pod configurations, and gathering insights into the pod's current state.

Example 2: Describing multiple pods using label selectors

kubectl describe pod -l app=nginx

In this example, the -l flag and the app=nginx label selector are used to describe multiple pods that have the label app with a value of nginx. It provides detailed information about all pods matching the label selector. This can be useful when you want to investigate multiple pods with similar characteristics.

The kubectl describe pod command is valuable for gaining deeper insights into the details and events of a pod. It helps administrators and developers understand the pod's configuration, identify any errors or issues, and troubleshoot problems effectively. It is a handy command for diagnosing and debugging specific pod-related scenarios in Kubernetes clusters.

2. kubectl logs

kubectl logs retrieve the logs of a specific pod.

Example: kubectl logs <pod-name>

Here are two coding examples that utilize the kubectl logs command, along with a brief explanation:

Example 1: Retrieving logs from a specific pod

kubectl logs my-pod

This command retrieves the logs from a specific pod named my-pod. It is useful for troubleshooting and debugging purposes, allowing you to view the log output of a particular pod to identify any errors, exceptions, or application-specific information.

Example 2: Following logs in real-time

kubectl logs -f my-pod

In this example, the -f flag is used to follow the logs of a specific pod in real time. It continuously displays the log output as it is generated by the pod, enabling you to monitor the application's runtime behavior or track the progress of an ongoing process.

The kubectl logs command is a valuable tool for accessing and viewing the logs of Kubernetes pods. It provides insights into the internal workings of applications and can aid in diagnosing issues, monitoring application behavior, and verifying successful execution. Tailing the logs in real-time, allows for proactive monitoring and troubleshooting of running pods within your cluster.

3. kubectl exec

Kubectl exec executes a command on a specific pod.

Example: kubectl exec <pod-name> -- <command>

Here are two coding examples that utilize the kubectl exec command, along with a brief explanation:

Example 1: Executing a command in a specific pod

kubectl exec my-pod -- ls /app

This command executes the ls /app command within the specified pod named my-pod. It allows you to run arbitrary commands inside a pod's container, providing a way to inspect file systems, check environment variables, or perform any other desired operations within the container.

Example 2: Opening an interactive shell in a pod

kubectl exec -it my-pod -- /bin/bash

In this example, the -it flags are used to open an interactive shell session inside the specified pod. It launches the /bin/bash shell, allowing you to directly interact with the container's command line. This is particularly useful for debugging, troubleshooting, or performing manual operations within the container.

The kubectl exec command enables you to execute commands directly within a pod's container. It provides a way to interact with running containers, perform administrative tasks, troubleshoot issues, and gather information from within the pod's environment. This command is valuable for accessing and operating within the context of a specific container, facilitating efficient debugging and troubleshooting within Kubernetes clusters.

Managing Deployments

1. kubectl get deployment

kubectl get deployments lists all deployments in the current namespace.

Example: kubectl get deployments

Here are two coding examples that utilize the kubectl get deployments command, along with a brief explanation:

Example 1: Listing all deployments in the current namespace

kubectl get deployments

This command retrieves a list of all deployments running in the current namespace. It displays information such as the deployment name, desired replicas, current replicas, and available updates. It helps to quickly check the status and configuration of deployments in your cluster.

Example 2: Getting detailed information about a specific deployment

kubectl get deployment my-deployment -o yaml

This example retrieves detailed information about a specific deployment named my-deployment and outputs it in YAML format. It provides comprehensive information about the deployment's configuration, including labels, replicas, strategy, and more. It can be helpful for debugging, troubleshooting, or understanding the deployment's specifications.

The kubectl get deployments command is useful for obtaining an overview of deployments in a Kubernetes cluster. It allows you to retrieve essential details about deployments, such as the number of replicas, the status of rolling updates, and the labels associated with them. This information is valuable for managing and monitoring your application deployments efficiently.

2. kubectl scale

Kubectl scale scales the number of replicas in a deployment, replicaset, or statefulset.

Example: kubectl scale deployment <deployment-name> --replicas=3

Here are two coding examples that utilize the kubectl scale command, along with a brief explanation:

Example 1: Scaling a deployment

kubectl scale deployment my-deployment --replicas=3

This command scales the deployment named my-deployment to have three replicas. It increases the number of instances of the application running in the cluster, providing high availability and increased capacity for handling incoming requests or workloads.

Example 2: Scaling a stateful set

kubectl scale statefulset my-statefulset --replicas=5

In this example, the kubectl scale command is used to scale the stateful set named my-statefulset to have five replicas. It adds more instances of the stateful application, ensuring data persistence and enabling horizontal scalability for stateful workloads.

The kubectl scale command is useful for adjusting the number of replicas in a deployment, replicaset, or statefulset. It allows you to scale your applications dynamically based on workload demands, performance requirements, or operational needs. Scaling up or down helps to ensure optimal resource utilization, improved performance, and seamless management of application instances in Kubernetes clusters.

3. kubectl rollout

The kubectl rollout command is used to manage the rollout process of a deployment in Kubernetes. It allows you to control the deployment of new versions of your application, handle rollbacks in case of issues, and monitor the progress of the rollout.

Let's explore two examples that demonstrate the usage of the kubectl rollout command:

Example: Rolling out a new version of an application

Suppose you have a deployment named ngnix-deployment running version 1.0 of your application. After making changes, you intend to deploy version 2.0. Here's how you can employ kubectl rollout:

Step:1 - Check the current status of the deployment:

kubectl rollout status deployment/nginx-deployment

Step:2 - Update the deployment's image to use the new version:

kubectl set image deployment/nginx-deployment nginx=nginx:2.0

By executing this command, you modify the image of the nginx deployment's container to nginx:2.0.

Step:3 - Monitor the progress of the rollout:

kubectl rollout status deployment/nginx-deployment

Utilize this command to track the current status of the rollout, including details such as the number of updated replicas and the desired replica count.

Working with Services

1. kubectl expose

The kubectl expose command in Kubernetes is employed to create a service for a deployment. Services provide a reliable and consistent network endpoint that allows communication with the pods managed by the deployment. They enable seamless access to the pods for other applications or services.

Let's explore two examples that demonstrate the usage of the kubectl expose command:

Example 1: Creating a ClusterIP service for a deployment

Suppose you have a deployment called nginx that manages a set of pods running your application. The objective is to expose these pods internally within the cluster. Here's how you can utilize kubectl expose:

Create a ClusterIP service for the deployment:

kubectl expose deployment/nginx-deployment --name=myapp-service --port=8080

By executing this command, a ClusterIP service named myapp-service is created. It directs traffic to the pods managed by the nginx-deployment deployment on port 8080.

Example 2: Creating a NodePort service for a deployment

Suppose you aim to expose the pods managed by the nginx-deployment deployment to external traffic. Here's how you can utilize kubectl expose to create a NodePort service:

Create a NodePort service for the deployment:

kubectl expose deployment/nginx-deployment --name=myapp-service --port=8080 --target-port=80 --type=NodePort

2. kubectl get service

The kubectl get service command in Kubernetes allows you to retrieve a list of services that are currently running within the cluster. Services provide stable network endpoints for accessing and communicating with pods, enabling seamless interaction with applications or services.

Let's explore two examples that demonstrate the usage of the kubectl get service command:

Example 1: Listing all services in the cluster

To obtain a comprehensive list of all services running in the cluster, you can execute the kubectl get service command without any additional parameters:

kubectl get service

Executing this command will present a table containing detailed information about each service. The information includes the service name, type, cluster IP, external IP (if applicable), and the associated ports.

Example 2: Filtering services by labels

In situations where you only want to list specific services based on assigned labels, you can utilize the kubectl get service command with the --selector or -l flag followed by the label selector. Consider the following example:

kubectl get service -l app=nginx

By executing this command, only the services that possess the label app with the value nginx will be listed. The output will provide details of the matching services, including their names, types, cluster IPs, external IPs (if applicable), and ports.

3. kubectl port-forward

Kubectl port-forward forwards a local port to a port on a pod.

Example: kubectl port-forward <pod-name> <local-port>:<pod-port>

Here are two coding examples that utilize the kubectl port-forward command, along with a brief explanation:

Example 1: Forwarding a local port to a pod

kubectl port-forward my-pod 8080:80

This command forwards the local port 8080 to port 80 on the pod named my-pod. It establishes a secure tunnel between the local machine and the pod, allowing you to access the pod's service or application running on port 80 via localhost:8080.

Example 2: Forwarding a local port to a service

kubectl port-forward service/my-service 8888:8080

In this example, the port-forward command is used to forward local port 8888 to port 8080 of the Kubernetes service named my-service. It enables you to access the service from your local machine by navigating to localhost:8888.

The kubectl port-forward command allows you to create a secure tunnel between a local port and a port on a pod or service. It is useful for accessing applications or services running within your Kubernetes cluster from your local machine. This feature is particularly handy for debugging, testing, or interacting with applications during development or troubleshooting processes.

Configuring and Debugging

1. kubectl config

The kubectl config command in Kubernetes is essential for managing kubeconfig files, which hold crucial information about clusters, users, and contexts required for authentication and accessing Kubernetes clusters.

It allows actions such as viewing, adding, modifying, and switching between different configurations.

Let's explore two simple examples that demonstrate the usage of the kubectl config command:

Example 1: Viewing the current context

To retrieve information about the currently active context within your kubeconfig file, you can execute the kubectl config current-context command:

kubectl config current-context

By running this command, you can obtain the name of the current context being used for interactions with the Kubernetes cluster.

Example 2: Switching to a different context

In scenarios where you have multiple contexts defined in your kubeconfig file, you can switch between them using the kubectl config use-context command. For example, if you have a context named "production" and want to switch to it, you would run the following command:

kubectl config use-context production

Executing this command will set the "production" context as the active context in your kubeconfig file. Subsequent Kubernetes commands will be executed against the specified cluster and user credentials associated with that context.

Note: Prior to utilizing the kubectl config use-context command, ensure that the context you intend to switch to is defined within your kubeconfig file.

2. kubectl describe

The kubectl describe command in Kubernetes is utilized to obtain detailed information about various Kubernetes resources, including pods, services, deployments, and more. It provides an extensive overview of the selected resource's current state, including its configuration, events, and relevant status updates.

Let's consider a simple example that demonstrates the usage of the kubectl describe command:

Example: Describing a Pod

Suppose you have a pod named "my-pod" running in your Kubernetes cluster, and you wish to retrieve comprehensive information about it. You can employ the kubectl describe command as shown below:

kubectl describe pod my-pod

Executing this command will present a detailed description of the specified pod. It encompasses various aspects such as its current status, associated labels and annotations, IP address, containers within the pod, volumes mounted, and any relevant events or conditions that have occurred.

This detailed information aids in troubleshooting issues, understanding the pod's behavior, and diagnosing any problems that may arise.

The output provided by the kubectl describe command offers valuable insights into the specified Kubernetes resource, allowing for a comprehensive understanding of its configuration and current state.

You can apply this command to other resources such as services, deployments, or nodes to obtain specific information about those resources as well.

3. kubectl get events

The kubectl get events command is utilized to fetch the events related to various resources within the cluster. These events offer insightful information about the lifecycle and status of resources like pods, services, deployments, and more. Let's consider a simple example that demonstrates the usage of the kubectl get events command:

Example: Retrieving events for all resources

To obtain a list of events for all resources in the cluster, you can execute the kubectl get events command:

kubectl get events

By running this command, a table will be displayed containing detailed information about each event. This includes the associated resource, event type (such as Normal or Warning), the reason behind the event, and the timestamp indicating when the event occurred. These events provide visibility into resource creations, deletions, updates, errors, or other significant occurrences.

By default, events are sorted in ascending order based on their timestamps, with the most recent events appearing at the end. However, you can use additional flags like --sort-by to customize the sorting criteria. For instance, you can use --sort-by='.metadata.creationTimestamp' to sort events based on their creation time.

Note: The events shown by the kubectl get events command are limited to the event history stored in the cluster, which may adhere to a retention policy or time window.

Resource Monitoring and Metrics

1. kubectl top

The kubectl top command in Kubernetes is utilized to fetch resource utilization metrics for nodes and pods within the cluster. It provides valuable information about CPU and memory usage, enabling you to monitor and analyze the performance of your Kubernetes resources effectively.

Let's consider a simple example that demonstrates the usage of the kubectl top command:

Example: Retrieving resource utilization for pods

To obtain resource utilization metrics for pods in your cluster, you can execute the kubectl top pod command:

kubectl top pod

Executing this command will display a table containing comprehensive details about each pod. This includes the pod's name, namespace, CPU usage, memory usage, and corresponding percentage values. CPU usage is commonly represented in millicores (m), while memory usage is indicated in bytes (B) or as KiB/MiB/GiB.

These metrics provide insights into pod resource consumption patterns, assisting in the identification of potential bottlenecks or issues.

If you want to narrow down the results to a specific namespace, you can specify it using the following command:

kubectl top pod -n production

This command will retrieve resource utilization metrics exclusively for pods within the production namespace.

Note: Prior to using the kubectl top command, ensure that the metrics server is installed and running in your cluster. The metrics server is responsible for collecting and providing resource utilization data. If it is not available, you may need to install it first.

2. kubectl describe node

The kubectl describe node command in Kubernetes is utilized to obtain an elaborate description of a specific node within the cluster. It provides comprehensive information about the node's configuration, current status, available resources, and other pertinent details.

Let's consider a simple example that demonstrates the usage of the kubectl describe node command:

Example: Describing a node

To retrieve detailed information about a particular node in your Kubernetes cluster, execute the kubectl describe node command followed by the node's name. For instance, suppose you have a node named "my-node" and wish to obtain its description. Utilize the following command:

kubectl describe node my-node

Upon executing this command, a detailed description of the specified node will be displayed. It includes pertinent information like the node's name, associated labels, network addresses, capacity (CPU and memory), resource utilization metrics, current conditions, and other relevant details. This description provides valuable insights into the node's configuration, overall status, and any potential issues it might be encountering.

Analyzing the output of the kubectl describe node command allows you to gather crucial information about the specified node, including its available resources, network addresses, and ongoing events or conditions. Such information is invaluable for troubleshooting, resource planning, and optimizing the performance of your Kubernetes cluster.

Note: The kubectl describe node command provides information about a single node at a time. To describe multiple nodes simultaneously, you can specify their names separated by spaces.

Conclusion

With kubectl, you can execute commands, run scripts, or open an interactive shell inside a pod's container for debugging or performing manual operations.

It provides commands to gather information about the cluster, such as listing nodes, namespaces, services, and viewing detailed information about specific resources. It supports authentication and authorization mechanisms, allowing you to interact with the Kubernetes cluster based on your assigned permissions and roles.

These commands should give you a good starting point for working with kubectl in Kubernetes. Remember to replace <pod-name> and <deployment-name> with the actual names of your pods and deployments.

kubectl is a versatile and powerful tool that serves as the primary interface for managing Kubernetes clusters and resources, making it an essential component in the Kubernetes ecosystem.


Monitor Your Entire Application with Atatus

Atatus is a Full Stack Observability Platform that lets you review problems as if they happened in your application. Instead of guessing why errors happen or asking users for screenshots and log dumps, Atatus lets you replay the session to quickly understand what went wrong.

We offer Application Performance Monitoring, Real User Monitoring, Server Monitoring, Logs Monitoring, Synthetic Monitoring, Uptime Monitoring, and API Analytics. It works perfectly with any application, regardless of framework, and has plugins.

Application Performance Monitoring
Application Performance Monitoring

Atatus can be beneficial to your business, which provides a comprehensive view of your application, including how it works, where performance bottlenecks exist, which users are most impacted, and which errors break your code for your frontend, backend, and infrastructure.

If you are not yet an Atatus customer, you can sign up for a 14-day free trial.

Atatus

#1 Solution for Logs, Traces & Metrics

tick-logo APM

tick-logo Kubernetes

tick-logo Logs

tick-logo Synthetics

tick-logo RUM

tick-logo Serverless

tick-logo Security

tick-logo More

Aiswarya S

Aiswarya S

Writes on SaaS products, the newest observability tools in the market, user guides and more.