Published 2023-04-02 13:39:17
Kubectl Cheat Sheet: Navigating Kubernetes in CLI
This Kubectl Cheatsheet is a quick reference for many useful kubectl commands.
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:
Me
+--------------------------+
x x | Kubernetes cluster |
x x | |
x x | +---------+ |
x +---------+ | | | |
x commands | | GET, POST, PUT etc. | | api | |
x -------------->| kubectl +---------------------+------+ server | |
x x | <---------------------+------+ | |
x x x <-------- +---------+ Response | +---------+ |
x x x displays | |
x x x commands | |
x | |
x | |
x +--------------------------+
x
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
kubectl cluster-info # get info about the cluster
kubectl cluster-info dump # dump current cluster state to stdout
Resource Management
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
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
kubectl create -f <file-name>
kubectl apply -f <file-name>
kubectl delete -f <file-name>
Deleting Resources
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
kubectl scale deployment <deployment-name> --replicas=<number-of-replicas>
Exposing Deployments
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
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
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
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
kubectl port-forward <pod-name> <local-port>:<container-port>
kubectl port-forward <service-name> <local-port>:<container-port>
Labeling and Annotating Resources
kubectl label pods <pod-name> <label-key>=<label-value>
kubectl annotate pods <pod-name> <annotation-key>=<annotation-value>
Taints and Tolerations
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
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
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
kubectl apply --dry-run=client -f <file-name>
Looping Through Resources
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
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
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
.
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.kubectl auth can-i <VERB> <RESOURCE> --namespace <NAMESPACE> --as <USER>
kubectl auth can-i create pods --namespace default
Check if a service account can perform an action on a resource
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.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
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
@Carlos glad to hear that it's useful for you. I'll keep adding more things to it.