Kubernetes CheatSheet
Kubernetes CheatSheet
COM
+91-9739110917 ADAM
Software Deployments
Software deployment includes all the process required for preparing a software application to run
and operate in a specific environment.
It involves installation, configuration, testing and making changes to optimize the performance of
the software.
Types of Deployments?
✓ Recreate: Version A is terminated then version B is rolled out.
✓ Ramped (also known as rolling-update or incremental): Version B is slowly rolled out and
replacing version A.
✓ Blue/Green: Version B is released alongside version A, then the traffic is switched to
version B.
✓ Canary: Version B is released to a subset of users, then proceed to a full rollout.
www.wezva.com ADAM: +919739110917
www.facebook.com/wezva https://www.linkedin.com/in/wezva
www.wezva.com ADAM: +919739110917
Features of Kubernetes
Following are some of the important features of Kubernetes:
o Continuous development, integration and deployment
o Containerized infrastructure
o Application-centric management
o Auto-scalable infrastructure
o Environment consistency across development testing and production
o Loosely coupled infrastructure, where each component can act as a separate unit
o Higher density of resource utilization
Kubernetes Architecture
www.facebook.com/wezva https://www.linkedin.com/in/wezva
www.wezva.com ADAM: +919739110917
✓ Install kubectl
$ curl -LO https://storage.googleapis.com/kubernetes-release/release/$(curl -s
https://storage.googleapis.com/kubernetes-
release/release/stable.txt)/bin/linux/amd64/kubectl && chmod +x ./kubectl && sudo mv
./kubectl /usr/local/bin/kubectl
✓ Install Minikube
$ curl -Lo minikube https://storage.googleapis.com/minikube/releases/latest/minikube-linux-
amd64 && chmod +x minikube && sudo mv minikube /usr/local/bin/
o Start Minikube
$ minikube start --vm-driver=none
$ minikube status
www.facebook.com/wezva https://www.linkedin.com/in/wezva
www.wezva.com ADAM: +919739110917
Kubectl Usage
$ kubectl [COMMAND] [TYPE] [NAME] [flags]
COMMAND: Specifies the operation that you want to perform on one or more resources, for
example create, apply, get, describe, delete, exec …
TYPE: Specifies the resource type i.e nodes, pods, services, rc, rs …
NAME: Specifies the name of the resource
flags: Optional arguments
$ kubectl version
$ kubectl get node
$ kubectl describe nodes <nodename>
Kubernetes Objects
• Kubernetes uses Objects to represent the state of your cluster
o What containerized applications are running (and on which nodes)
o The resources available to those applications
o The policies around how those applications behave, such as restart policies,
upgrades, and fault-tolerance
• Once you create the object, the Kubernetes system will constantly work to ensure that
object exists and maintain cluster’s desired state
• Every Kubernetes object includes two nested fields that govern the object’s configuration:
the object spec and the object status
• The spec, which we provide, describes your desired state for the object–the characteristics
that you want the object to have.
• The status describes the actual state of the object, and is supplied and updated by the
Kubernetes system.
• All objects in the kubernetes are identified by a Unique Name and a UID.
The basic Kubernetes objects include:
❑ Pod
❑ Service
❑ Volume
❑ Namespace
www.facebook.com/wezva https://www.linkedin.com/in/wezva
www.wezva.com ADAM: +919739110917
• Declarative is about describing what you're trying to achieve, without instructing how to do
it
• Imperative explicitly tells "how" to accomplish it
YAML Basics
o Kubernetes uses YAML syntax for expressing object configuration playbooks
o Nearly every YAML file starts with a list
o Each item in the list is a list of key/value pairs, commonly called a "hash" or a "dictionary"
o All YAML files can optionally begin with "---" and end with "...”
o All members of a list are lines beginning at the same indentation level starting
with a "- "
--- # A list of tasty fruits
fruits:
- Apple
- Orange
- Strawberry
www.facebook.com/wezva https://www.linkedin.com/in/wezva
www.wezva.com ADAM: +919739110917
- Mango
o A dictionary is represented in a simple key: value form (the colon must be
followed by a space)
--- # An employee record
Employee:
name: ADAM
job: DevOps Engineer
skill: Elite
Pods
A Pod is the smallest and simplest unit in the Kubernetes object model that
you create or deploy.
▪ A Pod represents a running process on your cluster.
▪ A Pod encapsulates an application container, storage resources, a unique network IP, and
options that govern how the container(s) should run
▪ Kubernetes manages the Pods rather than the containers directly.
▪ Pods in a Kubernetes cluster can be used in two main ways:
▪ Pods that run a single container - common usecase
▪ Pods that run multiple containers that need to work together
▪ Each Pod is assigned a unique IP address.
▪ Every container in a Pod shares the IP address and network ports.
▪ Containers inside a Pod can communicate with one another using localhost.
▪ All containers in the Pod can access the shared volumes, allowing those containers to share
data.
▪ Kubernetes scales pods and not containers.
Understanding Pods
▪ When a Pod gets created, it is scheduled to run on a Node in your cluster.
▪ The Pod remains on that Node until the process is terminated, the pod object is deleted,
the pod is evicted for lack of resources, or the Node fails.
▪ If a Pod is scheduled to a Node that fails, or if the scheduling operation itself fails, the Pod
is deleted
▪ If a node dies, the pods scheduled to that node are scheduled for deletion, after a timeout
period.
www.facebook.com/wezva https://www.linkedin.com/in/wezva
www.wezva.com ADAM: +919739110917
▪ A given pod (UID) is not “rescheduled” to a new node; instead, it will be replaced by an
identical pod, with even the same name if desired, but with a new UID
▪ Volumes in a pod will exists as long as that pod (with that UID) exists. If that pod is deleted
for any reason, volume is also destroyed and created as new on new pod
▪ Kubernetes uses a Controller, that handles the work of managing the Pod instances.
▪ A Controller can create and manage multiple Pods, handling replication, rollout and
providing self-healing capabilities
YML template for POD
▪ Always means that the container will be restarted even if it exited with a zero exit code
▪ OnFailure means that the container will only be restarted if it exited with a non-zero exit
code
▪ Never means that the container will not be restarted regardless of why it exited.
Syntax:
kind: Pod # Object Type
apiVersion: v1 # API version
metadata: # Set of data which describes the Object
name: <Pod Name> # Name of the Object
spec: # Data which describes the state of the Object
containers: # Data which describes the Container details
- name: <ContainerName1> # Name of the Container1
image: <ImageName1> # Base Image which is used to create Container1
command: [<Comma separated first cmd>]
- name: <ContainerName2> # Name of the Container2
image: <ImageName2> # Base Image which is used to create Container2
command: [<Comma separated first cmd>]
restartPolicy: Never # Defaults to Always
www.facebook.com/wezva https://www.linkedin.com/in/wezva
www.wezva.com ADAM: +919739110917
o Delete a Pod
$ kubectl delete pods <podname> (or)
$ kubectl delete -f <YAML>
www.facebook.com/wezva https://www.linkedin.com/in/wezva
www.wezva.com ADAM: +919739110917
www.facebook.com/wezva https://www.linkedin.com/in/wezva
www.wezva.com ADAM: +919739110917
www.facebook.com/wezva https://www.linkedin.com/in/wezva
www.wezva.com ADAM: +919739110917
Label Selectors:
• Unlike name/UIDs, Labels do not provide uniqueness, as in general, we can expect many
objects to carry the same label
• Once labels are attached to an object, we would need filters to narrow down and these are
called as Label Selectors
• The API currently supports two types of selectors: equality-based and set-based
• A label selector can be made of multiple requirements which are comma-separated
Equality-based requirement: ( = , != )
environment = production
tier != frontend
Set-based requirement: (in,notin and exists)
environment in (production, qa)
tier notin (frontend, backend)
Node Selectors:
• One use case for selecting labels is to constrain the set of nodes onto which a pod can
schedule i.e You can tell a pod to only be able to run on particular nodes
• Generally such constraints are unnecessary, as the scheduler will automatically do a
reasonable placement, but on certain circumstances we might need it
• We can use labels to tag Nodes
• You the nodes are tagged, you can use the Label Selectors to specify the pods run only of
specific nodes
www.facebook.com/wezva https://www.linkedin.com/in/wezva
www.wezva.com ADAM: +919739110917
www.facebook.com/wezva https://www.linkedin.com/in/wezva
www.wezva.com ADAM: +919739110917
- name: c00
image: ubuntu
command: ["/bin/bash", "-c", "while true; do echo Hello-Adam; sleep 5 ; done"]
Replication Set
• ReplicaSet is the next generation Replication Controller
• The replication controller only supports equality-based selector whereas the replica set
supports set-based selector i.e filtering according to set of values
• ReplicaSet rather than the Replication Controller is used by other objects like Deployment
Syntax:
kind: ReplicaSet # Defines the object to be ReplicaSet
apiVersion: apps/v1 # Replicaset is not available on v1
metadata:
name: <RS Name>
spec:
replicas: 2 # this element defines the desired number of pods
www.facebook.com/wezva https://www.linkedin.com/in/wezva
www.wezva.com ADAM: +919739110917
selector: # tells the controller which pods to watch/belong to this Replication Set
matchExpressions: # these must match the labels
- {key: keyname, operator: In, values: [value1, value2, value3]}
- {key: keyname, operator: NotIn, values: [value1]}
template: # template element defines a template to launch a new pod
metadata:
name: <podname>
labels: # selector values need to match the labels values specified in the pod template
<keyname>: <value>
spec:
containers:
- name: c00
image: ubuntu
command: ["/bin/bash", "-c", "while true; do echo Hello-Adam; sleep 5 ; done"]
o Apply Replicationcontroller:
$ kubectl apply -f rs.yml
$ kubectl get rs
$ kubectl describe rs <replicasetname>
o Scale Replicas:
$ kubectl scale --replicas=1 rs/<replicasetname> (OR)
$ kubectl scale --replicas=2 rs -l keyname=value
o Delete ReplicaSet:
$ kubectl delete rs <replicasetname>
www.facebook.com/wezva https://www.linkedin.com/in/wezva
www.wezva.com ADAM: +919739110917
Deployments
• Just using RC & RS might be cumbersome to deploy apps, update or rollback apps in the
cluster
• A Deployment object acts as a supervisor for pods, giving you fine-grained control over how
and when a new pod is rolled out, updated or rolled back to a previous state
• When using Deployment object, we first define the state of the App, then k8s master
schedules mentioned app instance onto specific individual Nodes
• K8s then monitors, if the Node hosting an instance goes down or pod is deleted, the
Deployment controller replaces it.
• This provides a self-healing mechanism to address machine failure or maintenance.
www.facebook.com/wezva https://www.linkedin.com/in/wezva
www.wezva.com ADAM: +919739110917
Syntax:
kind: Deployment
apiVersion: extensions/v1beta1
metadata:
name: <DeploymentName>
spec:
replicas: <Number of Containers>
template:
metadata:
name: <PodName>
labels:
<Keyname>: <Value>
spec:
containers:
- name: c00
image: ubuntu
command: ["/bin/bash", "-c", "while true; do echo Hello-Adam; sleep 5 ; done"]
o Creating a Deployment
$ kubectl apply -f pod8.xml
$ kubectl get deploy
$ kubectl describe deploy/<deploymentname>
$ kubectl get rs
$ kubectl get pods
o Updating a Deployment (Change the echo cmd & save the yml content as new file & apply)
$ kubectl apply –f <yml>
$ kubectl get pods
✓ We will see the rollout of two new pods with the updated cmd, as well as old pods being
terminated
www.facebook.com/wezva https://www.linkedin.com/in/wezva
www.wezva.com ADAM: +919739110917
www.facebook.com/wezva https://www.linkedin.com/in/wezva
www.wezva.com ADAM: +919739110917
Services
• When using RC, pods are terminated and created during scaling or replication operations
• When using Deployments, while updating the image version the pods are terminated & new
pods take the place of older pods.
• Pods are very dynamic i.e they come & go on the k8s cluster and on any of the available
nodes & it would be difficult to access the pods as the pods IP changes once its recreated
• Service Object is an logical bridge between pods & endusers, which provides Virtual IP (VIP)
address.
• Service allows clients to reliably connect to the containers running in the pod using the
VIP.
• The VIP is not an actual IP connected to a network interface, but its purpose is purely to
forward traffic to one or more pods.
• kube-proxy is the one which Keeps the mapping between the VIP and the pods up-to-date,
which queries the API server to learn about new services in the cluster.
• Although each Pod has a unique IP address, those IPs are not exposed outside the cluster.
• Services helps to expose the VIP mapped to the pods & allows applications to receive traffic
• Labels are used to select which are the Pods to be put under a Service.
• Creating a Service will create an endpoint to access the pods/Application in it.
• Services can be exposed in different ways by specifying a type in the Service Spec:
o ClusterIP (default) - Exposes VIP only reachable from within the cluster.
o NodePort - Exposes the Service on the same port of each selected Node in the cluster
using NAT. Makes a Service accessible from outside the cluster using
<NodeIP>:<NodePort>.
o LoadBalancer - Created by cloud providers that will route external traffic to every
node on the NodePort (ex: ELB on AWS).
• By default service can run only between ports 30000-32767
www.facebook.com/wezva https://www.linkedin.com/in/wezva
www.wezva.com ADAM: +919739110917
www.facebook.com/wezva https://www.linkedin.com/in/wezva
www.wezva.com ADAM: +919739110917
HealthChecks
o A Pod is considered ready when all of its Containers are ready.
o In order to verify if a container in a pod is healthy and ready to serve traffic, Kubernetes
provides for a range of health checking mechanisms
o Health checks, or probes are carried out by the kubelet to determine when to restart a
container (for livenessProbe) and used by services and deployments to determine if a pod
should receive traffic (for readinessProbe).
o For example, liveness probes could catch a deadlock, where an application is running, but
unable to make progress. Restarting a Container in such a state can help to make the
application more available despite bugs.
o One use of readiness probes is to control which Pods are used as backends for Services.
When a Pod is not ready, it is removed from Service load balancers.
o For running healthchecks we would use cmds specific to the application.
o If the command succeeds, it returns 0, and the kubelet considers the Container to be alive
and healthy. If the command returns a non-zero value, the kubelet kills the Container and
restarts it.
LivenessProbe with CMD Syntax:
apiVersion: v1
kind: Pod
metadata:
labels:
www.facebook.com/wezva https://www.linkedin.com/in/wezva
www.wezva.com ADAM: +919739110917
<Key>: <Value>
name: <Livenessname>
spec:
containers:
- name: <ContainerName>
image: <ImageName>
livenessProbe: # define the health check
exec:
command: # command to run periodically
- <OS Cmd>
initialDelaySeconds: <Seconds> # Wait for the specified time before it runs the first probe
periodSeconds: <Seconds> # Run the above command every n sec
timeoutSeconds: <Seconds> # Seconds to timeout if the cmd is not responding
www.facebook.com/wezva https://www.linkedin.com/in/wezva
www.wezva.com ADAM: +919739110917
periodSeconds: <Seconds>
httpGet: # HTTP URL to check periodically
path: / # Endpoint to check inside the container / means http://localhost/
port: <Portnumber> # Specific port to check
Readiness check
• While both liveness and readiness check and describe the state of the service, they serve
quite a different purpose.
• Liveness describes if the pod has started and everything inside it is ready to take the load.
If not, then it gets restarted. This does not include any external dependencies like for
example databases, which are clearly something the service doesn't have control over. We
don't get much benefit if we restart the service when the database is down, because it will
not help.
• This is where Readiness checks come in. This is basically a check if the application can
handle the incoming requests.
• It should do a sanity check against both internal and external elements that make the
service go, so the connection to the database should be checked there.
• If the check fails, the service is not being restarted, but the Kubernetes will not direct any
traffic to it. This is particularly useful if we perform a rolling update and the new version
has some issue connecting to the DB. In this case, it stays not ready, but those instances
are not being restarted.
ReadinessProbe With URL Syntax
apiVersion: v1
kind: Pod
metadata:
labels:
<Key>: <Value>
name: <PodName>
spec:
containers:
- name: <ContainerName>
image: <ImageName>
ports:
- containerPort: <port>
www.facebook.com/wezva https://www.linkedin.com/in/wezva
www.wezva.com ADAM: +919739110917
readinessProbe:
initialDelaySeconds: <Seconds>
periodSeconds: <Seconds>
httpGet: # HTTP URL to check periodically
path: / # Endpoint to check inside the container / means http://localhost/
port: <Portnumber> # Specific port to check
Volumes
• Containers are ephemeral (short lived in nature).
• All data stored inside a container is deleted if the container crashes. However,
the kubelet will restart it with a clean state, which means that it will not have any of the
old data
• To overcome this problem, Kubernetes uses Volumes. A Volume is essentially a directory
backed by a storage medium. The storage medium and its content are determined by the
Volume Type.
• In Kubernetes, a Volume is attached to a Pod and shared among the containers of that Pod.
• The Volume has the same life span as the Pod, and it outlives the containers of the Pod -
this allows data to be preserved across container restarts
• A Volume Type decides the properties of the directory, like size, content, etc. Some
examples of Volume Types are:
www.facebook.com/wezva https://www.linkedin.com/in/wezva
www.wezva.com ADAM: +919739110917
- name: <volumename>
mountPath: "<Path>”
volumes: # Definition for host
- name: <volumename>
emptyDir: {}
www.wezva.com +91-9739110917
https://www.facebook.com/wezva
https://www.linkedin.com/in/wezva +91-9886328782
www.facebook.com/wezva https://www.linkedin.com/in/wezva