Only registred users can make comments

Kubectl Cheat Sheet: Navigating Kubernetes in CLI

This Kubectl Cheatsheet is a quick reference for many useful kubectl commands.

It is a work in progress and we will be adding more commands as we go along. If you have any suggestions, please feel free to open an issue or a pull request. Don't forget to sign up for our newsletter
 
You can find this kubectl cheat sheet on our GitHub repository
 

Table Of Content

What is Kubectl
How The Communication Works
How to install Kubectl
Cluster Information
Resource Management
Inspecting Resources
Creating and Updating Resources
Deleting Resources
Scaling Deployments
Exposing Deployments
Managing Rollouts
Working with Logs
Executing Commands in Containers
Port Forwarding
Labeling and Annotating Resources
Configuring Kubectl
Dry Run
Looping Through Resources
Create Resources with cat command
Flattening Kubeconfig files
Getting API Resources
Custom Columns --custom-columns
Use kubectl auth can-i

Summary
About The Author

What Is Kubectl

This is the tool that most Kubernetes engineers primarily use when interacting with a Kubernetes cluster.

Behind the scenes, kubectl interacts directly with the Kubernetes API, converting the commands you type into API requests, which are then executed on the Kubernetes cluster.

With kubectl, you can perform a wide range of operations on the cluster, such as creating, deleting, and updating deployments, exposing your application, checking the logs of your running pods, and monitoring the health and capacity of your nodes and the overall cluster health.

To begin using kubectl, you must first install it on your local machine. Please refer to the next section for installation instructions.

 

How The Communication Works

The communication between kubectl and the Kubernetes cluster is based on RESTful HTTP requests and responses.

The following diagram illustrates how kubectl interacts with Kubernetes resources:

When you issue a command using kubectl, the tool reads the kubeconfig file on your local machine and obtains all the necessary information to authenticate with the Kubernetes API server. This file includes details about the Kubernetes server's address, your credentials, and context information.

The connection between kubectl and the API server is usually secured by TLS encryption to ensure that no tampering or eavesdropping occurs.

Authentication and authorization occur before the API server processes your request. The API server validates your credentials. There are various ways Kubernetes can authenticate you, which are covered in detail in the following article: Kubernetes - RBAC And Admission Controllers

Once you have been authenticated and authorized, the kubectl command is translated into an API request that conforms to the Kubernetes API specification.

The request is typically a RESTful HTTP request, containing a specific method (GET, POST, PUT, DELETE, etc.). It also targets the relevant API endpoint (e.g., /api/v1/namespaces/default/pods) and includes the necessary data in JSON format (if applicable). The request is then sent over the secure connection to the Kubernetes API server, along with the required headers and your credentials.

Upon receiving the API request, the API server processes it and performs the necessary operations, such as creating or updating resources.

Kubectl receives the API response from the Kubernetes API server, which typically includes data in JSON format, log messages, and more.

Finally, kubectl displays the message to the user in the terminal 🏅

How To Install Kubectl

Download the latest version:

curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/darwin/amd64/kubectl"

Download a specific version:

curl -LO "https://dl.k8s.io/release/v1.24.0/bin/darwin/amd64/kubectl"

To make the kubectl binary executable:

chmod +x ./kubectl

To be able to run kubectl without specifying the path, move the kubectl binaries to a file location on your system PATH:

sudo mv ./kubectl /usr/local/bin/kubectl
sudo chown root: /usr/local/bin/kubectl

to check the version

kubectl version --client

Output:

Client Version: version.Info{Major:"1", Minor:"19", GitVersion:"v1.19.7", GitCommit:"1dd5338295409edcfff11505e7bb246f0d325d15", GitTreeState:"clean", BuildDate:"2021-01-13T13:23:52Z", GoVersion:"go1.15.5", Compiler:"gc", Platform:"darwin/amd64"}

Cluster Information

With the following command, we can get information about the cluster, like the version of Kubernetes that is running, the IP address of the master, and the names of the nodes in the cluster.
kubectl cluster-info # get info about the cluster
kubectl cluster-info dump # dump current cluster state to stdout

Resource Management

The following commands are used to manage resources in the cluster:
 
kubectl get nodes # list all nodes in the cluster
kubectl get pods # list all pods in the namespace or with --all-namespaces flag
kubectl get services
kubectl get deployments
kubectl get secrets
kubectl edit <resource-type> <resource-name> # edit a resource in the default editor


# Flags
--all-namespaces # list the requested object(s) across all namespaces
--watch # after listing/getting the requested object, watch for changes
-o # output format example -o yaml or -o json
--show-labels # show labels in the last column
--selector # filter results by label selector example --selector env=prod
--sort-by # sort list types using a jsonpath expression example --sort-by='{.metadata.name}'
--field-selector # filter results by a field selector example --field-selector metadata.name=nginx
--no-headers # when using the default or custom-column output format, don't print headers (default print headers) 
--output-watch-events # output watch event objects when --watch or --watch-only is used example kube get pods --watch --output-watch-events

Inspecting Resources

The following commands are used to inspect resources in the cluster.
Also we have included the `kubectl explain` command which is used to get the documentation of a resource type.

kubectl describe nodes <node-name> # get detailed information about a node
kubectl describe pods <pod-name> # get detailed information about a pod
kubectl describe services <service-name> # get detailed information about a service
kubectl describe deployments <deployment-name> # get detailed information about a deployment
kubectl explain <resource-type> # get the documentation of a resource type example kubectl explain pods
 

Creating and Updating Resources

With the following commands, we can create and update resources in the cluster:

kubectl create -f <file-name>
kubectl apply -f <file-name>
kubectl delete -f <file-name>
 

Deleting Resources

With the following commands, we can delete resources in the cluster:
kubectl delete pods <pod-name>
kubectl delete services <service-name>
kubectl delete -f <file-name>
kubectl delete deployment <deployment-name> # delete a deployment
kubectl delete namespace <namespace-name> # delete a namespace

Scaling Deployments

With the following command, we can scale our deployments:

kubectl scale deployment <deployment-name> --replicas=<number-of-replicas>

Exposing Deployments

With the following commands we can expose Kubernetes deployments using kubectl with different service types: ClusterIP, NodePort, and LoadBalancer.
Exposing a deployment allows you to make the application accessible to users or other services, either within the cluster or externally.
kubectl expose deployment <deployment-name> --type=ClusterIP --port=<port> # Exposes the service on a cluster-internal IP. Choosing this value makes the service only reachable from within the cluster.
kubectl expose deployment <deployment-name> --type=NodePort --port=<port>
kubectl expose deployment <deployment-name> --type=LoadBalancer --port=<port> # In cloud providers that support load balancers, an external IP address would be provisioned to access the service.

❗The loadbalancer service type is only supported in cloud providers that support load balancers.

 Managing Rollouts

With the following commands, we can manage the rollouts of our deployments.
Rollouts are an essential part of the deployment process, as they allow you to update your applications while minimizing downtime and ensuring transitions between versions.

kubectl rollout status deployment <deployment-name> # Check the status of a rollout
kubectl rollout history deployment <deployment-name> # Check the history of a rollout
kubectl rollout undo deployment <deployment-name> # Rollback to the previous revision
kubectl rollout undo deployment <deployment-name> --to-revision=<revision-number> # Rollback to a specific revision

 

Working with Logs

With the following commands, we can work with the logs of our pods:
kubectl logs <pod-name>
kubectl logs -f <pod-name> # follow the logs
kubectl logs -p <pod-name> # print the logs for the previous instance of the container in a pod if it exists

Executing Commands in Containers

Sometimes we need to execute commands in a container:

kubectl exec <pod-name> -- <command> # execute a command in a container
kubectl exec -it <pod-name> -- <command> # execute a command in a container interactively
# enter the container's shell
kubectl exec -it <pod-name> -- /bin/bash # bash shell, very common to get into a container
# copy files to and from a container
kubectl cp <pod-name>:<path-to-file> <path-to-local-file> -c <container-name> # copy a file from a container to the local machine
kubectl cp <path-to-local-file> <pod-name>:<path-to-file> -c <container-name> # copy a file from the local machine to a container
 

Port Forwarding

With the following command, we can forward a local port to a port on a pod or service.
This is very handy if the application is not exposed to the outside world, but you still want to access it.
kubectl port-forward <pod-name> <local-port>:<container-port>
kubectl port-forward <service-name> <local-port>:<container-port>

 

Labeling and Annotating Resources

With the following commands, we can add labels and annotations to resources in the cluster.
This is useful for organizing and grouping resources, as well as for attaching metadata to resources.

kubectl label pods <pod-name> <label-key>=<label-value>
kubectl annotate pods <pod-name> <annotation-key>=<annotation-value>

Taints and Tolerations

Taints and tolerations are a way to control how pods are scheduled on nodes.
For example, we can use taints to prevent pods from being scheduled on nodes that have sensitive data.
kubectl taint nodes <node-name> <key>=<value>:<effect> # taint a node
kubectl taint nodes <node-name> <key>:<effect> # remove a taint from a node
kubectl taint nodes <node-name> <key>:NoSchedule # prevent pods from being scheduled on the node
kubectl taint nodes <node-name> <key>:NoExecute # prevent pods from being scheduled on the node and evict existing pods
kubectl taint nodes <node-name> <key>:PreferNoSchedule # prefer not to schedule pods on the node


Tolerations are applied to pods, and allow (but do not require) the pods to schedule onto nodes with matching taints.

Example pod spec with tolerations:

apiVersion: v1
kind: Pod
metadata:
  name: nginx
  labels:
    env: test
spec:
    containers:
    - name: nginx
        image: nginx
    tolerations:
    - key: "key"
        operator: "Equal"
        value: "value"
        effect: "NoSchedule"

This toleration block allows the Nginx Pod to be scheduled on any node that has a taint with the key "key", the value "value", and the effect "NoSchedule".

Tolerations enables a fine-grained control over where Pods are scheduled in a Kubernetes cluster and allows us to run workloads on specific nodes based on their taints.

Configuring Kubectl

kubectl config view # display merged kubeconfig settings or a specified kubeconfig file
kubectl config current-context # display the current-context
kubectl config use-context <context-name> # set the current-context in a kubeconfig file
kubectl config set-context <context-name> # set a context entry in kubeconfig
kubectl config set-cluster <cluster-name> # set a cluster entry in kubeconfig
kubectl config set-credentials <user-name> # set a user entry in kubeconfig
kubectl config unset users.<name> # unset a user entry in kubeconfig
 
The kubectl config set-cluster command is used to define a new cluster or update an existing one in the Kubeconfig file. This file contains the necessary information for kubectl to connect and interact with a Kubernetes cluster.
kubectl config set-cluster <cluster-name> \
--certificate-authority=<path-to-ca-file> \
--embed-certs=<true|false> \
--server=<address-and-port-of-api-server> \
--kubeconfig=<path-to-kubeconfig-file>

Dry Run

Dry run allows us to preview the changes that will be made to the cluster without actually making them. This is useful for debugging and testing.
 
kubectl apply --dry-run=client -f <file-name>

Looping Through Resources

At times, it's necessary to iterate over resources in our Kubernetes clusters, such as when we want to remove all pods within a particular namespace. Using a combination of bash and kubectl commands, we can accomplish this task effectively:

kubectl get pods -o name | cut -d/ -f2 | xargs -I {} kubectl delete pod {}
for pod in $(kubectl get pods -o name | cut -d/ -f2); do kubectl delete pod $pod; done

Create Resourses with cat command


With cat we can create resources from the terminal( from stdin):
cat <<EOF | kubectl create -f -
# create a n nginx pod
apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
    containers:
    - name: nginx
        image: nginx
EOF
 

Flattening Kubeconfig Files


Assume that you have multiple kubeconfig files and you want to merge them into one file. You can use the following command to do that.

```bash
KUBECONFIG=~/.kube/config:~/.kube/config2:~/.kube/config3 kubectl config view --flatten > ~/.kube/merged-config
```
then you can run the following command to use the merged kubeconfig file:

```bash
export KUBECONFIG=~/.kube/merged-config
```

Getting API Resources

kubectl api-resources lists all the available API resources in a Kubernetes cluster.

This command provides an overview of the different resource types supported by the API server, such as pods, services, deployments, etc. It also displays the short names and API group information for each resource.

kubectl api-resources
kubectl api-resources --namespaced=true # lists  namespaced resources only
# how to get curl call from kubectl with log level 9
kubectl get pods -v=9 2>&1 | grep curl # get curl call for a specific resource
kubectl get pods -v=9 2>&1 | grep curl | sed 's/.*curl -k -v -XGET/https/' | sed 's/ -H .*//' # get curl call for a specific resource

To obtain the curl command that corresponds to a specific kubectl request, we can set the log level to 9. This provides detailed debugging information, including the API server calls made by kubectl.

Example:
kubectl get pods -v=9  2>&1 | grep curl

# Output
3076 round_trippers.go:466] curl -v -XGET  -H "User-Agent: kubectl/v1.25.2 (darwin/arm64) kubernetes/5835544" -H "Authorization: Bearer <masked>" -H "Accept: application/json;as=Table;v=v1;g=meta.k8s.io,application/json;as=Table;v=v1beta1;g=meta.k8s.io,application/json" 'https://192.168.64.2:16443/api/v1/namespaces/web-app/pods?limit=500'

 

Custom Columns --custom-columns

--custom-columns is not very known to many people, at least from my experience.

When managing Kubernetes pods, having the ability to customize your command line output can be incredibly powerful. kubectl provides the --custom-columns option to do just that, enabling you to specify and format your own columns for a more tailored display of resources. 

Here's how you can use this feature:

kubectl get pods -o custom-columns=NAME:.metadata.name

This command will list all pods, showing only the custom column NAME with the value from each pod's .metadata.name field.

For more detailed insights, you can add multiple columns:

kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase

Output:

NAME                                               STATUS
keda-operator-metrics-apiserver-5bb87b6cc5-hqmrb   Running
devoriales-rabbitmq-0                              Running
keda-admission-webhooks-6b4b4b64fc-4wc8b           Running
keda-operator-7fdd98c445-9ljhj                     Running
consumer-deployment-58f8855bb7-hr7px               Running

With the above command, you're not only fetching the pod names but also their current phase, neatly organized into the NAME and STATUS columns.

Remember, the --custom-columns option takes a comma-separated list, allowing you to define multiple columns. Each column in the list is defined by a HEADER:JSON_PATH_EXPRESSION pair:

HEADER sets the column header.
JSON_PATH_EXPRESSION specifies the JSON path to the field whose values should appear in the column.
By using --custom-columns, you gain a focused view that can be adapted to the specific needs of your workflow, making your Kubernetes management both efficient and precise.

In the following example, we will set some odd header:

 kubectl get pods -o custom-columns=MY_SUPER_PODS:.metadata.name,STATUS:.status.phase

Output:

MY_SUPER_PODS                                      STATUS
keda-operator-metrics-apiserver-5bb87b6cc5-hqmrb   Running
devoriales-rabbitmq-0                              Running
keda-admission-webhooks-6b4b4b64fc-4wc8b           Running
keda-operator-7fdd98c445-9ljhj                     Running
consumer-deployment-58f8855bb7-hr7px               Running

Use kubectl auth can-i

kubectl auth can-i is used to check if subjects can perform an action on a resource.
The way how you specify this is by using the following syntax:
kubectl auth can-i <VERB> <RESOURCE> --namespace <NAMESPACE> --as <USER>
You can also set --all-namespaces flag to check if the user can perform an action on a resource in all namespaces.

Here is an practical example how we can check if the user can create pods in the default namespace:
kubectl auth can-i create pods --namespace default

Check if a service account can perform an action on a resource

The command `kubectl auth can-i` can be very handy when you want to check what a specific service account can do.
For example, you can check if the default service account in the default namespace can create pods:
kubectl auth can-i create pods --namespace default --as=system:serviceaccount:default:default

Output example:

yes

 --as flag is used to specify the service account.

system: is a prefix for service accounts.

serviceaccount:default:default is the name of the service account in the default namespace.

❗Please Note auth can-i assumes that your current user has the permissions to impersonate a service account. If not, you may need to adjust your RBAC policies accordingly.

Resources - Further Reading

 

Summary

In this Kubectl Cheatsheet blog post, we provide a reference guide for the most commonly used Kubernetes commands.
This cheatsheet covers a wide range of topics such as cluster information, resource management, inspecting resources, creating and updating resources, deleting resources, scaling deployments, exposing deployments, managing rollouts, working with logs, executing commands in containers, port forwarding, labeling and annotating resources, configuring kubectl, and more.
With detailed explanations and sample commands, this cheatsheet is a great resource for both beginners and experienced Kubernetes users looking to improve their workflow and increase their understanding of Kubernetes.
 

About the Author

Aleksandro Matejic, a Cloud Architect, began working in the IT industry over 21 years ago as a technical specialist, right after his studies. Since then, he has worked in various companies and industries in various system engineer and IT architect roles. He currently works on designing Cloud solutions, Kubernetes, and other DevOps technologies.

In his spare time, Aleksandro works on different development projects such as developing devoriales.com, a blog and learning platform launching in 2022/2023. In addition, he likes to read and write technical articles about software development and DevOps methods and tools.

You can contact Aleksandro by visiting his LinkedIn Profile

 
Comments
Commented by Aleksandro Matejic on 2023-11-02 10:33:31 Author

@Carlos glad to hear that it's useful for you. I'll keep adding more things to it.

Commented by Carlos Rodriguez on 2023-11-01 20:30:55

Forked the repository, great cheat sheet!