Kubectl Cheat Sheet PDF For Quick References
Kubectl Cheat Sheet PDF For Quick References
View offers
Programming Data Science DevOps Design Search for topics Submit a tutorial Jobs Sign In
Related Tutorials Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an a liate
commission.
Kubernetes
Docker
Recommended Learning
Introduction to Kubernetes (edx.org)
Kubernetes By Example
(kubernetesbyexample.com)
VIEW MORE
Sameeksha Medewar
Last Updated 24 May, 2022
Share:
Table of Contents
Kubernetesis one of the most famous container orchestration platforms. An open-source platform,
Kubernetes automates a wide range of management, deployment, and scaling tasks for containerized
applications.
A Kubernetes cluster is a set of control panes and worker machines called nodes, which form a cluster
every time you deploy Kubernetes. If you want to command your Kubernetes cluster to perform tasks,
you can use the command line kubectl. It uses Kubernetes API to communicate with a Kubernetes
cluster’s control pane. With it, you can perform almost any action on your Kubernetes cluster without
needing to make direct API calls.
Programmers with Kubernetes knowledge are in great demand, as many companies and
organizations embrace Kubernetes to develop applications e ciently.
Ready to make the most out of Kubernetes commands with kubectl? We’ve put together this kubectl
cheat sheet lled with insights about managing Kubernetes clusters, kubectl logs, kubectl list pods,
and much more.
With this kubectl and Kubernetes commands cheat sheet, you’ll be equipped to tackle any application
project.
Here is a link to the kubectl cheat sheet pdf that you can download and access o ine whenever and
wherever needed.
Kubectl Autocomplete
BASH
To set upan autocomplete in bash within the current shell, you must install the bash-completion
package using the following command.
For adding the autocomplete permanently to your bash shell, run the following command.
alias k=kubectl
complete -F __start_kubectl k
ZSH
To set upan autocomplete in zsh within the current shell, you need to run the following command.
echo "[[ $commands[kubectl] ]] && source <(kubectl completion zsh)" >> ~/.zshrc
Use several kubecon g les simultaneously and view the merged con g with this command:
KUBECONFIG=~/.kube/config:~/.kube/kubconfig2
kubectl config view
Save the namespace permanently for all subsequent kubectl commands in that context:
alias kx='f() { [ "$1" ] && kubectl config use-context $1 || kubectl config current-context ;
} ; f'
alias kn='f() { [ "$1" ] && kubectl config set-context --current --namespace $1 || kubectl
config view --minify | grep namespace | cut -d" " -f6 ; } ; f'
The “apply” helps manage the applications through les that de ne Kubernetes resources. You can
easily create and update resources within the cluster by running kubectl apply. It is one of the
commonly practiced ways for managing applications on production. Kubectl Apply
Creating Objects
Objects in Kubernetes are persistent entities that represent the state of your cluster.
A Kubernetes object is a "record of intent." After you create the object, the Kubernetes system will
constantly work to ensure that the object exists. By creating an object, you'retelling the Kubernetes
system about how your cluster's workload will look (desired state).
If you want to work with Kubernetes objects (create, modify, or delete), you need to use the
Kubernetes API. The kubectl command-line interface (CLI) makes it easier for you to make the
necessary Kubernetes API calls. Interested in using the Kubernetes API directly? Try out one of the
client libraries.
You can de ne the Kubernetes manifest le in YAML or JSON. This manifest le comes with the
extension as .yaml, .yml, and .json, etc.
The following are the commands that allow you to work around the manifest le. “Apply” is used to
push the required changes based on your con guration les.
Create resources:
** the “create” command will help in generating the new resources from les or standard input
devices.
Create a secret
We can use acustom resource to extend the Kubernetes API. It is not necessary that a custom
resource should always be available in the default installation of Kubernetes. Moreover, custom
resources have made it possible for us to create various core Kubernetes functions, which make
Kubernetes more modular in nature.
Dynamic registration makes it possible for custom resources to appear or disappear in a running
cluster. Also, cluster admins have the right to update custom resources without concerning the cluster
itself. Like the built-in resources, users can also create and access the objects of custom
resourceswhen they are installed.
List services sorted by name: Commands for Listing, Period Trees, and More
For this command, use a selector for excluding the results that have a label # named 'node-
role.kubernetes.io/master.'View all worker nodes:
This command is useful for transformations that are too complex for jsonpath, and can be found here.
List pod names of Pods that belong to Particular RC "jq:"
List all secrets currently in use by a pod:Get theoutput decoded secrets without external tools:
This command is helpful when cleaning up stopped containers, while avoiding removal of
initContainers.List all containerIDs of initContainer of all pods:
This command is helpful when locating a key within a complex nested JSON structure.
This command assumes you have a default container for the pods, default namespace and that the
`env` command is supported. It is helpful when running any supported command across all pods, not
just `env.`
Updating Resources
Roll the update "www" containers of "frontend" deployment, updating the image:
Createa service for a replicated nginx, which serves on port 80 and connects to the containers on
port 8000:
kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f -
Add a label:
Add an annotation:
Patching Resources
These commands will patch resources as required.
Keep in mind that the spec.containers[*].name is required because it's a merge key
Editing Resources
These commands will edit resources as required.
Scaling Resources
These commands will scale resources as required.
Scale mysql to 3 (when the deployment named mysql's current size is 2):
Deleting Resources
The following commands are used to delete the resources as required.
Delete podsand services with the same names "baz" and "foo:"
Dumppod container logs (stdout, multi-container case) for a previous instantiation of a container:
Run apod nginx and write its spec into a le called pod.yaml:
Listenon port 5000 on the local machine and forward to port 6000 on my-pod:
Copythe /tmp/foo_dir local directory to /tmp/bar_dir in a remote pod in the current namespace:
Listenon local port 5000 and forward to port 5000 on Service backend
Listenon local port 5000 and forward to Service target port with name <my-service-port>:
Listenon local port 5000 and forward to port 6000 on a Pod created by <my-deployment>:
Runcommand in rst pod and rst container in deployment (single- or multi-container cases):
kubectl cluster-info
Replace value as speci ed (if a taint with that key and e ect already exists):
Cluster Management
These commands help you manage clusters, from listing API resources to displaying pertinent
information:
kubectl cluster-info
kubectl version
kubectl api-resources
kubectl api-versions
List everything:
DaemonSet
ADaemonSetmakes sure that nodes run pod copies. Nodes and pods are added to clusters. Similarly,
pods undergo garbage collection once nodes are removed.When you delete a DaemonSet, all the
pods created by it also get deleted.
For simple cases, one DaemonSet could cover all nodes and each daemon type. A more complex
setup might use multiple DaemonSets for a single type of daemon, but with di erent ags, memory,
and CPU requests for various hardware types.
Shortcode = ds
Delete a DaemonSet:
Deployments
A deployment runs multiple application replicas and automatically replaces any failed or unresponsive
instances.Deployments are managed by the Kubernetes Deployment Controller. Moreover,
deployments make sure that user requests are served through one or more instances of your
application.
Shortcode = deploy
Events
A Kubernetes event is an object in the framework automatically generated in response to changes
with other resources—like nodes, pods, or containers.
State changes lie at the center of this. For example, phases across a pod’s lifecycle—like a transition
from pending to running, or statuses like successful or failed—may trigger a Kubernetes event. The
same goes for reallocations and scheduling.
Shortcode = ev
Logs
System component logs record events happening in a cluster, which can be useful for debugging.To
see the desired details of those events, you can con gure log verbosity.
There can be two types of logs, namely ne-grained and coarse-grained. Coarse-grained logs
represent errors within a component. On the other hand, ne-grained logs represent step-by-step
traces of events.
Retrieve the logs from a service and optionally selecting which container:
Get the output of the logs for a pod into a le named ‘pod.log:’
Namespaces
In Kubernetes, namespaces provide a mechanism for isolating groups of resources within a single
cluster. Resource names must be uniquewithina namespace but notacrossnamespaces. Namespace-
based scoping is applicable only for namespaced objects (e.g., Deployments, Services, etc.) and not
for cluster-wide objects (e.g., StorageClass, Nodes, PersistentVolumes, etc.).
Shortcode = ns
Delete a namespace:
Replication Controllers
A replication controller is a key Kubernetes feature, responsible for:
Shortcode = rc
kubectl get rc
ReplicaSets
RepliceSets ensure you have a stable set of replica pods operating. You might use one to con rm that
identical pods are available.
Shortcode = rs
Scale a ReplicaSet:
Secrets
A secret is an object containing a small amount of sensitive data such as a password, token, or key.
This information is either stored in a Pod speci cation or in a container image.Ifyou use a Secret, you
don't need to include con dential data in your application code.
Delete a secret:
Services
Services are anabstract way to expose an application running on a set of Pods as a network service.
If you want to use any unfamiliar servicediscovery mechanism, there is no need to make changes to
your application when developed using Kubernetes. This is because Kubernetes assigns each pod
with a unique IP address and a single DNS can manage all the load across multiple pods.
Shortcode = svc
Service Accounts
A service account provides an identity for processes that run in a pod. Here is a useful introduction to
Service Accounts.
Shortcode = sa
Listservice accounts:
StatefulSet
StatefulSets represent a set of pods with unique, persistent identities and stable hostnames that GKE
maintains regardless of where they are scheduled.The persistent disk storage associated with the
StatefulSet is responsible for storing state information and other resilient data for the given StatefulSet
pod.
Shortcode = sts
ListStatefulSet:
Conclusion
If you want to enter the Kubernetes world with high pro ciency in managing containers, this kubectl
cheat sheet will help you achieve your goals.
Don’t forget to download our kubectl cheat sheet so you can have easy access to the commands
whenever you’d like.
Have a job interview coming up? Prepare even more with our article about Kubernetes interview
questions!
The commandportion describes what operation you want to perform, such as create, describe, get,
apply, and delete.
Typedescribes the kind of resource kubectl is targeting, such as pods, services, daemonsets,
deployments, replicasets, statefulsets, Kubernetes jobs, and cron jobs, etc
Nameis a case sensitive eld that speci es the name of the resource in question. Flagshelp denote
special options or requests made to a certain resource.
Open a bash command shell in kubectl exec, where you can execute commands:
Share:
Sameeksha Medewar
Sameeksha is a freelance content writer for more than half and a year. She has a hunger to
explore and learn new things. She possesses a bachelor's degree in Computer Science. View all
posts by the Author
Related Posts
Leave a comment
Email address* Name*
Comment*
SUBMIT
Blog Roadmaps About Us Programming Tips Help & FAQ We Feedback Advertise / Partner Write for us Privacy Policy
Disclosure: This page may contain affliate links, meaning when you click the links and make a purchase, we receive a commission.