In this Kubectl Cheat Sheet, we have explored a comprehensive set of Kubernetes commands that cover various aspects of cluster management, deployment, monitoring, interaction, and more.
By familiarizing yourself with these kubectl commands, you can leverage the full power of Kubernetes to orchestrate and scale your applications effectively.
As a powerful tool, Kubernetes offers many commands that empower administrators and developers to interact with clusters, deploy applications, and monitor resources effectively.
In this Kubectl Cheatsheet, we will delve into the world of Kubernetes commands, exploring their functionality and providing practical examples for each.
Let's embark on this journey to demystify Kubernetes and unlock its full potential.
Bookmark this kubectl guide and refer it whenever you want to.
What is Kubectl?
In Kubernetes, kubectl
is a command-line tool that allows you to interact with Kubernetes clusters.
The tool manages and controls various aspects of your Kubernetes environment, including deploying and managing applications, inspecting cluster resources, and executing administrative tasks.
To configure kubectl, you need to set up the kubeconfig file. The kubeconfig file contains information about clusters, users, and contexts that kubectl uses to interact with Kubernetes clusters.
The configuration for kubectl
includes the context, which determines the cluster, user, and namespace for a particular kubectl
command. The context is defined in the kubeconfig file, which is usually located at ~/.kube/config
by default.
Let's start Kubectl Cheat Sheet with the most commonly used shortcodes in Kubernetes (K8s).
Kubectl Commands Cheat Sheet - Shortcodes
-
Daemonsets = ds
-
Deployments = deploy
-
Events = ev
-
Namespaces = ns
-
Nodes = no
-
Pods = po
-
Replication Controllers = rc
-
ReplicaSets = rs
-
Services = svc
-
Service Accounts = sa
-
StatefulSets = sts
-
Certificatesigningrequests = csr
-
Componentstatuses = cs
-
Configmaps = cm
-
Endpoints = ep
-
Horizontalpodautoscalers = hpa
-
Ingresses = ing
-
Limitranges = limits
-
Persistentvolumeclaims = pvc
-
Persistentvolumes = pv
-
Poddisruptionbudgets = pdb
-
Podsecuritypolicies = psp
-
Resourcequotas = quota
#1: Cluster Management
Cluster management involves interacting with and managing Kubernetes clusters. Here are some kubectl commands related to cluster management:
kubeclt version: Display the Kubernetes version that is currently running on the client and server.
kubectl cluster-info: Retrieves information about the Kubernetes cluster, including the cluster's endpoint, API version, and master node.
kubectl api-resources: Shows the available API resources
kubectl api-versions: shows the available API versions
kubectl config view: Displays the current kubeconfig configuration, including the clusters, contexts, and users configured.
kubectl config get-contexts: Lists all the available contexts in the kubeconfig file.
kubectl config use-context <context-name>
: Sets the current context to the specified context, allowing you to switch between different clusters or configurations.
Here is how to use it.
kubectl config use-context context-1
kubectl config current-context: Displays the currently selected context.
kubectl config delete-context <context-name>
: Deletes a specific context (in this case, content-name) from the kubeconfig file.
Here is how you can use it.
kubectl config delete-context context-1
These commands enable you to gather information about the cluster, manage multiple cluster configurations, and switch between different contexts to work with different clusters.
Let's get started with the next part of this Kubectl commands cheat sheet.
Also Read: Kubectl Config Set Context Tutorial
#2: Contexts
Contexts in Kubernetes represent a combination of a cluster, user, and namespace. They allow you to specify which cluster you want to interact with, which user to authenticate as, and the default namespace to use.
Here are some relevant commands:
kubectl config set-cluster: Configuring a cluster.
kubectl config get-contexts: Lists all available contexts in the kubeconfig file.
kubectl config current-context: Displays the currently selected context.
kubectl config use-context <context-name>
: Sets the current context to the specified context, allowing you to switch between different clusters or configurations.
kubectl config set-context <context-name>
--cluster=<cluster-name>
--user=<user-name>
--namespace=<namespace>
: Creates or modifies a context with the specified cluster, user, and namespace.
Here is an example of how to use this command.
kubectl config set-context my-context --cluster=my-cluster --user=my-user --namespace=my-namespace
kubectl config delete-context <context-name>
: Deletes a specific context from the kubeconfig file.
kubectl get all --all-namespaces: Shows everything
kubectl describe node <node_name>
: Get Information about a node.
Using contexts, you can manage and switch between different cluster configurations easily, enabling you to work with multiple Kubernetes clusters and environments efficiently.
Also Read: A Complete Guide to Kubernetes Liveness Probes
#3: Daemonsets
DaemonSets are an important resource in Kubernetes that ensure a specific pod is running on each node in a cluster. They are primarily used for background or system-level tasks that need to run on every node.
Here are some relevant Kubectl commands for Daemonsets.
kubectl create daemonset <daemonset_name>
: Creating a daemonset.
Here is an example showing how to use this kubectl command.
kubectl create daemonset ds1
kubectl get daemonset: Listing all running daemonsets.
kubectl edit daemonset <daemonset_name>
: Edit and update one or more daemonset definitions
kubectl describe ds <daemonset_name>
-n <namespace_name>
: Describing a specific daemonset.
Here is an example showcasing how to use this kubectl command.
kubectl describe ds my-daemonset -n my-namespace
kubectl delete daemonset <daemonset_name>
: Deleting a daemonset.
kubectl rollout daemonset: Manages a daemonsets rollout
Also Read: How to Use Kubectl Rollout Restart?
#4: Deployments
Deployments in Kubernetes allow you to manage and scale applications by providing declarative updates for Pods and ReplicaSets. You can use kubectl to create and manage Deployments.
Here are some relevant commands:
kubectl get deployment: Lists deployments
kubectl create deployment <deployment_name>
: Creating a new deployment.
kubectl describe deployment <deployment_name>
: Show the current status of one or more deployments in detail.
kubectl edit deployment <deployment_name>
: Edit and update the definition of one or more server deployments.
kubectl rollout status <deployment_name>
: Checking the status of deployment.
kubectl rollout history <deployment_name>
: Viewing the revision history of a deployment.
kubectl rollout undo: Reverting to a previous revision.
kubectl delete deployment <deployment_name>
: Delete deployment
Also Read: A Complete Guide to Kubectl Port Forwarding
#5: Kubernetes Events
In Kubernetes, events are used to track and monitor the status and activities of various resources within the cluster.
They provide valuable information about the lifecycle events and changes happening in the cluster. Events can help in troubleshooting, auditing, and understanding the behavior of resources.
Here is a Kubectl commands list to handle Kubernetes events.
kubectl get events: Retrieving events from the cluster.
kubectl get events --field-selector type=Warning: Shows warnings
kubectl get events --field-selector involvedObject.kind!=Pod: Shows events excluding Pod events
kubectl get events --field-selector involvedObject.kind=Node, involvedObject.name=<node_name>
: Pull events for a single node with a unique identifier
kubectl get events --field-selector type!=Normal: Remove all typical events from a list of occurrences.
kubectl describe events: Describing specific events.
Also Read: Differences between ELK and SPLUNK
#6: Kubernetes Logs
In Kubernetes, logs are crucial for troubleshooting and understanding the behavior of applications and containers running within the cluster. Kubernetes provides several ways to access and view logs.
Here are some relevant commands:
kubectl logs <pod_name>
: Viewing the logs of a specific pod or container.
kubectl logs --since=1h <pod_name>
: Print the last hour's logs for a pod.
kubectl logs --tail=21 <pod_name>
: Get the last 21 lines of logs
kubectl logs -f <pod_name>
: Streaming logs in real-time.
kubectl logs -f <service_name>
[-c <$container>
]: Obtain logs from a service and, if desired, specify which container.
Here is how you can use this command to obtain Kubernetes logs.
kubectl logs -f my-pod -c my-container
kubectl logs -c <container_name>
<pod_name>
: Logs for a container in a pod should be printed.
kubectl logs --previous <pod_name>
: Use this to view the logs of the previous container instance.
kubectl logs <pod_name>
pod.log: Put a pod's logs into a file called 'pod.log.'
kubectl logs --help: Get help while viewing Kubernetes logs using Kubectl
#7: Namespaces in Kubernetes
In Kubernetes, namespaces are virtual clusters within a physical cluster. They provide a way to divide and isolate resources, such as pods, services, and storage, into logical groups.
Here are some kubectl commands for Kubernetes Namespaces.
kubectl create namespace <namespace>
: Creates a new namespace.
kubectl get namespaces: Lists all namespaces.
kubectl describe namespace <namespace>
: Describes a specific namespace.
kubectl delete namespace <namespace>
: Deletes a namespace and its resources.
kubectl config set-context --current --namespace=<namespace>
: Sets the current context's namespace.
kubectl get <resource>
--namespace=<namespace>
: Lists resources (pods, services, deployments, etc.) in a specific namespace.
kubectl describe <resource>
--namespace=<namespace>
: Describes a specific resource in a namespace.
kubectl apply -f <directory>
--namespace=<namespace>
: Applies all YAML/JSON files in a directory to a specific namespace.
kubectl config set-context --current --namespace=<namespace>
: Switches the current context's namespace to the specified namespace.
kubectl config use-context <context>
--namespace=<namespace>
: Sets the namespace for a specific context.
Here is an example of how to use this kubectl command.
kubectl config use-context my-context --namespace=my-namespace
Also Read: Prometheus Operator in Kubernetes
#8: Working with Nodes
In Kubernetes, nodes represent the individual machines (physical or virtual) that make up the cluster. They are the worker machines where containers are scheduled and run.
Here are some kubectl commands you can use with nodes.
kubectl get node: Retrieving information about nodes in the cluster.
kubectl taint node <node_name>
: Update the taints on one or more nodes.
kubectl delete node <node_name>
: Remove a node or a group of nodes
kubectl top node: Display node resource use (CPU/Memory/Storage).
kubectl describe node: Describing a specific node.
kubectl drain node <node_name>
: Evicting pods from a node for maintenance.
kubectl cordon node <node_name>
: Marking a node as unschedulable.
kubectl uncordon node <node_name>
: Marking a node as schedulable.
kubectl label node: Update or add labels to one or more nodes
kubectl annotate node <node_name>
: Annotate node
Also Read: Kubernetes Nodes vs Pods vs Cluster
#9: Working with K8s Pods
In Kubernetes, a pod is the smallest and most basic unit of deployment. It represents a single instance of a running process within the cluster.
Here are some kubectl commands for pods.
kubectl get pod: Listing all pods in the cluster.
kubectl delete pod <pod_name>
: Delete a pod.
kubectl top pod: Display pod resource usage (CPU/Memory/Storage).
kubectl describe pod <pod_name>
: Describing a specific pod.
kubectl create pod <pod_name>
-n <namespace>
: Create a pod in a namespace.
kubectl logs: Viewing the logs of a specific pod.
kubectl exec: Running commands inside a container within a pod.
kubectl exec -it <pod_name>
/bin/sh: Obtain an interactive shell on a single-container pod.
kubectl label pod <pod_name>
: Updates or add label.
kubectl annotate pod <pod_name>
<annotation>
: Add or update a pod's annotations.
An example of how to use the above kubectl command to add/update a K8s pod.
kubectl annotate pod my-pod description="Annotated pod"
Also Read: Kubernetes Security, Resource Limits, and Namespaces Best Practices
#10: Replication Controllers and ReplicaSets
In Kubernetes, Replication Controllers and ReplicaSets are resources used to ensure the desired number of replicas (copies) of a pod are running and maintained within the cluster.
They provide a way to achieve high availability and scalability for applications. While ReplicaSets have largely replaced Replication Controllers, it's important to understand both concepts.
Here are some relevant kubectl commands for Replication Controllers and ReplicaSets.
kubectl get replicationcontrollers: Listing all replication controllers.
kubectl describe replicationcontroller: Describing a specific replication controller.
kubectl get replicasets: Listing all replica sets.
kubectl get rc --namespace=”<namespace_name>
”: Sort the replication controllers by namespace.
kubectl describe replicaset <replicaset_name>
: Describing a specific replica set.
kubectl scale --replicas=[x]: Scale a ReplicaSet
Here is how to use this Kubectl command.
kubectl scale --replicas=3 deployment/example
#11: Secrets in Kubernetes
In Kubernetes, secrets are used to store and manage sensitive information, such as passwords, tokens, or API keys, securely within the cluster.
They provide a way to separate sensitive data from the application logic and enable secure access to credentials when needed.
Here are some kubectl commands to handle Kubernetes secrets.
kubectl create secret: Creating secrets to securely store sensitive information.
kubectl get secrets: Retrieving information about secrets.
kubectl describe secret: Describing a specific secret.
kubectl delete secret <secret_name>
: Delete secret
Also Read: Istio vs Consul vs Linkerd - Which One to Choose?
#12: Handle Kubernetes Services
In Kubernetes, services are a fundamental resource used to enable communication and networking between different pods or external clients.
They provide a stable endpoint for accessing and connecting to applications running within the cluster.
Here are some relevant kubectl commands that you can use for K8s services.
kubectl create service: Creating a service to expose a deployment or pod.
kubectl get services <service_name>
: Retrieving information about services.
kubectl describe service: Describing a specific service.
kubectl delete services -o wide: Delete all services.
kubectl delete services <service_name>
: Delete a specific service.
An example of how to use this kubectl command.
kubectl delete services my-service
kubectl edit services: One or more services' definitions should be edited and updated.
kubectl expose deployment <deployment_name>
: Make a replication controller, service, deployment, or pod available as a new Kubernetes service.
Use this kubectl command as shown below.
kubectl expose deployment my-deployment --port=8080 --target-port=80 --type=LoadBalancer
Also Read: What is Helm in K8s?
#13: Service Accounts
In Kubernetes, Service Accounts is a built-in mechanism for providing an identity to pods running within the cluster. They allow pods to authenticate and interact with other resources, such as the API server or other services, using the Kubernetes API.
Here are some relevant Kubectl commands to work with Kubernetes Service Account.
kubectl create serviceaccount: Creating a service account.
kubectl get serviceaccounts: Retrieving information about service accounts.
kubectl describe serviceaccount: Describing a specific service account.
kubectl replace serviceaccount: Replace service accounts
kubectl delete serviceaccount <service_account_name>
: Delete a service account.
#14: StatefulSets
In Kubernetes, StatefulSets is a resource used to manage stateful applications, such as databases or other applications that require stable network identities and persistent storage.
StatefulSets guarantees about the ordering and uniqueness of pod creation and deployment, allowing applications to maintain stable network identities and persistent storage across rescheduling or scaling operations.
Here are some relevant kubectl commands for Kubernetes StatefulSets.
kubectl create statefulset: Creating a statefulset.
kubectl get statefulsets: Retrieving information about statefulsets.
kubectl describe statefulset: Describing a specific statefulset.
kubectl delete statefulset [stateful_set_name] --cascade=false: Delete Stateful only.
Use this kubectl command as shown below.
kubectl delete statefulset/my-statefulset --cascade=false
Also Read: A Complete Guide to Kubernetes ImagePullPolicy
#15: K8s Manifest Files
In Kubernetes, manifest files are used to define and describe the desired state of resources that you want to deploy and manage within the cluster.
Manifest files are typically written in YAML or JSON format and contain the specifications for various Kubernetes objects, such as pods, deployments, services, and more.
Here are some relevant kubectl commands for Kubernetes manifest files.
kubectl apply -f manifest_file.yaml: Applying configurations defined in a YAML file.
kubectl create -f manifest_file.yaml: Object creation
kubectl create -f ./dir: Objects are created in all manifest files in a directory.
kubectl create -f 'URL': Objects are created from a URL.
Here is an example showcasing how to use this kubectl command.
kubectl create -f https://example.com/my-resource.yaml
kubectl delete -f manifest_file.yaml: Object deletion
kubectl get -f: Retrieving resources defined in a YAML file
Also Read: What are init conatiners?
#16: Kubectl Autocomplete
Kubectl autocomplete is a convenient feature that enables command-line autocompletion for kubectl commands, flags, and resource names.
It saves time and reduces errors by providing suggestions as you type. Here's how to set up kubectl autocomplete for different shells:
kubectl completion: Enabling kubectl auto-completion for shells.
kubectl completion fish | source: Enables autocompletion for kubectl in the current Fish session. Add the above command to your config.fish file to enable autocompletion permanently.
kubectl completion powershell | Out-String | Invoke-Expression: Enables autocompletion for kubectl in the current PowerShell session.
Add the above command to your PowerShell profile file to enable autocompletion permanently.
Also Read: Docker Image vs Container
#17: List for Updating, Patching, and Editing Kubernetes Resources
In Kubernetes, you can update, patch, and edit resources using various kubectl commands. These commands allow you to modify the configuration and properties of existing resources in the cluster.
Here are the commonly used commands for updating, patching, and editing resources in Kubernetes.
Also Read: Guide to Kubectl Proxy Command
A. Kubectl Commands for Updating Kubernetes Resources
kubectl apply -f <filename>
: Updates or creates resources defined in a YAML or JSON file. It applies the changes to the cluster based on the file's specifications.
kubectl replace -f <filename>
: Updates resources defined in a YAML or JSON file. It replaces the existing resources with the updated ones, ensuring the desired state matches the new configuration.
kubectl edit <resource_type>
<resource_name>
: Opens the resource in the default editor specified by the $EDITOR
environment variable.
You can make changes directly in the editor and save the file to apply the updates to the resource. Here is an example of how to use this kubectl command.
kubectl edit deployment my-app-deployment
kubectl set image: Updating a container image for deployment.
B. Kubectl Commands for Patching K8s Resources
kubectl patch <resource_type>
<resource_name>
--patch=<patch_definition>
: Applies a patch to the specified resource. The patch definition can be provided inline using JSON or YAML format, or you can pass a patch file using the --patch-file
flag.
An example of how to use the kubectl patch command for patching Kubernetes resources.
kubectl patch deployment example-deployment --patch='{ "spec": { "replicas": 5 } }'
C. Kubectl Command for Editing Resources in Kubernetes
kubectl edit <resource_type>
<resource_name>
: Opens the resource in the default editor specified by the $EDITOR
environment variable.
You can make changes directly in the editor and save the file to apply the updates to the resource.
Also Read: How to Run K8s on AWS?
#18: Scaling and Deleting Resources in Kubernetes
In Kubernetes, you can scale and delete resources using various kubectl commands. These commands allow you to adjust the number of replicas or remove resources from the cluster.
Here are the commonly used kubectl commands for scaling and deleting resources in Kubernetes:
kubectl scale: Scaling the number of replicas for a deployment or replicaset.
kubectl scale deployment <deployment-name>
--replicas=<desired-replicas>
: Scales the number of replicas for a deployment to the specified value.
Here is an example of how to use this particular kubectl command.
kubectl scale deployment example-deployment --replicas=5
kubectl scale statefulset <statefulset-name>
--replicas=<desired-replicas>
: Scales the number of replicas for a statefulset to the specified value.
kubectl delete: Removing resources from the cluster.
kubectl delete pods -l app=my-app: Deletes all pods with the label "app=my-app".
kubectl delete -f my-deployment.yaml: Deletes the resources defined in "my-deployment.yaml".
kubectl delete pods --namespace=my-namespace: Deletes all pods in the "my-namespace" namespace.
Also Read: AWS Karpenter vs Cluster Autoscaler
#19: Copying Files and Directories to and from Containers
In Kubernetes, you can copy files and directories to and from containers running within pods using the kubectl cp command. This command allows you to transfer files between your local machine and containers in the cluster.
Here's how to use kubectl cp for copying files:
kubectl cp: Copying files and directories to and from containers.
kubectl cp <pod_name>
:<container_path>
<local_path>
: Copies a file or directory from the specified container to your local machine.
Here is how to use this kubectl cp
kubectl cp my-pod:/app/logs/log.txt ./local_logs/
kubectl cp <local_path>
<pod_name>
:<container_path>
: Copies a file or directory from your local machine to the specified container.
An example of how to use this:
kubectl cp ./config.yml my-pod:/app/config/
Also Read: Kubernetes Cost Optimization Tools You Should Know About
#20: Interacting with Nodes and the Cluster
Interacting with nodes and the cluster in Kubernetes involves executing various administrative tasks and accessing cluster-level information.
Here are some kubectl commands and examples to help you interact with nodes and the cluster.
A. Node-related Kubectl Commands
kubectl get nodes: Retrieves information about the nodes in the cluster, including their names, status, and IP addresses.
kubectl describe node <node_name>
: Provides detailed information about a specific node, including its capacity, allocatable resources, and labels.
kubectl label node <node_name>
<label_key>
=<label_value>
: Adds a label to a node to help categorize and identify it.
Here is an example of how to use this particular kubectl command.
kubectl label node my-node environment=production
kubectl cordon <node_name>
: Marks a node as unschedulable, preventing new pods from being scheduled on it.
kubectl uncordon <node_name>
: Marks a previously cordoned node as schedulable again.
kubectl drain <node_name>
: Safely evicts all the pods from a node and reschedules them onto other available nodes.
kubectl taint node <node_name>
<key>
=<value>
:<effect>
: Applies a taint to a node to repel or attract pods during scheduling.
Here's how to use this kubectl command:
kubectl taint node my-node key=value:NoSchedule
B. Kubectl Commands List for Cluster
kubectl cluster-info: Displays information about the Kubernetes cluster, including the cluster's endpoint and API server version.
kubectl get namespaces: Lists all namespaces in the cluster.
kubectl get pods --all-namespaces: Retrieves information about all pods in all namespaces.
kubectl exec: Starts a proxy server that allows direct access to the Kubernetes API server.
kubectl version: Displays the version of kubectl and the Kubernetes client/server components.
C. A few Common Examples of Kubectl Commands for Cluster & Nodes
-
Retrieve information about the nodes in the cluster: kubectl get nodes
-
Describe a specific node in detail: kubectl describe node my-node
-
Label a node as "environment=production": kubectl label node my-node environment=production
-
Cordon a node to mark it as unschedulable: kubectl cordon my-node
-
Drain a node and reschedule the pods onto other nodes: kubectl drain my-node
Also Read: Docker Commands Cheat Sheet
Conclusion - Kubectl Cheatsheet
Even though this is an exhaustive list of kubectl commands, refer to the official Kubernetes documentation for further details and command variations.
Kubernetes offers an extensive command-line interface that caters to diverse scenarios, making it a versatile tool for both beginners and experienced users. The examples provided here should serve as a starting point for your exploration.
Embrace the power of Kubernetes, and unlock the true potential of containerized applications.
Happy orchestrating!