
Hello and welcome! We have gathered the most commonly used commands in Kubernetes for you, all in one ready-to-use kubectl cheat sheet. In this "kubectl cheat sheet," we will walk you through step-by-step instructions on how to manage your Kubernetes cluster using the kubectl command-line tool.
What is kubectl?
Kubectl is the CLI tool for Kubernetes that allows you to interact with your clusters, create, manage, edit, and delete resources with ease. It communicates with the Kubernetes API server so you can monitor and control your applications.
How does kubectl work?
Kubectl operates by sending commands to the Kubernetes API server, which then carries out the requested operations within the cluster. When you execute a kubectl command, such as deploying an application or retrieving the status of resources, kubectl communicates with the API server over HTTP, transmitting your instructions. The API server processes these requests, updates the cluster's state in etcd (a distributed key-value store), and directs other components, like the scheduler or controller manager, to perform necessary actions to achieve the desired state. This interaction allows you to efficiently manage and monitor your Kubernetes resources from the command line.
In earlier versions of Kubernetes, kubectl utilized generators to create resource configurations based on specific inputs. These generators allowed users to specify the type of resource to create, such as a Pod, Deployment, or Job, by using the --generator flag. For example, kubectl run nginx --image=nginx --generator=run-pod/v1 would create a Pod resource. This approach enabled users to script and automate resource creation with predictable outcomes. However, it's important to note that the --generator flag was deprecated in Kubernetes v1.12 and removed in v1.18. As of v1.18, kubectl run is simplified to create only Pods, and the use of generators has been replaced by more explicit and declarative commands like kubectl create and kubectl apply
Now, let’s start:
Optional Flags
Kubectl provides optional flags that enhance command output and resource management. For example:
Output Formats:
JSON Output:
You can use the -o=json flag to format command output as JSON.
kubectl get pods -o=json
YAML Output:
You can use the -o=yaml flag to format command output as YAML.
kubectl get pods -o=yaml
Wide Output:
The -o=wide option provides detailed plain-text output (e.g., it displays the node name for pods).
kubectl get pods -o=wide
For more tailored outputs, kubectl offers the --custom-columns flag, allowing you to define specific columns to display.
For example, to list pods with their names and the nodes they're running on:
kubectl get pods -o=custom-columns="POD NAME:.metadata.name,NODE:.spec.nodeName"
This command will output:
POD NAME NODE
nginx-deployment-1 node-1
nginx-deployment-2 node-2
Namespace Specification:
By default, kubectl commands operate within the namespace defined by the current context. To target a specific namespace, you can use the -n or --namespace flag:
kubectl get pods -n
To view resources across all namespaces, the -A or --all-namespaces flag is used:
kubectl get pods -A
And to set a default namespace for the current context:
kubectl config set-context --current --namespace=ns_name
File Input:
The -f flag is used to specify a filename, directory, or URL when creating a resource.
kubectl create -f ./file_name
Label Filtering:
You can use the -l flag to filter resources based on specific labels.
kubectl get pods -l name=label_name
Help Option:
To display help for kubectl commands, use the -h flag.
kubectl -h
Watch Mode:
You continuously monitor resource changes with the --watch (or -w) flag:
kubectl get pods -w
Sorting Output:
You can sort the output based on a specific field using the --sort-by flag:
kubectl get pods --sort-by=.metadata.name
kubectl Usage with Aliases
When you working with kubectl, it involves typing lengthy commands, which can be time-consuming and error-prone. To improve efficiency, many developers create aliases for frequently used commands.
Setting Up a Basic Alias
alias k=kubectl
echo 'alias k=kubectl' >> ~/.bashrc
This allows you to use k in place of kubectl.
You can use the kubectl-aliases repository, which provides hundreds of pre-defined aliases, enabling quicker command execution.
For Cluster Management, Context and Configuration
Cluster Management means setting up, viewing, and modifying your cluster.
Command
Description
kubectl cluster-info
Displays the endpoints and basic information about your Kubernetes cluster.
kubectl config get-contexts
Lists all contexts defined in your kubeconfig file.
kubectl config current-context
Shows the current active context.
kubectl config use-context
Pod Management
Shortcode = po
A Pod is the smallest unit in Kubernetes, representing a single instance of a running process in your cluster. It can contain one or more containers that share storage and network resources.
Command
Description
kubectl get pods
Lists all pods in the current namespace.
kubectl describe pod
For ReplicaSets
Shortcode = rs
A ReplicaSet ensures a specified number of pod replicas are running. The main difference is that ReplicaSets support set-based label selectors.
Command
Description
kubectl get rs
Lists all ReplicaSets in the current namespace.
kubectl get rs
For Daemonsets
Shortcode = ds
A DaemonSet ensures that a specific pod runs on all (or some) nodes in the cluster. This is useful for tasks like running a monitoring agent on every node.
Command
Description
kubectl get daemonset
Lists all DaemonSets in the current namespace.
kubectl describe daemonset
For StatefulSets
Shortcode = sts
StatefulSets manage the deployment and scaling of pods, ensuring each has a unique, stable identity and persistent storage. This is important for stateful applications.
Command
Description
kubectl get statefulset
Lists all StatefulSets in the current namespace.
kubectl describe statefulset
For Namespace
Shortcode = ns
Namespaces provide a way to divide cluster resources between multiple users or applications.
Command
Description
kubectl get namespace
Lists all namespaces in your cluster (the current context’s namespaces).
kubectl create namespace
For Services
Shortcode = svc
A Service defines a logical set of pods and a policy to access them. It enables communication between different parts of your application and can expose your application to external traffic.
Command
Description
kubectl get services
Lists all services in the current namespace
kubectl create service
For Service Accounts
Shortcode = sa
A ServiceAccount provides an identity for processes running in a pod, allowing them to interact with the Kubernetes API securely.
Command
Description
kubectl get serviceaccounts
Lists all service accounts in the current namespace
kubectl describe serviceaccount
For Deployments
Shortcode = deploy
A Deployment provides declarative updates for pods and ReplicaSets. You can define the desired state of your application, and the Deployment controller changes the actual state to the desired state at a controlled rate.
Command
Description
kubectl get deployment
Lists all deployments in the current namespace.
kubectl describe deployment
For Events
Shortcode = ev
Events are records of what happened in your cluster, such as pod creations, deletions, or errors.
Command
Description
kubectl get events
Lists all events in the current namespace
kubectl get events --field-selector type!=Normal
Displays events that are not of type Normal
kubectl get events --field-selector type=Warning
Filters and displays only events of type Warning
kubectl get events -w
Watches for new events in real-time
kubectl get events --field-selector involvedObject.name=
Logs
Logs are the output of your running applications and system components.
Command
Description
kubectl logs
For Secrets and Config Maps
Shortcode for ConfigMaps = cm
Secrets store sensitive information like passwords or keys, while ConfigMaps hold non-sensitive configuration data. Both allow you to decouple configuration artifacts from image content to keep your applications portable.
Command
Description
kubectl get secrets
Lists all secrets in the current namespace
kubectl get configmaps
Lists all ConfigMaps in the current namespace
kubectl describe secret
For Node Management
Shortcode = no
A Node is a worker machine in Kubernetes.
Command
Description
kubectl get nodes
Lists all the nodes in your cluster
kubectl describe node
For Storage(PV, PVC)
Shortcode for Persistent Volume = pv
Shortcode for Persistent Volume Claim = pvc
PersistentVolumes are storage resources in your cluster, and PersistentVolumeClaims are requests for storage by users.
Command
Description
kubectl get pv
Lists all Persistent Volumes in the cluster
kubectl describe pv
For Copying Files and Directories
You can transfer files between your local system and a pod's container helping in debugging or data backup.
Command
Description
kubectl cp
For Output Verbosity and Debugging
Verbosity refers to the level of detail included in the logs generated by components like kubectl and kubelet. You can adjust the verbosity of kubectl commands.
Command
Description
kubectl get
Reduce up to 50% of your Cloud Costs with PerfectScale
PerfectScale is a powerful tool designed to work seamlessly with Kubernetes. By integrating PerfectScale into your Kubernetes environment, you can simplify and optimize the orchestration of your containers. This integration enhances the efficiency of managing your clusters, allowing you to allocate resources more effectively, reduce operational costs, and improve the overall stability and resilience of your applications. PerfectScale's AI-driven insights provide comprehensive visibility into your system's performance, enabling proactive adjustments to meet dynamic demands. This means you can ensure peak performance while cutting costs by up to 50% through data-driven, autonomous actions that continuously optimize each layer of your Kubernetes stack. To experience the benefits of PerfectScale firsthand, consider Booking a Demo today and Start a Free Trial today!