Skip to main content
Cheatsheet

The Ultimate Kubectl Command Cheat Sheet

Take a quick look at kubectl commands that are essential for managing your Kubernetes deployments.

β€” Sreenath V

Warp Terminal

Kubernetes is a powerful platform designed to manage and automate the deployment, scaling, and operation of containerized applications. In simple terms, it helps you run and manage your software applications in an organized and efficient way.

kubectl is the command-line tool that helps you manage your Kubernetes cluster. It allows you to deploy applications, manage resources, and get information about your applications. Simply put, kubectl is the main tool you use to communicate with Kubernetes and get things done.

In this article, we will explore essential kubectl commands that will make managing your Kubernetes cluster easier and more efficient.

Essential Kubernetes Concepts

Before diving into the commands, let's quickly review some key Kubernetes concepts to ensure a solid understanding.

  • Pod: The smallest deployable unit in Kubernetes, containing one or more containers that run together on the same node.
  • Node: A physical or virtual machine in the Kubernetes cluster where Pods are deployed.
  • Services: An abstraction that defines a set of Pods and provides a stable network endpoint to access them.
  • Deployment: A controller that manages the desired state and lifecycle of Pods by creating, updating, and deleting them.
  • Namespace: A logical partition in a Kubernetes cluster to isolate and organize resources for different users or teams.

General Command Line Options

This section covers various optional flags and parameters that can be used with different kubectl commands. These options help customize the output format, specify namespaces, filter resources, and more, making it easier to manage and interact with your Kubernetes clusters.

The get command in kubectl is used to retrieve information about Kubernetes resources. It can list various resources such as pods, services, nodes, and more.

To retrieve a list of all the pods in your Kubernetes cluster in JSON format,

kubectl get pods -o json

List all the pods in the current namespace and output their details in YAML format.

kubectl get pods -o yaml

Output the details in plain-text format, including the node name for each pod,

kubectl get pods -o wide

List all the pods in a specific namespace using the -n option:

kubectl get pods -n <namespace_name>

To create a Kubernetes resource from a configuration file, us the command:

kubectl create -f <filename>

To filter logs by a specific label, you can use:

kubectl logs -l <label_filter>

For example, to get logs from all pods labeled app=myapp, you would use:

kubectl logs -l app=myapp

For quick command line help, always use the -h option.

kubectl -h

Create and Delete Kubernetes Resources

In Kubernetes, you can create resources using the kubectl create command, update or apply changes to existing resources with the kubectl apply command, and remove resources with the kubectl delete command. These commands allow you to manage the lifecycle of your Kubernetes resources effectively and efficiently.

The apply and create are two different approaches to create resources in Kubernetes. While the apply follows a declarative approach, create follows an imperative approach.

Learn about these different approaches in our dedicated article.

kubectl apply vs create: What’s the Difference?
Two different approaches for creating resources in Kubernetes cluster. What’s the difference?

To apply a configuration file to a pod, use the command:

 kubectl apply -f <JSON/YAML configuration file>

If you have multiple JSON/YAML configuration files, you can use glob pattern matching here:

 kubectl apply -f '*.json'

To create a new Kubernetes resource using a configuration file,

kubectl create -f <configuration file>

The -f option can receive directory values or configuration file URL to create resource.

kubectl create -f <directory>

OR

kubectl create -f <URL to files>

The delete option is used to delete resources by file names, resources and names, or by resources and label selector.

To delete resources using the type and name specified in the configuration file,

 kubectl delete -f <configuration file>

Cluster Management and Context Commands

Cluster management in Kubernetes refers to the process of querying and managing information about the Kubernetes cluster itself. According to the official documentation, it involves various commands to display endpoint information, view and manage cluster configurations, list API resources and versions, and manage contexts.

The cluster-info command displays the endpoint information about the master and services in the cluster.

kubectl cluster-info

To print the client and server version information for the current context, use:

kubectl version

To display the merged kubeconfig settings,

kubectl config view

To extract and display the names of all users from the kubeconfig file, you can use a jsonpath expression.

kubectl config view -o jsonpath='{.users[*].name}'

Display the current context that kubectl is using,

kubectl config current-context

You can display a list of contexts with the get-context option.

kubectl config get-contexts

To set the default context, use:

kubectl config use-context <context-name>

Print the supported API resources on the server.

kubectl api-resources

It includes core resources like pods, services, and nodes, as well as custom resources defined by users or installed by operators.

You can use the api-versions command to print the supported API versions on the server in the form of "group/version". This command helps you identify which API versions are available and supported by your Kubernetes cluster.

kubectl api-versions

The --all-namespaces option available with the get command can be used to list the requested object(s) across all namespaces. For example, to list all pods existing in all namespaces,

kubectl get pods --all-namespaces

Daemonsets

A DaemonSet in Kubernetes ensures that all (or some) Nodes run a copy of a specified Pod, providing essential node-local facilities like logging, monitoring, or networking services. As nodes are added or removed from the cluster, DaemonSets automatically add or remove Pods accordingly. They are particularly useful for running background tasks on every node and ensuring node-level functionality throughout the cluster.

You can create a new DaemonSet with the command:

kubectl create daemonset <daemonset_name>

To list one or more DaemonSets, use the command:

kubectl get daemonset

The command,

kubectl edit daemonset <daemonset_name>

will open up the specified DaemonSet in the default editor so you can edit and update the definition.

To delete a daemonset,

kubectl delete daemonset <daemonset_name>

You can check the rollout status of a daemonset with the kubectl rollout command:

kubectl rollout status daemonset

The command below provides detailed information about the specified DaemonSet in the given namespace:

kubectl describe ds <daemonset_name> -n <namespace_name>

Deployments

Kubernetes deployments are essential for managing and scaling applications. They ensure that the desired number of application instances are running at all times, making it easy to roll out updates, perform rollbacks, and maintain the overall health of your application by automatically replacing failed instances.

In other words, Deployment allows you to manage updates for Pods and ReplicaSets in a declarative manner. By specifying the desired state in the Deployment configuration, the Deployment Controller adjusts the actual state to match at a controlled pace. You can use Deployments to create new ReplicaSets or replace existing ones while adopting their resources seamlessly. For more details, refer to StatefulSet vs. Deployment.

To list one or more deployments:

kubectl get deployment

To display detailed information about the specified deployment, including its configuration, events, and status,

kubectl describe deployment <deployment_name>

The below command opens the specified deployment configuration in the default editor, allowing you to make changes to its configuration:

kubectl edit deployment <deployment_name>

To create a deployment using kubectl, specify the image to use for the deployment:

kubectl create deployment <deployment_name> --image=<image_name>

You can delete a specified deployment and all of its associated resources, such as Pods and ReplicaSets by using the command:

kubectl delete deployment <deployment_name>

To check the rollout status of the specified deployment and providing information about the progress of the deployment's update process,

kubectl rollout status deployment <deployment_name>

Perform a rolling update in Kubernetes by setting the container image to a new version for a specific deployment.

kubectl set image deployment/<deployment name> <container name>=image:<new image version>

To roll back the specified deployment to the previous revision (undo),

kubectl rollout undo deployment/<deployment name>

The command below will forcefully replace a resource from a configuration file:

kubectl replace --force -f <configuration file>

Retrieving and Filtering Events

In Kubernetes, events are a crucial component for monitoring and diagnosing the state of your cluster. They provide real-time information about changes and actions happening within the system, such as pod creation, scaling operations, errors, and warnings.

Use the command:

kubectl get events

To retrieve and list recent events for all resources in the system, providing valuable information about what has happened in your cluster.

To filter and list only the events of type "Warning," thereby providing insights into any potential issues or warnings in your cluster,

kubectl get events --field-selector type=Warning

You can retrieve and list events sorted by their creation timestamp. This allows you to view events in chronological order.

kubectl get events --sort-by=.metadata.creationTimestamp

To lists events, excluding those related to Pod events,

kubectl get events --field-selector involvedObject.kind!=Pod

This helps you focus on events for other types of resources.

To list events specifically for a node with the given name,

kubectl get events --field-selector involvedObject.kind=Node, involvedObject.name=<node_name>

You can filter events, excluding those that are of the "Normal" type, allowing you to focus on warning and error events that may require attention:

kubectl get events --field-selector type!=Normal

Managing Logs

Logs are essential for understanding the real-time behavior and performance of your applications. They provide a record of activity and outputs generated by containers and pods, which can be invaluable for debugging and monitoring purposes.

To print the logs for the specified pod:

kubectl logs <pod_name>

To print the logs for the specified pod since last hour:

kubectl logs --since=1h <pod_name>

You can read the most recent 50 lines of logs for the specified pod using the --tail option.

kubectl logs --tail=50 <pod_name>

The command below streams and continuously displays the logs of the specified pod, optionally filtered by the specified container:

kubectl logs -f <pod_name> [-c <container_name>]

For example, as per the official documentation,

kubectl logs -f -c ruby web-1

Begin streaming the logs of the ruby container in pod web-1.

To continuously display the logs of the specified pod in real-time,

kubectl logs -f <pod_name>

You can fetch the logs up to the current point in time for a specific container within the specified pod using the command:

kubectl logs -c <container_name> <pod_name>

To save the logs for the specified pod to a file,

kubectl logs <pod_name> > pod.log

To print the logs for the previous instance of the specified pod:

kubectl logs --previous <pod_name>

This is particularly useful for troubleshooting and analyzing logs from a previously failed pod.

Namespaces

In Kubernetes, namespaces are used to divide and organize resources within a cluster, creating separate environments for different teams, projects, or applications. This helps in managing resources, access permissions, and ensuring that each group or application operates independently and securely.

To create a new namespace with the specified name in your Kubernetes cluster:

kubectl create namespace <namespace_name>

To list all namespaces in your Kubernetes cluster, use the command:

kubectl get namespaces

You can get a detailed description of the specified namespace, including its status, resource quotas using the command:

kubectl describe namespace <namespace_name>

To delete the specified namespace along with all the resources contained within it:

kubectl delete namespace <namespace_name>

The command

kubectl edit namespace <namespace_name>

opens the default editor on your machine with the configuration of the specified namespace, allowing you to make changes directly.

To display resource usage (CPU and memory) for all pods within a specific namespace, you can use the following command:

kubectl top pods --namespace=<namespace_name>

Nodes

In Kubernetes, nodes are the fundamental building blocks of the cluster, serving as the physical or virtual machines that run your applications and services.

To update the taints on one or more nodes,

kubectl taint node <node_name>

List all nodes in your Kubernetes cluster:

kubectl get node

Remove a specific node from your Kubernetes cluster,

kubectl delete node <node_name>

Display resource usage (CPU and memory) for all nodes in your Kubernetes cluster:

kubectl top nodes

List all pods running on a node with a specific name:

kubectl get pods -o wide | grep <node_name>

Add or update annotations on a specific node:

kubectl annotate node <node_name> <key>=<value>
πŸ“‹
Annotations are key-value pairs that can be used to store arbitrary non-identifying metadata.

Mark a node as unschedulable (no new pods will be scheduled on the specified node).

kubectl cordon node <node_name>

Mark a previously cordoned (unschedulable) node as schedulable again:

kubectl uncordon node <node_name>

Safely evict all pods from the specified node in preparation for maintenance or decommissioning:

kubectl drain node <node_name>

Add or update labels on a specific node in your Kubernetes cluster:

kubectl label node <node_name> <key>=<value>

Pods

A pod is the smallest and simplest unit in the Kubernetes object model that you can create or deploy. A pod represents a single instance of a running process in your cluster and can contain one or more containers. These containers share the same network namespace, storage volumes, and lifecycle, allowing them to communicate with each other easily and share resources.

Pods are designed to host tightly coupled application components and provide a higher level of abstraction for deploying, scaling, and managing applications in a Kubernetes environment. Each pod is scheduled on a node, where the containers within it are run and managed together as a single, cohesive unit.

List all pods in your Kubernetes cluster:

kubectl get pods

List all pods in your Kubernetes cluster and sort them by the restart count of the first container in each pod:

kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'

List all pods in your Kubernetes cluster that are currently in the "Running" phase:

kubectl get pods --field-selector=status.phase=Running

Delete a specific pod from your Kubernetes cluster:

kubectl delete pod <pod_name>

Display detailed information about a specific pod in your Kubernetes cluster:

kubectl describe pod <pod_name>

Create a pod using the specifications provided in a YAML file:

kubectl create -f pod.yaml

OR

kubectl apply -f pod.yaml

To execute a command in a specific container within a pod in your Kubernetes cluster:

kubectl exec <pod_name> -c <container_name> <command>

Start an interactive shell session in a container within a specified pod:

# For Single Container Pods
kubectl exec -it <pod_name> -- /bin/sh

# For Multi-container pods,
kubectl exec -it <pod_name> -c <container_name> -- /bin/sh

Display resource (CPU and memory) usage statistics for all pods in your Kubernetes cluster:

kubectl top pods

Add or update annotations on a specific pod:

kubectl annotate pod <pod_name> <key>=<value>

To add or update the label of a pod:

kubectl label pod <pod_name> new-label=<label name>

List all pods in your Kubernetes cluster and display their labels:

kubectl get pods --show-labels

Forward one or more local ports to a pod in your Kubernetes cluster, allowing you to access the pod's services from your local machine:

kubectl port-forward <pod_name> <port_number_to_listen_on>:<port_number_to_forward_to>

Replication Controllers

Replication Controller (RC) ensures that a specified number of pod replicas are running at any given time. If any pod fails or is deleted, the Replication Controller automatically creates a replacement. This self-healing mechanism enables high availability and scalability of applications.

To list all Replication Controllers in your Kubernetes cluster

kubectl get rc

List all Replication Controllers within a specific namespace:

kubectl get rc --namespace=”<namespace_name>”

ReplicaSets

ReplicaSet is a higher-level concept that ensures a specified number of pod replicas are running at any given time. It functions similarly to a Replication Controller but offers more powerful and flexible capabilities.

List all ReplicaSets in your Kubernetes cluster.

kubectl get replicasets

To display detailed information about a specific ReplicaSet:

kubectl describe replicasets <replicaset_name>

Scale the number of replicas for a specific resource, such as a Deployment, ReplicaSet, or ReplicationController, in your Kubernetes cluster.

kubectl scale --replicas=<number_of_replicas> <resource_type>/<resource_name>

Secrets

Secrets are used to store and manage sensitive information such as passwords, tokens, and keys.

Unlike regular configuration files, Secrets help ensure that confidential data is securely handled and kept separate from application code.

Secrets can be created, managed, and accessed within the Kubernetes environment, providing a way to distribute and use sensitive data without exposing it in plain text.

To create a Secret,

kubectl create secret (docker-registry | generic | tls)

List all Secrets in your Kubernetes cluster:

kubectl get secrets

Display detailed information about a specific Secret:

kubectl describe secret <secret_name>

Delete a specific Secret from your Kubernetes cluster:

kubectl delete secret <secret_name>

Services

Services act as stable network endpoints for a group of pods, allowing seamless communication within the cluster. They provide a consistent way to access pods, even as they are dynamically created, deleted, or moved.

By using a Service, you ensure that your applications can reliably find and interact with each other, regardless of the underlying pod changes.

Services can also distribute traffic across multiple pods, providing load balancing and improving the resilience of your applications.

To list all Services in your Kubernetes cluster:

kubectl get services

To display detailed information about a specific Service:

kubectl describe service <service_name>

Create a Service that exposes a deployment:

kubectl expose deployment <deployment_name> --port=<port> --target-port=<target_port> --type=<type>

Edit the configuration of a specific Service:

kubectl edit service <service_name>

Service Accounts

Service Accounts provide an identity for processes running within your cluster, enabling them to interact with the Kubernetes API and other resources. By assigning specific permissions and roles to Service Accounts, you can control access and limit the actions that pods and applications can perform, enhancing the security and management of your cluster.

Service Accounts are essential for managing authentication and authorization, ensuring that each component operates with the appropriate level of access and adheres to the principle of least privilege.

To list all Service Accounts in your Kubernetes cluster:

kubectl get serviceaccounts

Display detailed information about a specific Service Account:

kubectl describe serviceaccount <serviceaccount_name>

Next is replacing a service account. Before replacing, you need to export the existing Service Account definition to a YAML file.

kubectl get serviceaccount <serviceaccount_name> -o yaml > serviceaccount.yaml

Once you made changes to the YAML file, replace the existing Service Account with the modified one:

kubectl replace -f serviceaccount.yaml

Delete a specific Service Account from your Kubernetes cluster:

kubectl delete serviceaccount <service_account_name>

StatefulSet

StatefulSet is a specialized workload controller designed for managing stateful applications. Unlike Deployments, which are suitable for stateless applications, StatefulSets provide guarantees about the ordering and uniqueness of pods.

Each pod in a StatefulSet is assigned a unique, stable identity and is created in a specific order. This ensures consistency and reliability for applications that require persistent storage, such as databases or distributed systems.

StatefulSets also facilitate the management of pod scaling, updates, and rollbacks while preserving the application's state and data.

To list all StatefulSets in your Kubernetes cluster:

kubectl get statefulsets

To delete a specific StatefulSet from your Kubernetes cluster without deleting the associated pods:

kubectl delete statefulset <stateful_set_name> --cascade=false

πŸ’¬ Hope you like this quick overview of the kubectl commands. Please let me know if you have any questions or suggestions.