Hot Summer Sale - up to 36% OFF

Kubectl Commands Cheat Sheet (With Examples)

Kubectl Commands Cheat Sheet (With Examples)
Published on Jun 20, 2025 Updated on Jun 20, 2025

Kubernetes offers kubectl - a nifty and powerful command-line tool for managing cluster resources. You can create, update, and delete resources and perform other cluster management tasks.

This tutorial covers essential Kubectl command operations and illustrates widely used commands for interacting with cluster components.

#What is Kubernetes and Kubectl

Despite simplifying the building and packaging of applications, containerization is fraught with numerous challenges. Security can be a huge concern regarding storing sensitive data and privilege escalation. Networking configurations can get complex as more pods are added, and resource overhead can cause performance bottlenecks, leading to service degradation. This is where Kubernetes comes in.

Kubernetes is the talk of the town in container orchestration. It’s an undeniably robust platform that packs comprehensive features for automating the deployment and management of containerized applications at scale.

Kubectl is a CLI tool that interacts with various components in the cluster. It lets you deploy, view, and inspect resources, view logs, and troubleshoot issues. Essentially, It’s a CLI cluster management tool.

Build and scale your self-managed Kubernetes clusters effortlessly with powerful Dedicated Servers — ideal for containerized workloads.

#Cluster Management

A cluster is a group of nodes - essentially the Master node and worker nodes - that operate together to run containerized applications. The master node ( The brain of the cluster) manages the cluster and schedules workloads on worker nodes. Worker nodes offer an environment for running pods.

kubectl cluster-info: The command Checks cluster information.

Command Line
kubectl cluster-info

The output provides information such as the Control plane and CoreDNS URLs. kubectl config view: Displays detailed cluster configuration details

Command Line
kubectl config view

The output includes detailed information such as the path of the SSL certificate, server URL, and context.

kubectl api-resources: Lists available API resources

Command Line
kubectl  api-resources

The command outputs all API resources supported by the node or server.

kubectl api-versions: Queries supported API versions.

Command Line
kubectl  api-versions

The output includes API versions as group/version. It provides information about APIs in the target cluster.

kubectl config current-context - Displays current contexts

Command Line
kubectl  config current-context

Typically, this displays the control plane’s name. For example, if you are running a Minikube cluster locally, you will get the following output.

Outputminikube

kubectl config get-contexts - Displays the cluster’s vital information, including name and namespace. Here is the sample output.

Command Line
kubectl  config get-contexts
OutputCURRENT   NAME       CLUSTER    AUTHINFO   NAMESPACE
*                   minikube   minikube        minikube      default

#Namespaces

A namespace is to a cluster what a vLAN is to a network. It is a logical separation within a cluster that allows for separating resources such as pods and services. A namespace effectively creates sub-clusters that allow different applications, users, and teams to operate independently while sharing the cluster. This logical division provides access control to specific namespaces and helps with efficient resource organization and management.

kubectl get namespaces - Lists all namespaces in the cluster.

Command Line
kubectl  get namespaces

The output provides the names of all namespaces, their statutes, and how long they have been active.

kubectl describe namespace namespace-name - Display detailed information about a namespace.

Command Line
kubectl  describe namespace default

The example above gives more insights into the default namespace. Details include name, labels, status, and resource quotas.

kubectl create namespace namespace-name - Creates a namespace

Command Line
kubectl  create namespace sample-ns

The above command creates a namespace called sample-ns.

kubectl config set-context --current --namespace=namespace-name - The command sets the default namespace for your project.

In this example, the namespace sample-ns has been configured as the default namespace.

Command Line
kubectl  config set-context --current --namespace=sample-ns

kubectl config view | grep namespace - Displays the default namespace.

kubectl config view | grep namespace 

kubectl delete namespace namespace_name – Deletes a specific namespace.

For example, to delete the namespace sample-ns run the command:

Command Line
kubectl  delete namespace sample-ns

NOTE: Once a namespace is deleted, you need to set the default namespace from the available namespaces in your cluster. Alternatively, you can create a new one and set it as the default.

#Pods

The smallest deployable components in a Kubernetes cluster are called pods. They constitute one or more containers and are scheduled by the control plane on worker nodes. Typically, a pod houses a single container, but it can also house multiple containers, especially when operating as one unit.

kubectl get pods - The command List all pods

Command Line
kubectl  get pods

The output prints out currently running pods with basic information such as pod name, status, and how long the pod has been active.

kubectl get pods -o wide - List all pods and provides detailed information such as IP address and node on which the pod is running.

Command Line
kubectl  get pods -o wide
OutputNAME                         READY   STATUS    RESTARTS   AGE     IP           NODE       NOMINATED NODE   READINESS GATES
nginx-app-65fd5796b9-vdmb4   1/1     Running   0          2m14s   10.244.0.5   minikube   <none>           <none>
nginx-app-65fd5796b9-w9w64   1/1     Running   0          25m     10.244.0.3   minikube   <none>           <none>

kubectl get pods --field-selector=status.phase=Running – Lists all pods in namespace whose status is Running.

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

The output is similar to the command for listing pods, only that it displays active pods.

kubectl describe pod pod-name - Provides detailed information about a specific pod. The output offers information such as the pod’s namespace, volumes, containers, and events. The command is typically used for troubleshooting and debugging purposes.

OutputName:             nginx-app-65fd5796b9-vdmb4
Namespace:        default
Priority:         0
Service Account:  default
Node:             minikube/192.168.58.2
Start Time:       Thu, 20 Mar 2025 18:48:39 +0200
Labels:           app=nginx-app
                  pod-template-hash=65fd5796b9
Annotations:      <none>
Status:           Running
IP:               10.244.0.5
IPs:
IP:             10.244.0.5
Controlled By:  ReplicaSet/nginx-app-65fd5796b9

kubectl get pods --show-labels - Lists pods and all the labels assigned or associated with each pod.

Command Line
kubectl get pods --show-labels

The output is similar to listing pods but includes information about pod labels.

Outputnginx-app-65fd5796b9-vdmb4   1/1     Running   0          28m   app=nginx-app,pod-template-hash=65fd5796b9
nginx-app-65fd5796b9-w9w64   1/1     Running   0          52m   app=nginx-app,pod-template-hash=65fd5796b9

kubectl label pods pod-name label-name=label-name - The command adds a new label to a pod.

The command below adds a label cherry-webservers with the value of web-server-1 to a pod named nginx-app-65fd5796b9-vdmb4.

Command Line
kubectl label pods nginx-app-65fd5796b9-vdmb4  cherry-webservers=web-server-1

kubectl logs pod-name - Examine the pod’s logs.

Command Line
kubectl logs nginx-app-65fd5796b9-vdmb4

The command above lists the logs of a pod called nginx-app-65fd5796b9-vdmb4.

kubectl delete pod pod-name - Delete a pod.

The command below deletes the pod called nginx-app-65fd5796b9-vdmb4.

Command Line
kubectl delete pod nginx-app-65fd5796b9-vdmb4

kubectl exec -it pod-name -- /bin/bash - Access the shell of a running pod.

The following command accesses the shell of the pod nginx-app-65fd5796b9-vdmb4.

Command Line
kubectl exec -it nginx-app-65fd5796b9-w9w64  -- /bin/bash

#Nodes

A node is a hardware machine or virtual instance that forms part of a cluster. The master node, or simply the control plane, manages the cluster and ensures cluster health and availability of all services. Worker nodes are endpoints on which pods are scheduled by the control plane. They offer the compute resources required to run pods.

kubectl get nodes - Lists all nodes in a cluster.

Command Line
kubectl get nodes

The output provides salient information such as node name, status, role ( whether master or worker node), age ( when the node was added to the cluster ), and Kubernetes version.

OutputNAME                STATUS   ROLES    AGE     VERSION
node-1             Ready    master   2d      v1.32.2
node-2             Ready    worker   1d      v1.32.2

kubectl describe node node-name - Retrieves detailed information about a specific node, including node name, labels, system information, network configuration, resource utilization, namespaces, pods, etc.

Command Line
kubectl describe node <node-name>

kubectl label nodes node-name environment=dev - The command labels a node using the label environment=dev.

Command Line
kubectl label nodes <node-name> environment=dev

kubectl get nodes --show-labels - Displays labels for all nodes.

Command Line
kubectl get nodes --show-labels

kubectl cordon node-name - Marks a node as unschedulable to prevent new pods from being deployed on it.

Command Line
kubectl cordon <node-name>

kubectl uncordon node-name - Restores the node to the cluster after maintenance.

Command Line
kubectl uncordon <node-name>

kubectl drain node-name --ignore-daemonsets - evicts all pods from the node and reschedules them on other available nodes.

Command Line
kubectl  drain <node-name> --ignore-daemonsets

kubectl taint nodes node-name key1=value1:taint-effect - Tainting a node with a key-value pair and taint effect.

Command Line
kubectl  taint nodes <node-name> key1=value1:<taint-effect>

#Working with configuration files ( YAML or Manifest Files )

A YAML configuration file is the de facto way of creating and updating components. It provides a blueprint for creating and updating resources such as Deployments. YAML manifests offer a simple syntax, making them highly reusable and ideal for creating and updating cluster resources.

kubectl apply -f file.yaml - This command creates a resource defined in the YAML manifest file. It is idempotent, implying that running it multiple times will have no effect.

Command Line
kubectl apply -f file.yaml

kubectl apply -f URL - Create a resource from a URL containing a YAML file.

Command Line
kubectl apply -f URL

kubectl apply -f file.yaml --dry-run=client - Perform a dry run before applying a YAML manifest.

Command Line
kubectl apply -f file.yaml  --dry-run=client

kubectl delete -f file-name.yaml - Delete or remove a resource specified in the YAML file.

Command Line
kubectl apply -f file.yaml  --dry-run=client

#Logs

Logs provide information about events in the cluster. They offer valuable insights into components' behavior, allowing for troubleshooting where issues occur and performance optimization. Essentially, component logs provide a trail of events that occur every step of the way.

kubectl logs pod-name - Displays logs for a specific pod with a single container only.

Command Line
kubectl logs <pod-name>

kubectl logs -f my-pod - View live logs from a pod. Similar to the following logs with the tail -f command on Linux/UNIX.

Command Line
kubectl logs -f my-pod

While viewing logs, the shell is typically unavailable for running commands. To quit or exit viewing of logs, press CTRL + C.

kubectl logs --tail=10 <pod_name> – Display the most recent 10 lines of logs (Last 10 lines).

Command Line
kubectl logs --tail=10 <pod_name> 

kubectl logs --since=5h <pod_name> - Displays logs generated for the last 5 hours for a specific pod.

Command Line
kubectl logs --since=5h <pod_name>

kubectl logs my-pod -c my-container - Retrieves logs from a multi-container pod. The command lists logs from a specific container, in this case, my-container.

Command Line
kubectl logs my-pod -c my-container

kubectl logs my-pod --all-containers=true - Display logs from all containers hosted in a pod.

Command Line
kubectl logs my-pod --all-containers=true

kubectl logs my-pod -n my-namespace - Fetches logs from pods in a specific namespace.

Command Line
kubectl logs my-pod  -n my-namespace

kubectl logs -l environment=production - Lists logs of all pods bearing the label environment=production.

Command Line
kubectl logs  -l environment=production

#Services

A service exposes a pod/group of pods to network traffic, allowing for service discovery, accessibility, and other salient services, including load balancing.

kubectl get services - Display all enabled services in the current namespace.

Command Line
kubectl get services

Alternatively, you can run:

Command Line
kubectl get svc

kubectl get svc --all-namespaces - Fetch services in all namespaces.

Command Line
kubectl get svc --all-namespaces

kubectl get svc service-name - Displays information about a specific service.

Command Line
kubectl get svc  service-name

kubectl describe svc service-name - Retrieve detailed output about a particular service, including namespace, labels, and annotations.

Command Line
kubectl describe svc  service-name

kubectl delete svc service-name - Delete / Remove a service.

Command Line
kubectl delete svc service-name

#Deployments

A deployment is an object that provides a declarative state of an application. It defines an application's desired state, including the container, image, number of pods, metadata, and much more. It’s a management tool that provides a template that defines how the application will run.

A deployment provides added benefits such as rollback updates and support, pod management via ReplicaSets, and scaling.

kubectl get deployments - List all existing deployments.

Command Line
kubectl  get deployments

kubectl describe deployment deployment-name - Provide detailed information about the deployment, including namespaces, labels, replicas, pod template, etc.

Command Line
kubectl describe deployment deployment-name

kubectl scale deployment deployment-name --replicas=4 - Scale or increase the number of replicas to 4.

Command Line
kubectl scale deployment deployment-name --replicas=4

kubectl set image deployment/deployment name container name=image:new image version - Perform a rolling update by modifying the app's image version.

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

kubectl rollout undo deployment deployment-name - Rollback or undo changes made to a deployment.

Command Line
kubectl rollout undo deployment deployment-name

kubectl delete deployment deployment-name - Delete a deployment.

Command Line
kubectl delete deployment deployment-name

#DaemonSets

DaemonSets are objects that ensure specified services run on each node. They guarantee that a specific pod is scheduled on all nodes to run unique workloads. They are perfect for log collection or monitoring workloads running on all nodes. Also, operation teams can run node-specific tasks on nodes, such as managing security policies.

kubectl get daemonsets -A - List all daemonsets in all namespaces.

Command Line
kubectl get daemonsets -A

kubectl describe daemonset daemonset_name -n namespace_name - Display detailed information about a specific daemonset in the specified namespace.

Command Line
kubectl describe daemonset daemonset_name -n namespace_name

kubectl delete daemonset daemonset_name – Remove a daemonset.

Command Line
kubectl  delete daemonset daemonset_name

#ReplicaSets

A ReplicaSet is a controller that maintains the lifecycle of pods in a cluster by keeping an eye on a cluster of pods. It ensures that N number of pods are running at any given moment. Failed pods are automatically replaced by healthy ones, and by so doing, service availability is guaranteed.

kubectl get replicasets - List all ReplicaSets in the cluster.

Command Line
kubectl get replicasets

Alternatively, you can run:

Command Line
kubectl get rs

kubectl describe rs my-replicaset - List detailed information about a ReplicaSet.

Command Line
kubectl  describe rs my-replicaset

kubectl scale rs my-replicaset --replicas=4 - Manually scale the number of replicas to 4.

Command Line
kubectl  scale rs my-replicaset  --replicas=4

kubectl delete rs my-replicaset - Delete a ReplicaSet.

Command Line
kubectl delete  rs my-replicaset

NOTE: This deletes the ReplicaSet but does not remove existing Pods. To delete the Pods as well, use:

kubectl delete rs my-example-rs --cascade=foreground

#Secrets

Secrets secure sensitive information such as API keys and passwords, preventing exposure to the public. Highly sensitive information is decoupled from the source code. The risk of exposure is thus well managed since the data is kept separate from the application code.

kubectl get secrets - View all secrets.

Command Line
Kubectl get secrets

kubectl describe secret my-secret - Fetches more detailed information about a secret.

Command Line
kubectl describe secret <my-secret>

kubectl create secret generic my-secret --from-file=password=password.txt - Create a secret called my-secret from a text called password.txt containing the password.

Command Line
kubectl create secret generic <my-secret>

kubectl delete secret my-secret – Delete a secret.

Command Line
kubectl delete secret <my-secret>

#Common errors in Kubernetes

For the most part, Kubernetes commands will run as expected without any issues. However, sometimes you will encounter some errors while running the kubectl commands. This section explores some common Kubernetes errors and how to resolve them.

#1. Pending pods

A pod can be stuck in Pending status upon being deployed. This implies that it has not been successfully scheduled in a node.

#Causes

The error is likely caused by insufficient resources (such as RAM and CPU) to schedule a pod. Additionally, the image specified in the deployment used to create the pod may be unavailable or corrupted.

#Troubleshooting tips

To fix the error, check detailed pod information.

Command Line
kubectl describe pod <pod-name>

Also, be sure the image name specified in the pod configuration is correct, and the image registry is valid. Additionally, ensure your nodes have sufficient resources to run the workloads.

#2. Node NotReady status

The NodeNotReady error indicates that a node is in an unhealthy state to accept any pod.

#Causes

This can be due to several reasons, such as insufficient resources, network connectivity issues with the master node, underlying hardware issues with the worker node etc.

#Troubleshooting tips

To diagnose this error, list the nodes in your cluster by running:

Command Line
kubectl get nodes

The output below shows node2 in a NotReady status.

OutputNAME            STATUS     ROLES    AGE    VERSION
node1           Ready      <none>        2d        v1.32.2
node2           NotReady   <none>     1d        v1.32.2

To start fixing this error, obtain detailed node status by running:

Command Line
kubectl describe node <node-name>

The output offers insights into any warnings or errors affecting the node. Carefully analyze the output and look out for any inconsistencies or errors. This will help you to troubleshoot issues affecting the node.

In most cases, adding compute resources such as RAM and CPU for the affected node will help resolve the error.

Sometimes, the error might arise from issues with the kubelet process on the worker node. To troubleshoot this, restart the kubelet process.

Command Line
sudo systemctl restart kubelet

Also, consider restarting the kube-proxy service on the affected node. This can help resolve any network-related issue preventing the worker node from communicating with the master node.

Command Line
sudo systemctl restart kube-proxy

#3. ImagePullBackOff / ErrImagePull error

The ImagePullBackOff and ErrImagePull Errors occur when Kubernetes fails to pull an image needed to create a pod in your cluster.

#Causes

The error is caused by any of the following issues:

  • Specifying an invalid image or repository name

  • Specifying an incorrect image tag

  • Insufficient disk storage

  • Network issues that could be preventing the image from being pulled

  • Unauthorized access to an image registry

  • Unavailable image registry or underlying issues with the registry.

#Troubleshooting tips

To resolve the error, follow the pointers outlined:

  • Use correct and consistent image names and valid tags.

  • Monitor your network and ensure your nodes can communicate seamlessly with the specified image registry.

  • Use reliable image registries such as Azure Container Registry (ACR), Docker Hub, and GitLab container registry.

  • Check the nodes' disk space and ensure ample storage for pods and images.

  • Use Kubernetes secrets to store registry credentials for your Pods. Refrain from hard-coding authentication credentials in YAML files.

#4. Pod Stuck in Terminating State

Sometimes, pods can enter the Terminating phase while being removed or deleted. This implies that a pod is scheduled to be removed but gets stuck. Usually, the terminating state is supposed to be a brief state. However, this doesn't always happen, and sometimes the pod deletion process stalls, leading to the error.

#Causes

Let's brush through some of the reasons for this error.

  • A pod being unresponsive to termination signals.
  • A node on which the pod is running is down or unreachable. The pod will remain in this status until the node is revived and is running.
  • A finalizer associated with the pod is not completing, causing the pod to get stuck in the terminating state.

#Troubleshooting tips

Here is a list of possible fixes to this error:

  • Force delete a pod. You can achieve by running the command:
Command Line
kubectl delete pod --grace-period=0 --force --namespace <NAMESPACE> <PODNAME>
  • Delete the finalizer field in the metadata section in the pod’s YAML definition.

  • Check Node status and ensure that all nodes are up and running. You can achieve this by running the command:

Command Line
kubectl get pods

#5. CrashLoopBackOff error

The CrashLoopBackOff error is a state where a pod is stuck in a restart loop. It starts, crashes, and restarts, and the cycle starts over again. This can be diagnosed using the kubectl get pods command.

Command Line
kubectl get pods

The output shows a pod in the ``CrashLoopBackOff` state.

OutputNAME                                 READY     STATUS                          RESTARTS   AGE
nginx-468d5ql7c-4dgq5      0/1           CrashLoopBackOff          2                    1m

#Causes

The CrashLoopBackOff error can happen due to the following reasons.

  • Incorrect or invalid commands / command-line arguments

  • Misconfigurations or typos in the YAML configuration files

  • Missing resources, e.g., unmounted persistent volumes

#Troubleshooting

To resolve the error, here are a few troubleshooting steps you can take.

Check the pod description using the following command:

Command Line
kubectl describe pod pod-name

The output provides salient information such as the pod definition, and containers running inside the pod. It also sheds light on resource allocation and missing arguments that could be causing the error.

Consider checking pod logs to get insights on what triggered the error. You can check all container logs as shown.

Command Line
kubectl logs mypod --all-containers

You can narrow it down to checking logs for a single container in the pod:

kubectl logs mypod -c mycontainer

#Conclusion

That was a breakdown of common kubectl commands. We have demonstrated how to use them to retrieve information, create, and delete resources within the cluster. We have further gone ahead to list some common errors you are likely to encounter when running these commands and troubleshooting tips. Hopefully, you now have a firm grasp of kubectl commands and can administer a Kubernetes cluster seamlessly.

Bare Metal Servers - 15 Minute Deployment

Get 100% dedicated resources for high-performance workloads.

Share this article

Related Articles

Published on Jun 9, 2023 Updated on Aug 13, 2024

How to install Kubectl on Ubuntu 22.04

In this guide, we’ll explore three main ways to install Kubectl on your Ubuntu 22.04 system: binary using curl, apt package manager, and snap package manager.

Read More
Published on Jul 7, 2023 Updated on Nov 29, 2024

How to Create and Use Kubernetes Secrets | A Complete Guide

This guide looks at Kubernetes secrets management, including how they can be created and used in your cluster.

Read More
Published on Sep 12, 2024 Updated on Nov 29, 2024

Kubernetes Secrets: How to Manage Secrets in Kubernetes?

Learn what are secrets in Kubernetes and how to manage them from creating, listing to deleting. You will also learn the importance of using secrets in Kubernetes with simple examples and best practices for protection.

Read More
We use cookies to ensure seamless user experience for our website. Required cookies - technical, functional and analytical - are set automatically. Please accept the use of targeted cookies to ensure the best marketing experience for your user journey. You may revoke your consent at any time through our Cookie Policy.
build: 964ac6ab8.1239