The guide to kubectl I never had.
What kind of engineer are you? π€ Can somebody guess by just looking at you? More than likely not.
Would that somebody be able to tell by looking at your keyboard instead? Might be a bit easier now. β¨οΈ
You know you are dealing with a Kubernetes engineer when the βkβ key on their keyboard has seen better days. At the Glasskube office, you will find spare βkβ keys all over the place, just in case π
Iβm joking of course.
Iβm not really sure about what a faded keyboard says about its owner. What I do know for sure is how important kubectl
is to anybody who wants to be a proficient Kubernetes administrator.
kubectl
is the CLI tool used to communicate to the Kubernetes API it can seem simple at first but can quickly get complicated.
So in this blog post, I aim to write the guide I wish I had when I started. Focusing first on command syntax and useful commands, before moving on to the vibrant ecosystem of plugins and tools built to expand the functionalities of kubectl
and Kubernetes.
Sharing tips and tricks along the way as well as a helpful kubecltl cheatsheet
at the end. π
Letβs get to it. βΈοΈ
Disclaimer πβ
This isnβt an article about Kubernetes. K8s is an incredibly vast technology, encompassing numerous concepts, such as various types of Kubernetes objects and their interactions. For this discussion, I'll assume you're familiar with these concepts. Instead, I'll focus specifically on
kubectl
, its usage, and the tools built around it.
Just before we beginβ
If you are a fan of supporting Open Source projects working to make Kubernetes package management better for everyone then please consider supporting Glasskube, by giving us a Star on GitHub π
Installationβ
To install kubectl
, you have a few different options depending on your operating system. Here's how to install it on some common platforms:
Linux (Ubuntu/Debian)β
sudo apt-get update && sudo apt-get install -y kubectl
MacOS using Homebrewβ
brew install kubectl
Windows using Chocolateyβ
choco install kubernetes-cli
After installation, you can verify if kubectl has been installed correctly by running:
kubectl version --client
kubectl commands:β
kubectl
is a Command Line Interface (CLI) tool used to communicate with the Kubernetes API. There are many commands, too many to remember.
Donβt worry though itβs not as daunting as some might want you to think.
We will explore ways to quickly access command references, k8s-object-specific commands, helpful aliases, and command completion. But first, how are command strings built?
The syntaxβ
English and Chinese are subject-verb-object (SVO)
languages.
Hindi and Korean are subject-object-verb (SOV)
languages.
If kubectl were a language, it would be a kubectl + verb + object/[name optional] + flag
(kvof) language π
Also similar to languages, the best way to learn and absorb grammar is by using it in context and not memorizing long verb and object lists.
βΉοΈ If you are stuck and want to quickly reference the existing Kubernetes objects in any Kubernetes version run
kubectl api-resources
.
Commands are built by choosing that action [verb]
you want to apply to the desired Kubernetes resource [object]
usually followed by the name of the resource additionally you have a large array of filters [flags]
that can be applied to the command which will determine the final scope and output.
Letβs look at a simple example of command building using the commonly used get
verb to retrieve all resources in the glasskube-system
namespace, and the output is in yaml
format:
kubectl get all --namespace glasskube-system -o yaml
βΉοΈ If you come across a Kubernetes resource that you havenβt heard of before or need a refresher use
kubectl explain [resource-name]
to get an in-terminal description and usage instructions.
Working imperativelyβ
When working in Kubernetes environments your tasks are many, anything from deploying new apps, troubleshooting faulty resources, inspecting usage, and much more. Later on, we will explore how useful declarative ways of working are more appropriate for defining and deploying workloads, but for everything else we have our arsenal of useful imperative Kubernetes commands at the ready.
Simple commands to get us started are:
# Create a new deployment named "nginx-deployment" with the nginx image
kubectl run nginx-deployment --image=nginx
# Delete a pod named "nginx-deployment" in the default namespace
kubectl delete pod nginx-deployment
To take imperative commands to the next step know that you can modify resources by using the TUI editor:
By running kubectl edit -n [namespace] [resource-name]
a text editor like the one below will open. Make you edits and close the editor just like in vim by running ESC + :q!
.
# Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving this file will be
# reopened with the relevant failures.
#
apiVersion: v1
kind: Pod
metadata:
annotations:
kubectl.kubernetes.io/default-container: manager
creationTimestamp: "2024-04-22T17:07:39Z"
generateName: glasskube-controller-manager-556ff6fccf-
labels:
control-plane: controller-manager
pod-template-hash: 556ff6fccf
name: glasskube-controller-manager-556ff6fccf-4qlxz
namespace: glasskube-system
ownerReferences:
- apiVersion: apps/v1
blockOwnerDeletion: true
controller: true
kind: ReplicaSet
name: glasskube-controller-manager-556ff6fccf
uid: 430e90e9-32f3-45f6-92dc-4bae26ae1654
"/var/folders/2q/wjmbwg1n5vn8v7vlw17nsz0h0000gn/T/kubectl-edit-1306753911.yaml" 209L, 5898B
Most commands are applicable to all sorts of Kubernetes objects. Insofar as it is useful further down we will touch on specific commands that are useful for certain Kubernetes resources. Before that though, itβs worth learning about some useful flags that can be applied to many different objects.
Useful flags:β
--env:
The --env
flag allows you to specify environment variables for the container being created.
kubectl run nginx-deployment --image=nginx --env="ENV_VARIABLE=value"
--template: This flag allows you to specify a Go template for the output format of your kubectl command. It's handy when you want to customize the output structure, filtering, or presentation.
kubectl get pods --template='{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'
--dry-run=[client/server]:
Massively useful when you want render a manifest for an object you don't remember how to write from scratch or have a template at hand. The --dry-run
flag prints the object manifest that would be sent without sending it. Use the server
option to see the server side request that would be generated.
kubectl create secret generic github-api-token --from-literal token=$GITHUB_TOKEN --dry-run=client -o yaml
Concatenating the command with other tools can be very useful too. Taking the example above, you can pipe the output of the generated manifest and pass in into a third party secret manager like Sealed-secrets to create a kubeseal secret manifest.
kubectl create secret generic github-api-token --from-literal token=$GITHUB_TOKEN --dry-run=client -o yaml | kubeseal --format yaml > api-token-secret.sealed.yaml
--field-selector: With this flag, you can filter resources based on specific fields. For instance, you can filter pods based on their status or labels.
kubectl get pods --field-selector=status.phase=Running
--field-selector type=[Normal/Warning]: This is a specific use of the --field-selector flag, where you filter events based on their type, either Normal or Warning.
**kubectl events -n [resource-namespace] --for=[resource-kind]/[resource-name]: ** This command fetches events related to a specific resource in the specified namespace. It continuously watches for new events related to the given resource.
kubectl events -n my-namespace --for=deployment/my-deployment
Old School vs. New School watching flags:β
watch vs. -w:
watch
: This is a traditional Unix command used to execute a specified command repeatedly at regular intervals, displaying its output in the terminal. Unlike the -w flag in kubectl, the watch command does not automatically update the terminal output when changes occur.
-w
: This is a modern flag in kubectl that enables continuous watching for changes to resources.
Working with Podsβ
Pods are the smallest abstraction inside the Kubernetes ecosystem, they are the logical units that house your containers. Pods consume resources and can be executed into and produce logs. Here are some commands that will help you manage pods.
# Show resource usage of a pod
kubectl top pod -n [namespace] [pod-name]
# Run a command inside a new pod in the cluster
kubectl run -it ubuntu --image ubuntu --rm -- bash
# Show resource labels as columns
# e.g. kubectl get pods -n [namespace] -L vault-active -L vault-sealed
kubectl get pods -n [namespace] -L vault-active -L vault-sealed
# Execute a command inside a pod
kubectl exec -it [pod-name] -n [namespace] --
# Port forward to a pod
kubectl port-forward [pod-name] [local-port]:[remote-port] -n [namespace]
# Show container logs
kubectl logs -n [namespace] [pod-name]
kubectl logs -n [namespace] /deployment/[deployment-name] # Use -f flag for continuous streaming
# Run a command inside an existing container
kubectl exec -it -n [namespace] [pod-name] -- [command...]
Working with nodesβ
Nodes are the underlying instances that provide computational power and storage on top of which your Kubernetes cluster runs.
# Show node resource utilization
kubectl top node [node-name] # Node name is optional; without shows table of all nodes
# Get node information
kubectl get node
Working with Deployments, DaemonSets and StatefulSetsβ
Deployments, DaemonSets, and StatefulSets are higher-level abstractions in Kubernetes that manage the deployment and scaling of application workloads.
# Restart a workload (e.g. deployment, stateful set, daemon set)
kubectl rollout restart -n [namespace] [workload-kind]/[workload-name] # Triggers a re-creation of all pods for this workload, adhering to the workload configuration
# Check the status of a deployment rollout
kubectl rollout status deployment/[name]
# View rollout history of a deployment
kubectl rollout history deployment/[name] # View rollout history of a deployment
# Scale a deployment to the specified number of replicas
kubectl scale deployment/ --replicas=[number] # Scale a deployment to the specified number of replicas
# Watch events related to a deployment
kubectl events -n glasskube-system --for=deployment/glasskube-controller-manager
#Update Deployment Image
kubectl set image deployment/[deployment-name] [container-name]=new-image:tag
# Delete DaemonSet
kubectl delete daemonset [daemonset-name]