In this article we are sharing Kubernetes Cheat sheet for the devops engineers throughout the world. Having a kubernetes cheat sheet on hand is helpful in a lot of ways. For instance it is highly unusual for anyone to remember all kubernetes commands. Hence, people can refer to this Kubernetes Cheat sheet for guidance.
In an era of abruptly advancing the IT field, the development and deployment of applications on a large scale have become a sort of challenge. However, thanks to the container technologies, which provided a new approach to developers to write and deploy applications. Containers technology enables developers to easily package up a form with all of its necessary parts, which include libraries and dependencies, and transfer it all out as one package. All this procedure can be managed without the availability of a virtual machine. However, containers themselves alone aren’t enough to run the mega show. To build complex applications that require various components covering numerous containers on several different machines, containers orchestration tools are needed.
One tool which has been becoming a developer’s favorite tool for fulfilling the orchestration needs of containerized applications is Kubernetes. In this article, we’re offering a basic overview of Kubernetes, its functionality, and feature. Moreover, we will also go through the Kubernetes Cheat Sheet, keeping in mind the aspirants who are looking to learn Kubernetes as a tool. This cheat sheet will work as a handy reference while implementing what they have learned. Furthermore, in this cheat sheet, you will grasp basic concepts about Kubernetes.
What is Kubernetes?
Kubernetes that is also known as “k8s” or “Kube,” is an open-source container orchestration platform. While deploying, managing, and scaling containerized applications, it helps automates the manual processes involved in the whole cycle. In simpler terms, you can ensemble groups of hosts running Linux containers. Kubernetes is a tool that helps you efficiently manage those clusters with ease.
Kubernetes itself is not a “Platform as a Service (PaaS)” tool. Instead, its role is more to serve as a basic framework. It allows developers to choose various useful options such as application frameworks types, monitoring and logging tools, languages, and several other tools of their choice. The utility of Kubernetes is work as the basis for a complete PaaS to implement the procedures mentioned above in application development.
Some of the key features of Kubernetes are as under:
- It is a container orchestrator
- It has capabilities to run a Linux container.
- Launches a container
- It maintains and observes the container site
- Handles container-oriented networking
Google and Kubernetes
Kubernetes was an idea of Google who created it. Before announcing Kubernetes as an open-source project in 2014, Google had been running similar systems in nature to manage containers as a part of their internal infrastructure. With time, Kubernetes can be seen as a rapidly growing open-source community. Active involvement and continuous contribution from the engineers based at Google, Red Hat, and many other development companies to the Kubernetes project have played an essential role in its success.
The Architecture of Kubernetes?
The below diagram illustrates the architecture of Kubernetes:
Key Concepts
Before going into further details, let’s go through the key features of this architecture.
Term | Definition / Function |
Node | A machine in the cluster |
Docker | It helps in containers creation that includes apps |
Pods | It is the basic building block of Kubernetes. Considered the most straightforward and smallest unit in the Kubernetes model that developers create or deploy. It is also called a group of containers. |
Service | It is defined as a concept which outlines a logical set of Pods with a policy through which developers can access them |
Label | It is used to identify pods |
Jobs | The role of the job is to create pod(s) and ensure that a specified number is completed. To consider a job “completed,” the specified number of the successful run of pods must be achieved |
Cronjob | Schedules job in Kubernetes |
Replica sets | It controls the numbers of Pod replicas running |
Namespaces | They are defined as logical differentiation between teams and their respective environments. It allows various teams, such as Development, Product, to share the Kubernetes cluster by giving separate workspace. |
Deployment | Desired state of pods |
Kubelet | These are container agents that are responsible for keeping the set of pods |
Proxy | Load balancer for pods that helps in allocating tasks across them |
Etcd | It is metadata service |
CAdvisor | It is used to monitor the usage of resources and their performance |
Replication Controller | It manages the replication of pod |
Scheduler | It is used to schedule pod in worker nodes |
API Server | API server of Kubernetes |
Moving forward, let’s go through the roles that master and worker nodes play in the Kubernetes architecture.
Master Node:
- It is responsible for retaining the wanted state of the cluster on which we are working.
- The term “master” specifies a group of procedures that are used to manage a cluster.
- It also contains Kubelet service info, API, replication controller, scheduler, and Kubernetes master.
Worker Node:
The worker node is also called a ‘minion.’ It contains the necessary services to run the pods that are managed by the master.
- It provides services like Container Runtime, Kubelet, Kube-proxy, etc.
- It also contains Kubelet, Services, CAdvisor, Pods, and Containers.
Installation
Installing kubectl
You need to download a pre-compiled release and unzip the content. kubectl must be located in the following directory: platforms/<os>/<arch>
https://github.com/kubernetes/kubernetes/releases
Next, Add kubectl to your path. Copy it into a directory already present in your $PATH (e.g. /usr/local/bin). For example:
# Linux $ sudo cp kubernetes/platforms/linux/amd64/kubectl /usr/local/bin/kubectl # OS X $ sudo cp kubernetes/platforms/darwin/amd64/kubectl /usr/local/bin/kubectl |
And make sure it’s executable:
$ sudo chmod +x /usr/local/bin/kubectl |
Kubectl Commands
Pods and Container Introspection
Command | Function |
Kubectl get pods | Lists down all current pods |
Kubectl describe pod<name> | Describes the names of a pod |
Kubectl get rc | Enlists all replication controllers |
Kubectl gets rc –namespace=”namespace.” | Enlists replication controllers in a namespace |
Kubectl describe rc <name> | Displays the replication controller name |
Kubectl get cvc | Lists down services |
Kubectl describe svc<name> | Displays a service name |
Kubectl delete pod<name> | Deletes a pod |
Kubectl get nodes -w | Lookouts nodes continuously |
Read more: Top 25 Useful Kubernets Tools
For Debugging
Function | Command |
For executing the command on a service by selecting a container | Kubectl exec<service><commands>[-c< $container>] |
Getting logs from the service | Kubectl logs -f<name>>[-c< $container>] |
To look kubelet logs | Watch -n two cat/var/log/kublet.log |
For showing metrics for a node | Kubectl top node |
To display metrics for a pod | Kubectl top pod |
For Cluster Introspection
Function | Command |
Version related information | Kubectl version |
Cluster related information | Kubectl cluster-info |
Configuration details | Kubectl config g view |
Information about a node | Kubectl describe node<node> |
Objects – Kubernetes Cheat sheet
Let’s look into some of the familiar objects used in Kubernetes:
All | clusterrolebindings | clusterroles |
cm= conf gmaps | controllerrevisions | crd=custom resource definition |
Cronjobs | cs=component statuses | csr= certificate signing requests |
Deploy=deployments | ds= daemon sets | ep=end points |
ev= events | hpa= horizontal pod autoscaling | ing= ingress |
jobs | limits=limit ranges | Netpol- network policies |
No = nodes | ns= namespaces | pdb= pod distribution budgets |
po= pods | Pod preset | Pod templates |
Psp= pod security policies | Pv= persistent volumes | pvc= persistent volume claims |
quota= resource quotas | rc= replication controllers | Role bindings |
roles | rs= replica sets | sa= service accounts |
sc= storage classes | secrets | sts= stateful sets |
Other Quick Commands in Kubernetes Cheat sheet
Some of the other handy quick commands are as under:
Function | Command |
Launching a pod with a name and image | Kubectl run<name> — image=<image-name> |
To generate a service described in <manifest.yaml> | Kubectl create -f <manifest.yaml> |
Scaling the replication counter to enumerate the number of instances | Kubectl scale –replicas=<count>rc<name> |
Mapping out the external port to the internal replication port | Expose rc<name> –port=<external>–target-port=<internal> |
Stop all pods in <n> | Kubectl drain<n>– delete-local-data–force–ignore-daemonset |
Produce a namespace | Kubectl create namespace <namespace> |
Allowing the master node to run pods | Kubectltaintnodes –all-node-role.kuernetes.io/master- |
Administration
To administer and interact with any given Kubernetes cluster, whether local or remote, you need to set up a kubeconfig file. By default settings, kubectl configuration file lives at ~/.kube/config
Moreover, a cluster can also be created in a local machine via Minikube (which will be discussed in detail later).
current-context: federal-contextapiVersion: v1clusters:– cluster: api-version: v1 server: http://cow.org:8080 name: cow-cluster– cluster: certificate-authority: path/to/my/cafile server: https://horse.org:4443 name: horse-clustercontexts:– context: cluster: horse-cluster namespace: chisel-ns user: green-user name: federal-contextkind: Configpreferences: colors: trueusers:– name: green-user user: client-certificate: path/to/my/client/cert client-key: path/to/my/client/key |
A Little More Than Kubernetes
The functionality of Kubernetes is to operate at the application level instead of the hardware level. As discussed earlier, it offers some general features common to PaaS offerings. These include deployment, load balancing, scaling, logging, monitoring, and more. However, Kubernetes does not work as an all-inclusive Platform as a Service (PaaS). As a developer, you will need to consider any needs for DevOps functionality separately:
- Networking
- Metrics and logging
- Image registry
- Complex deployments
- Management of application lifecycle
- Application services; database and messaging
- Self-service portal
- Container security
Running Locally Through Minikube
For a smooth and easier functionality of Kubernetes locally, Minikube is a tool that is mostly used. It operates through running a single-node Kubernetes cluster on a virtual machine on your personal computer. This tool is useful for users who are looking to have hands-on Kubernetes experience or develop with it on a smaller scale.
Prerequisites
The Minikube requirement is to have VT-x/AMD-v virtualization enabled in BIOS on all platforms.
Example:
# Linux$ cat /proc/cpuinfo | grep ‘vmx\|svm’# OS X$ sysctl -a | grep machdep.cpu.features | grep VMX |
Make sure whether the setting is enabled or not where you are looking for this command to output something.
Install an x86 virtualization software package in your local machine:
- Linux: The latest VirtualBox
- OS X: The latest VirtualBox or VMware Fusion
Install Minikube
You can leave the sudo mv minikube /usr/local/bin if you opt to add minikube manually.
# Linux/curl -Lo minikube https://storage.googleapis.com/minikube/releases/v0.12.2/minikubelinux-amd64 && chmod +x minikube && sudo mv minikube /usr/local/bin/ # OS Xcurl -Lo minikube https://storage.googleapis.com/minikube/releases/v0.12.2/minikubedarwin-amd64 && chmod +x minikube && sudo mv minikube /usr/local/bin/ |
Install Kubectl
To run commands against the cluster, you must download and install the kubectl client binary to do so.
Example:
# Linux/amd64curl -Lo kubectl http://storage.googleapis.com/kubernetes-release/release/v1.3.0/bin/linux/amd64/kubectl && chmod +x kubectl && sudo mv kubectl /usr/local/bin/ # OS X/amd64curl -Lo kubectl http://storage.googleapis.com/kubernetes-release/release/v1.3.0/bin/darwin/amd64/kubectl && chmod +x kubectl && sudo mv kubectl /usr/local/bin/ |
Kubernetes Cheat sheet – Kubectl CLI
kubectl [command] [TYPE] [NAME] [flags] |
Command: It lay down the desired operation to perform on one or more resources, like create, get, delete.
Type: It makes the resource type specified. Moreover, resource types are strictly case-sensitive. Besides, singular, plural, or abbreviated forms can be specified.
Name: It describes the name of the resource. Moreover, names are also case-sensitive. Details for all resources are displayed if the name is not there.
Kubectl Operations
All the below mentioned examples include the general syntax and description of kubectl operations:
Creating Objects
Example my-rc.yaml file for creating an object-based Replication Controller apiVersion: v1kind: ReplicationControllermetadata: name: nginxspec: replicas: 3 selector: app: nginx template: metadata: name: nginx labels: app: nginx spec: containers: – name: nginx image: nginx ports: – containerPort: 80 # create resource(s)$ kubectl create -f my-rc.yamlreplicationcontroller “nginx” created # create resource(s) from url$ kubectl create -f https://git.io/vPieopod “busybox0” created # start a single instance of nginx$ kubectl run nginx –image=nginxdeployment “nginx” created |
Start your 30-day FREE TRIAL with DevOpsU.org and begin your certification journey now!
The viewing, Finding Resources
Get commands with the necessary output$ kubectl get pod | ||||
Name | Ready | Status | Restarts | Age |
busybox-sleep | 1/1 | Running | 0 | 8 m |
busybox-sleep-less | 1/1 | Running | 0 | 8 m |
busybox0 | 1/1 | Running | 0 | 3 m |
hello-minikube-3015430129-vfgei | 1/1 | Running | 0 | 20 m |
nginx-701339712-tkuma | 1/1 | Running | 0 | 3 m |
Getting commands with YAML or JSON file format $ kubectl get pod/nginx-cmpmt -o yamlapiVersion: v1kind: Podmetadata: annotations:kubernetes.io/created-by: |{“kind”:”SerializedReference”,”apiVersion”:”v1”,”reference”:{“kind”:”ReplicationController”,”namespace”:”default”,”name”:”nginx”,”uid”:”01e01208-bb6a-11e6-a905-7eca61497d69”,”apiVersion”:”v1”,”resourceVersion”:”58757”}} creationTimestamp: 2016-12-06T04:11:05Z generateName: nginx- labels:app: nginx name: nginx-cmpmt namespace: default ownerReferences: – apiVersion: v1controller: truekind: ReplicationControllername: nginxuid: 01e01208-bb6a-11e6-a905-7eca61497d69 resourceVersion: “58815” selfLink: /api/v1/namespaces/default/pods/nginx-cmpmt uid: 01e10582-bb6a-11e6-a905-7eca61497d69spec:containers: – image: nginximagePullPolicy: Alwaysname: nginxports:- containerPort: 80 protocol: TCPresources: {}terminationMessagePath: /dev/termination-logvolumeMounts:- mountPath: /var/run/secrets/kubernetes.io/serviceaccount name: default-token-xxufg readOnly: true dnsPolicy: ClusterFirst nodeName: minikube restartPolicy: Always securityContext: {} serviceAccount: default serviceAccountName: default terminationGracePeriodSeconds: 30 volumes: – name: default-token-xxufgsecret: secretName: default-token-xxufgstatus: conditions: – lastProbeTime: nulllastTransitionTime: 2016-12-06T04:11:05Zstatus: “True”type: Initialized – lastProbeTime: nulllastTransitionTime: 2016-12-06T04:11:23Zstatus: “True”type: Ready – lastProbeTime: nulllastTransitionTime: 2016-12-06T04:11:05Zstatus: “True”type: PodScheduledcontainerStatuses: – containerID:docker://46cdf4314702cc368cf76b46d690134bc78e0de313eb324409fefe088753ed78image: nginximageID: docker://sha256:abf312888d132e461c61484457ee9fd0125d666672e22f972f3b8c9a0ed3f0a1lastState: {}name: nginxready: truerestartCount: 0state: running: startedAt: 2016-12-06T04:11:23Z hostIP: 192.168.99.100 phase: Running podIP: 172.17.0.13 startTime: 2016-12-06T04:11:05Z |
Describing commands with verbose output $ kubectl describe pods busybox-sleepName: busybox-sleepNamespace: defaultNode: minikube/192.168.99.100Start Time: Tue, 11 Aug 2022 23:11:35 +0900Labels: <none>Status: RunningIP: 172.17.0.5Controllers: <none>Containers: busybox:Container ID:docker://4f599b509de0e8504b151e2dfeb98c14082ee149ec8da9132824e38095a6b86fImage: busyboxImage ID: docker://sha256:e02e811dd08fd49e7f6032625495118e63f597eb150403d02e3238af1df240baPort:Args: sleep 1000000State: Running Started: Tue, 11 Aug 2022 23:11:43 +0900Ready: TrueRestart Count: 0Environment Variables: <none>Conditions: Type Status Initialized True Ready True PodScheduled TrueVolumes: default-token-xxufg:Type: Secret (a volume populated by a Secret)SecretName: default-token-xxufgQoS Tier: BestEffort List Services Sorted by Name $ kubectl get services –sort-by=.metadata.name NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGEhello-minikube 10.0.0.38 <nodes> 8080/TCP 51mkubernetes 10.0.0.1 <none> 443/TCP 53m Get ExternalIPs of all nodes $ kubectl get nodes –o jsonpath=’{.items[*].status.addresses[?(@.type==”ExternalIP”)].address}’ |
The viewing, Finding Resources
Add a Label $ kubectl label pods busybox-sleep new-label=new-busybox-sleep pod “busybox-sleep” labeled Add an annotation$ kubectl annotate pods busybox-sleep icon-url=http://goo.gl/XXBTWq pod “busybox-sleep” annotated Autoscale a deployment “nginx.” $ kubectl autoscale deployment nginx –min=2 –max=5 deployment “nginx” autoscaled Rolling update pods of frontend-v1 $ kubectl rolling-update frontend-v1 -f frontend-v2.json Force replace, delete, and re-create the resource. It will cause a service outage $ kubectl replace –force -f ./pod.json # Create a service for replicated nginx. It serves on port 80 and connects to the containers on port 8000 $ kubectl expose rc nginx –port=80 –target-port=8000 |
Patching Resources
Update a node Partially $ kubectl patch node k8s-node-1 -p ‘{“spec”:{“unschedulable”:true}}’ “k8s-node-1” patched # Update a container’s image; spec.containers[*].name is required because it’s a merge key $ kubectl patch pod valid-pod -p ‘{“spec”:{“containers”:[{“name”:”Kubernetes-serve-hostname,””image”:”new image”}]}}’“k8s-node-1” patched |
Editing Resources
Edit the service “docker-registry.” $ kubectl edit svc/docker-registryservice “docker-registry” edited |
Scaling Resources
Scale a replicaset named nginx-701339712 to 5 $ kubectl scale –replicas=5 rs/nginx-701339712replicaset “nginx-701339712” scaled Scale multiple replication controllers $ kubectl scale –replicas=5 rc/foo rc/bar rc/baz |
Deleting Resources
Deleting a pod using the type and specific name $ kubectl delete pod/nginx-701339712-tkumapod “nginx-701339712-tkuma” deleted Deleting pods and services with the same names “baz” and “foo.” $ kubectl delete pod, service baz foopod “baz” deletedservice “foo” deleted Deleting pods and services with label name=myLabel $ kubectl delete pods,services -l name=myLabel Deleting all pods and services in namespace my-ns $ kubectl -n my-ns delete po,svc –all |
Interacting With Running Pods
Dump pod logs (stdout) $ kubectl logs busybox-sleep Stream pod logs (stdout) $ kubectl logs -f hello-minikube-3015430129-vfgei Running pod as an interactive shell $ kubectl run -i –tty busybox –image=busybox – sh Attach to Running Container $ kubectl attach my-pod –i Forward port to service $ kubectl port-forward my-svc 6000 |
Marking a specific node as un-schedulable $ kubectl cordon minikubenode “minikube” cordoned Mark a specific as schedulable $ kubectl uncordon minikubenode “minikube” uncordoned Displaying addresses of the master and services $ kubectl cluster-infoKubernetes master is running at https://192.168.99.100:8443KubeDNS is running at https://192.168.99.100:8443/api/v1/proxy/namespaces/kube-system/services/kube-dnskubernetes-dashboard is running at https://192.168.99.100:8443/api/v1/proxy/namespaces/kube-system/services/kubernetes-dashboard Dump current cluster state to stdout $ kubectl cluster-info dump Dump current cluster state to /path/to/cluster-state $ kubectl cluster-info dump –output-directory=/path/to/cluster-state |
Kubernetes Cheat sheet – Kubernetes Commands
Get Commands
kubectl get allkubectl get namespaceskubectl get configmapskubectl get nodeskubectl get podskubectl get rskubectl get svc kuardkubectl get endpoints kuard |
Some additional switches that can be also be added to the above commands:
- -o wide : Show more information
- –watch or -w : watch for changes
Labels
To get pods showing labels
kubectl get pods –show-labels |
To get pods by label
kubectl get pods -l environment=production,tier!=frontendkubectl get pods -l ‘environment in (production,test),tier notin (frontend,backend)’ |
Describe Command
kubectl describe nodes [id]kubectl describe pods [id]kubectl describe rs [id]kubectl describe svc kuard [id]kubectl describe endpoints kuard [id] |
Delete Command
kubectl delete nodes [id]kubectl delete pods [id]kubectl delete rs [id]kubectl delete svc kuard [id]kubectl delete endpoints kuard [id] |
Create Pod
kubectl run kuard –generator=run-pod/v1 –image=gcr.io/kuar-demo/kuard-amd64:1 –output yaml –export –dry-run > kuard-pod.ymlkubectl apply -f kuard-pod.yml |
Pod Example
apiVersion: v1kind: Podmetadata: name: cuda-testspec: containers: – name: cuda-test image: “k8s.gcr.io/cuda-vector-add:v0.1” resources: limits: nvidia.com/gpu: 1 nodeSelector: accelerator: nvidia-tesla-p100 |
Create Deployment
kubectl run kuard –image=gcr.io/kuar-demo/kuard-amd64:1 –output yaml –export –dry-run > kuard-deployment.ymlkubectl apply -f kuard-deployment.yml |
Deployment Example
apiVersion: apps/v1kind: Deploymentmetadata: name: nginx-deployment namespace: my-namespace labels: – environment: production, – teir: frontend annotations: – key1: value1, – key2: value2spec: replicas: 3 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: – name: nginx image: nginx:1.7.9 ports: – containerPort: 80 |
Create Service
kubectl expose deployment kuard –port 8080 –target-port=8080 –output yaml –export –dry-run > kuard-service.ymlkubectl apply -f kuard-service.yml |
Rollout
Rollout Status
kubectl rollout status deployment/nginx-deploymentWaiting for rollout to finish: 2 out of 3 new replicas have been updated.deployment “nginx-deployment” successfully rolled out |
To get rollout history
kubectl rollout history deployment/nginx-deploymentkubectl rollout history deployment/nginx-deployment –revision=2 |
To undo a rollout
kubectl rollout undo deployment/nginx-deploymentkubectl rollout undo deployment/nginx-deployment –to-revision=2 |
Resume or Pause a rollout
kubectl rollout pause deployment/nginx-deploymentkubectl rollout resume deploy/nginx-deployment |
Kubernetes Cheat sheet – Some Useful Features of Kubernetes
Among the many vital features described earlier, some of the more useful features of Kubernetes are as under:
- Automated scheduling
- Self-healing
- Automated rollouts and rollbacks
- Horizontal scaling
- Service discovery and load balancing