Kubernetes Tutorial
Kubernetes Tutorial
Audience
This tutorial has been prepared for those who want to understand the containerized
infrastructure and deployment of application on containers. This tutorial will help in
understanding the concepts of container management using Kubernetes.
Prerequisites
We assume anyone who wants to understand Kubernetes should have an understating of
how the Docker works, how the Docker images are created, and how they work as a
standalone unit. To reach to an advanced configuration in Kubernetes one should
understand basic networking and how the protocol communication works.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at [email protected]
i
Kubernetes
Table of Contents
About the Tutorial .......................................................................................................................................... i
Audience ......................................................................................................................................................... i
Prerequisites ................................................................................................................................................... i
Copyright & Disclaimer ................................................................................................................................... i
Table of Contents........................................................................................................................................... ii
ii
Kubernetes
iii
Kubernetes
Basic Kubernetes
1
1. Kubernetes ─ Overview Kubernetes
Features of Kubernetes
Following are some of the important features of Kubernetes.
One of the key components of Kubernetes is, it can run application on clusters of physical
and virtual machine infrastructure. It also has the capability to run applications on cloud.
It helps in moving from host-centric infrastructure to container-centric
infrastructure.
2
2. Kubernetes ─ Architecture Kubernetes
The key components of master and node are defined in the following section.
etcd
It stores the configuration information which can be used by each of the nodes in the
cluster. It is a high availability key value store that can be distributed among multiple
nodes. It is accessible only by Kubernetes API server as it may have some sensitive
information. It is a distributed key value Store which is accessible to all.
API Server
Kubernetes is an API server which provides all the operation on cluster using the API. API
server implements an interface, which means different tools and libraries can readily
3
Kubernetes
communicate with it. Kubeconfig is a package along with the server side tools that can
be used for communication. It exposes Kubernetes API.
Controller Manager
This component is responsible for most of the collectors that regulates the state of cluster
and performs a task. In general, it can be considered as a daemon which runs in non-
terminating loop and is responsible for collecting and sending information to API server. It
works toward getting the shared state of cluster and then make changes to bring the
current status of the server to the desired state. The key controllers are replication
controller, endpoint controller, namespace controller, and service account controller. The
controller manager runs different kind of controllers to handle nodes, endpoints, etc.
Scheduler
This is one of the key components of Kubernetes master. It is a service in master
responsible for distributing the workload. It is responsible for tracking utilization of working
load on cluster nodes and then placing the workload on which resources are available and
accept the workload. In other words, this is the mechanism responsible for allocating pods
to available nodes. The scheduler is responsible for workload utilization and allocating pod
to new node.
Docker
The first requirement of each node is Docker which helps in running the encapsulated
application containers in a relatively isolated but lightweight operating environment.
Kubelet Service
This is a small service in each node responsible for relaying information to and from control
plane service. It interacts with etcd store to read configuration details and wright values.
This communicates with the master component to receive commands and work. The
kubelet process then assumes responsibility for maintaining the state of work and the
node server. It manages network rules, port forwarding, etc.
4
Kubernetes
5
3. Kubernetes ─ Setup Kubernetes
It is important to set up the Virtual Datacenter (vDC) before setting up Kubernetes. This
can be considered as a set of machines where they can communicate with each other via
the network. For hands-on approach, you can set up vDC on PROFITBRICKS if you do
not have a physical or cloud infrastructure set up.
Once the IaaS setup on any cloud is complete, you need to configure the Master and the
Node.
Note: The setup is shown for Ubuntu machines. The same can be set up on other Linux
machines as well.
Prerequisites
Installing Docker: Docker is required on all the instances of Kubernetes. Following are
the steps to install the Docker.
Step 2: Update the package information. Make sure that the apt package is working.
Once all the above tasks are complete, you can start with the actual installation of the
Docker engine. However, before this you need to verify that the kernel version you are
using is correct.
6
Kubernetes
$ curl -L https://github.com/coreos/etcd/releases/download/v2.0.0/etcd
-v2.0.0-linux-amd64.tar.gz -o etcd-v2.0.0-linux-amd64.tar.gz ->1
$ cd etcd-v2.0.0-linux-amd64 ------------>3
$ mkdir /opt/bin ------------->4
$ cp etcd* /opt/bin ----------->5
7
Kubernetes
Now we are ready to build Kubernetes. We need to install Kubernetes on all the machines
on the cluster.
The above command will create a _output dir in the root of the kubernetes folder. Next,
we can extract the directory into any of the directory of our choice /opt/bin, etc.
Next, comes the networking part wherein we need to actually start with the setup of
Kubernetes master and node. In order to do this, we will make an entry in the host file
which can be done on the node machine.
First, we will start copying all the configuration files to their correct location.
The above command will copy all the configuration files to the required location. Now we
will come back to the same directory where we have built the Kubernetes folder.
8
Kubernetes
$ cp kubernetes/cluster/ubuntu/init_conf/kube-apiserver.conf /etc/init/
$ cp kubernetes/cluster/ubuntu/init_conf/kube-controller-manager.conf
/etc/init/
$ cp kubernetes/cluster/ubuntu/init_conf/kube-kube-scheduler.conf /etc/init/
$ cp kubernetes/cluster/ubuntu/initd_scripts/kube-apiserver /etc/init.d/
$ cp kubernetes/cluster/ubuntu/initd_scripts/kube-controller-manager
/etc/init.d/
$ cp kubernetes/cluster/ubuntu/initd_scripts/kube-kube-scheduler /etc/init.d/
$ cp kubernetes/cluster/ubuntu/default_scripts/kubelet /etc/default/
$ cp kubernetes/cluster/ubuntu/default_scripts/kube-proxy /etc/default/
$ cp kubernetes/cluster/ubuntu/default_scripts/kubelet /etc/default/
The next step is to update the copied configuration file under /etc. dir.
$ ETCD_OPTS="-listen-client-urls=http://kube-master:4001"
Configure kube-apiserver
For this on the master, we need to edit the /etc/default/kube-apiserver file which we
copied earlier.
$ KUBE_APISERVER_OPTS="--address=0.0.0.0 \
--port=8080 \
--etcd_servers=<The path that is configured in ETCD_OPTS> \
--portal_net=11.1.1.0/24 \
--allow_privileged=false \
--kubelet_port= < Port you want to configure> \
--v=0"
$ KUBE_CONTROLLER_MANAGER_OPTS="--address=0.0.0.0 \
--master=127.0.0.1:8080 \
--machines=kube-minion \ -----> #this is the kubernatics node
9
Kubernetes
--v=0
$ KUBE_SCHEDULER_OPTS="--address=0.0.0.0 \
--master=127.0.0.1:8080 \
--v=0"
Once all the above tasks are complete, we are good to go ahead by bring up the
Kubernetes Master. In order to do this, we will restart the Docker.
Use the same method of copying the files that we did for kubernetes master. As it will only
run the kubelet and the kube-proxy, we will configure them.
$ cp kubernetes/cluster/ubuntu/init_conf/kubelet.conf /etc/init/
$ cp kubernetes/cluster/ubuntu/init_conf/kube-proxy.conf /etc/init/
$ cp kubernetes/cluster/ubuntu/initd_scripts/kubelet /etc/init.d/
$ cp kubernetes/cluster/ubuntu/initd_scripts/kube-proxy /etc/init.d/
$ cp kubernetes/cluster/ubuntu/default_scripts/kubelet /etc/default/
$ cp kubernetes/cluster/ubuntu/default_scripts/kube-proxy /etc/default/
10
Kubernetes
$ KUBELET_OPTS="--address=0.0.0.0 \
--port=10250 \
--hostname_override=kube-minion \
--etcd_servers=http://kube-master:4001 \
--enable_server=true
--v=0"
/
$ KUBE_PROXY_OPTS="--etcd_servers=http://kube-master:4001 \
--v=0"
/etc/init/kube-proxy.conf
Now we are done with the configuration. You can check by running the following
commands.
11
4. Kubernetes ─ Images Kubernetes
Kubernetes (Docker) images are the key building blocks of Containerized Infrastructure.
As of now, we are only supporting Kubernetes to support Docker images. Each container
in a pod has its Docker image running inside it.
When we are configuring a pod, the image property in the configuration file has the same
syntax as the Docker command does. The configuration file has a field to define the image
name, which we are planning to pull from the registry.
Following is the common configuration structure which will pull image from Docker registry
and deploy in to Kubernetes container.
apiVersion: v1
kind: pod
metadata:
name: Tesing_for_Image_pull -----------> 1
spec:
containers:
- name: neo4j-server ------------------------> 2
image: <Name of the Docker image>----------> 3
imagePullPolicy: Always ------------->4
command: ["echo", "SUCCESS"] ------------------->
name: neo4j-server: This is the name given to the container that we are trying
to create. Like we have given neo4j-server.
image: <Name of the Docker image>: This is the name of the image which we
are trying to pull from the Docker or internal registry of images. We need to define
a complete registry path along with the image name that we are trying to pull.
imagePullPolicy: Always: This image pull policy defines that whenever we run
this file to create the container, it will pull the same name again.
command: [“echo”, “SUCCESS”]: With this, when we create the container and
if everything goes fine, it will display a message when we will access the container.
In order to pull the image and create a container, we will run the following command.
12
Kubernetes
The above command will produce an output of success or we will get an output as failure.
13
5. Kubernetes ─ Jobs Kubernetes
The main function of a job is to create one or more pod and tracks about the success of
pods. They ensure that the specified number of pods are completed successfully. When a
specified number of successful run of pods is completed, then the job is considered
complete.
Creating a Job
Use the following command to create a job:
apiVersion: v1
kind: Job ------------------------> 1
metadata:
name: py
spec:
template:
metadata
name: py -------> 2
spec:
containers:
- name: py ------------------------> 3
image: python----------> 4
command: ["python", "SUCCESS"]
restartPocliy: Never --------> 5
kind: Job => We have defined the kind as Job which will tell kubectl that the
yaml file being used is to create a job type pod.
Name:py => This is the name of the template that we are using and the spec
defines the template.
name: py => we have given a name as py under container spec which helps to
identify the Pod which is going to be created out of it.
Image: python => the image which we are going to pull to create the container
which will run inside the pod.
restartPolicy: Never => This condition of image restart is given as never which
means that if the container is killed or if it is false, then it will not restart itself.
14
Kubernetes
We will create the job using the following command with yaml which is saved with the
name py.yaml.
The above command will create a job. If you want to check the status of a job, use the
following command.
The above command will give the complete status of the job that is created such as how
many pods completed, how many successes, start time, etc.
Scheduled Job
Scheduled job in Kubernetes uses Cronetes, which takes Kubernetes job and launches
them in Kubernetes cluster.
Note: The feature of a scheduled job is supported by version 1.4 and the betch/v2alpha
1 API is turned on by passing the –runtime-config=batch/v2alpha1 while bringing up
the API server.
We will use the same yaml which we used to create the job and make it a scheduled job.
apiVersion: v1
kind: Job
metadata:
name: py
spec:
schedule: h/30 * * * * ? -------------------> 1
template:
metadata
name: py
spec:
containers:
- name: py
image: python
args:
/bin/sh -------> 2
-c
ps –eaf ------------> 3
15
Kubernetes
restartPocliy: OnFailure
ps –eaf => Will run ps -eaf command on the machine and list all the running
process inside a container.
This scheduled job concept is useful when we are trying to build and run a set of tasks at
a specified point of time and then complete the process.
16
6. Kubernetes ─ Labels & Selectors Kubernetes
Labels
Labels are key-value pairs which are attached to pods, replication controller and services.
They are used as identifying attributes for objects such as pods and replication controller.
They can be added to an object at creation time and can be added or modified at the run
time.
Selectors
Labels do not provide uniqueness. In general, we can say many objects can carry the same
labels. Labels selector are core grouping primitive in Kubernetes. They are used by the
users to select a set of objects.
Equality-based selectors
Set-based selectors
Equality-based Selectors
They allow filtering by key and value. Matching objects should satisfy all the specified
labels.
Set-based Selectors
Set-based selectors allow filtering of keys according to a set of values.
apiVersion: v1
kind: Service
metadata:
name: sp-neo4j-standalone
spec:
ports:
- port: 7474
name: neo4j
type: NodePort
selector:
app: salesplatform ---------> 1
component: neo4j ----------> 2
In the above code, we are using the label selector as app: salesplatform and component
as component: neo4j.
17
Kubernetes
Once we run the file using the kubectl command, it will create a service with the name
sp-neo4j-standalone which will communicate on port 7474. The ype is NodePort with
the new label selector as app: salesplatform and component: neo4j.
18
7. Kubernetes ─ Namespace Kubernetes
Functionality of Namespace
Following are some of the important functionalities of a Namespace in Kubernetes:
Create a Namespace
The following command is used to create a namespace.
apiVersion: v1
kind: Namespce
metadata
name: elk
19
Kubernetes
apiVersion: v1
kind: Service
metadata:
name: elasticsearch
namespace: elk
labels:
component: elasticsearch
spec:
type: LoadBalancer
selector:
component: elasticsearch
ports:
- name: http
port: 9200
protocol: TCP
- name: transport
port: 9300
protocol: TCP
In the above code, we are using the same namespace under service metadata with the
name of elk.
20
8. Kubernetes ─ Nodes Kubernetes
A node is a working machine in Kubernetes cluster which is also known as a minion. They
are working units which can be physical, VM, or a cloud instance.
Each node has all the required configuration required to run a pod on it such as the proxy
service and kubelet service along with the Docker, which is used to run the Docker
containers on the pod created on the node.
They are not created by Kubernetes but they are created externally either by the cloud
service provider or the Kubernetes cluster manager on physical or VM machines.
The key component of Kubernetes to handle multiple nodes is the controller manager,
which runs multiple kind of controllers to manage nodes. To manage nodes, Kubernetes
creates an object of kind node which will validate that the object which is created is a valid
node.
{
Kind: node
apiVersion: v1
"metadata": {
"name": "10.01.1.10",
"labels"
{
"name": "cluster 1 node"
}
}
}
21
Kubernetes
Node Controller
They are the collection of services which run in the Kubernetes master and continuously
monitor the node in the cluster on the basis of metadata.name. If all the required services
are running, then the node is validated and a newly created pod will be assigned to that
node by the controller. If it is not valid, then the master will not assign any pod to it and
will wait until it becomes valid.
–register-node=true
However, if the cluster administrator wants to manage it manually then it could be done
by turning the flat of -
–register-node=false
22
9. Kubernetes ─ Service Kubernetes
The above configuration will create a service with the name Tutorial_point_service.
23
Kubernetes
apiVersion: v1
kind: Endpoints
metadata:
name: Tutorial_point_service
subnets:
address:
"ip": "192.168.168.40" -------------------> (Selector)
ports:
- port: 8080
In the above code, we have created an endpoint which will route the traffic to the endpoint
defined as “192.168.168.40:8080”.
Types of Services
ClusterIP: This helps in restricting the service within the cluster. It exposes the service
within the defined Kubernetes cluster.
24
Kubernetes
spec:
type: NodePort
ports:
- port: 8080
nodePort: 31999
name: NodeportService
NodePort: It will expose the service on a static port on the deployed node. A ClusterIP
service, to which NodePort service will route, is automatically created. The service can
be accessed from outside the cluster using the NodeIP:nodePort.
spec:
ports:
- port: 8080
nodePort: 31999
name: NodeportService
clusterIP: 10.20.30.40
Load Balancer: It uses cloud providers’ load balancer. NodePort and ClusterIP services
are created automatically to which the external load balancer will route.
A full service yaml file with service type as Node Port. Try to create one yourself.
apiVersion: v1
kind: Service
metadata:
name: appname
labels:
k8s-app: appname
spec:
type: NodePort
ports:
- port: 8080
nodePort: 31999
name: omninginx
selector:
k8s-app: appname
component: nginx
env: env_name
25
10. Kubernetes ─ Pod Kubernetes
A pod is a collection of containers and its storage inside a node of a Kubernetes cluster. It
is possible to create a pod with multiple containers inside it. For example, keeping a
database container and data container in the same pod.
Types of Pod
There are two types of Pods:
Example: We will create a pod with a tomcat image which is available on the Docker hub.
This can also be done by creating the yaml file and then running the kubectl create
command.
apiVersion: v1
kind: Pod
metadata:
name: Tomcat
spec:
containers:
- name: Tomcat
image: tomcat: 8.0
ports:
containerPort: 7500
imagePullPolicy: Always
Once the above yaml file is created, we will save the file with the name of tomcat.yml
and run the create command to run the document.
26
Kubernetes
It will create a pod with the name of tomcat. We can use the describe command along
with kubectl to describe the pod.
apiVersion: v1
kind: Pod
metadata:
name: Tomcat
spec:
containers:
- name: Tomcat
image: tomcat: 8.0
ports:
containerPort: 7500
imagePullPolicy: Always
-name: Database
Image: mongoDB
Ports:
containerPort: 7501
imagePullPolicy: Always
In the above code, we have created one pod with two containers inside it, one for tomcat
and the other for MongoDB.
27
11. Kubernetes ─ Replication Controller Kubernetes
Replication Controller is one of the key features of Kubernetes, which is responsible for
managing the pod lifecycle. It is responsible for making sure that the specified number of
pod replicas are running at any point of time. It is used in time when one wants to make
sure that the specified number of pod or at least one pod is running. It has the capability
to bring up or down the specified no of pod.
It is a best practice to use the replication controller to manage the pod life cycle rather
than creating a pod again and again.
apiVersion: v1
kind: ReplicationController --------------------------> 1
metadata:
name: Tomcat-ReplicationController --------------------------> 2
spec:
replicas: 3 ------------------------> 3
template:
metadata:
name: Tomcat-ReplicationController
labels:
app: App
component: neo4j
spec:
containers:
- name: Tomcat- -------------------------> 4
image: tomcat: 8.0
ports:
- containerPort: 7474 ------------------------> 5
Setup Details
Kind: ReplicationController => In the above code, we have defined the kind as
replication controller which tells the kubectl that the yaml file is going to be used
for creating the replication controller.
replicas: 3 => This helps the replication controller to understand that it needs to
maintain three replicas of a pod at any point of time in the pod lifecycle.
28
Kubernetes
name: Tomcat => In the spec section, we have defined the name as tomcat which
will tell the replication controller that the container present inside the pods is
tomcat.
containerPort: 7474 => It helps in making sure that all the nodes in the cluster
where the pod is running the container inside the pod will be exposed on the same
port 7474.
Here, the Kubernetes service is working as a load balancer for three tomcat replicas.
29
12. Kubernetes – Replica Sets Kubernetes
Replica Set ensures how many replica of pod should be running. It can be considered as a
replacement of replication controller. The key difference between the replica set and the
replication controller is, the replication controller only supports equality-based selector
whereas the replica set supports set-based selector.
Setup Details
apiVersion: extensions/v1beta1 => In the above code, the API version is the
advanced beta version of Kubernetes which supports the concept of replica set.
30
Kubernetes
kind: ReplicaSet => We have defined the kind as the replica set which helps
kubectl to understand that the file is used to create a replica set.
tier: Backend => We have defined the label tier as backend which creates a
matching selector.
{key: tier, operation: In, values: [Backend]} => This will help
matchExpression to understand the matching condition we have defined and in
the operation which is used by matchlabel to find details.
Run the above file using kubectl and create the backend replica set with the provided
definition in the yaml file.
31
13. Kubernetes – Deployments Kubernetes
Deployments are upgraded and higher version of replication controller. They manage the
deployment of replica sets which is also an upgraded version of the replication controller.
They have the capability to update the replica set and are also capable of rolling back to
the previous version.
They provide many updated features of matchLabels and selectors. We have got a new
controller in the Kubernetes master called the deployment controller which makes it
happen. It has the capability to change the deployment midway.
Deleting: The user can pause/cancel the deployment by deleting it before it is completed.
Recreating the same deployment will resume it.
Rollback: We can roll back the deployment or the deployment in progress. The user can
create or update the deployment by using DeploymentSpec.PodTemplateSpec =
oldRC.PodTemplateSpec.
Deployment Strategies
Deployment strategies help in defining how the new RC should replace the existing RC.
Recreate: This feature will kill all the existing RC and then bring up the new ones. This
results in quick deployment however it will result in downtime when the old pods are down
and the new pods have not come up.
Rolling Update: This feature gradually brings down the old RC and brings up the new
one. This results in slow deployment, however there is no deployment. At all times, few
old pods and few new pods are available in this process.
32
Kubernetes
tier: Backend
spec:
containers:
- name: Tomcat-
image: tomcat: 8.0
ports:
- containerPort: 7474
In the above code, the only thing which is different from the replica set is we have defined
the kind as deployment.
Create Deployment
$ kubectl create –f Deployment.yaml -–record
33
14. Kubernetes – Volumes Kubernetes
The concept of volume was present with the Docker, however the only issue was that the
volume was very much limited to a particular pod. As soon as the life of a pod ended, the
volume was also lost.
On the other hand, the volumes that are created through Kubernetes is not limited to any
container. It supports any or all the containers deployed inside the pod of Kubernetes. A
key advantage of Kubernetes volume is, it supports different kind of storage wherein the
pod can use multiple of them at the same time.
hostPath ─ This type of volume mounts a file or directory from the host node’s
filesystem into your pod.
nfs ─ An nfs volume allows an existing NFS (Network File System) to be mounted
into your pod. The data in an nfs volume is not erased when the Pod is removed
from the node. The volume is only unmounted.
iscsi ─ An iscsi volume allows an existing iSCSI (SCSI over IP) volume to be
mounted into your pod.
34
Kubernetes
rbd ─ RBD stands for Rados Block Device. An rbd volume allows a Rados Block
Device volume to be mounted into your pod. Data remains preserved after the
Pod is removed from the node.
Persistent Volume Claim (PVC): The storage requested by Kubernetes for its pods is
known as PVC. The user does not need to know the underlying provisioning. The claims
must be created in the same namespace where the pod is created.
35
Kubernetes
- ReadWriteOnce -------------------> 5
hostPath:
path: "/tmp/data01" --------------------------> 6
capacity: => This spec will define the capacity of PV that we are trying to create.
storage: 10Gi => This tells the underlying infrastructure that we are trying to
claim 10Gi space on the defined path.
ReadWriteOnce => This tells the access rights of the volume that we are creating.
path: "/tmp/data01" => This definition tells the machine that we are trying to
create volume under this path on the underlying infrastructure.
Creating PV
$ kubectl create –f local-01.yaml
persistentvolume "pv0001" created
Checking PV
$ kubectl get pv
Describing PV
$ kubectl describe pv pv0001
36
Kubernetes
spec:
accessModes:
- ReadWriteOnce ------------------------> 3
resources:
requests:
storage: 3Gi ---------------------> 4
name: myclaim-1 => Name of the claim that we are trying to create.
ReadWriteOnce => This specifies the mode of the claim that we are trying to
create.
storage: 3Gi => This will tell kubernetes about the amount of space we are trying
to claim.
Creating PVC
$ kubectl create –f myclaim-1
persistentvolumeclaim "myclaim-1" created
Describe PVC
$ kubectl describe pv pv0001
37
Kubernetes
spec:
containers:
- name: myfrontend
image: nginx
ports:
- containerPort: 80
name: "http-server"
volumeMounts: ----------------------------> 1
- mountPath: "/usr/share/tomcat/html"
name: mypd
volumes: -----------------------> 2
- name: mypd
persistentVolumeClaim: ------------------------->3
claimName: myclaim-1
volumeMounts: => This is the path in the container on which the mounting will
take place.
Volume: => This definition defines the volume definition that we are going to
claim.
38
15. Kubernetes ─ Secrets Kubernetes
Secrets can be defined as Kubernetes objects used to store sensitive data such as user
name and passwords with encryption.
39
Kubernetes
Using Secrets
Once we have created the secrets, it can be consumed in a pod or the replication controller
as:
Environment Variable
Volume
As Environment Variable
In order to use the secret as environment variable, we will use env under the spec section
of pod yaml file.
env:
- name: SECRET_USERNAME
valueFrom:
secretKeyRef:
name: mysecret
key: tomcat-pass
As Volume
spec:
volumes:
- name: "secretstest"
secret:
secretName: tomcat-pass
containers:
- image: tomcat:7.0
name: awebserver
volumeMounts:
- mountPath: "/tmp/mysec"
name: "secretstest"
40
Kubernetes
replicas: replica_count
template:
metadata:
name: appname
spec:
nodeSelector:
resource-group:
containers:
- name: appname
image:
imagePullPolicy: Always
ports:
- containerPort: 3000
env: -----------------------------> 1
- name: ENV
valueFrom:
configMapKeyRef:
name: appname
key: tomcat-secrets
In the above code, under the env definition, we are using secrets as environment variable
in the replication controller.
41
Kubernetes
42
16. Kubernetes ─ Network Policy Kubernetes
Network Policy defines how the pods in the same namespace will communicate with each
other and the network endpoint. It requires extensions/v1beta1/networkpolicies to
be enabled in the runtime configuration in the API server. Its resources use labels to select
the pods and define rules to allow traffic to a specific pod in addition to which is defined in
the namespace.
First, we need to configure Namespace Isolation Policy. Basically, this kind of networking
policies are required on the load balancers.
kind: Namespace
apiVersion: v1
metadata:
annotations:
net.beta.kubernetes.io/network-policy: |
{
"ingress": {
"isolation": "DefaultDeny"
}
}
43
Kubernetes
- from:
- podSelector:
matchLabels:
role: frontend
ports:
- protocol: TCP
port: 6379
44
Kubernetes
Advanced Kubernetes
45
17. Kubernetes ─ API Kubernetes
Kubernetes API serves as a foundation for declarative configuration schema for the
system. Kubectl command-line tool can be used to create, update, delete, and get API
object. Kubernetes API acts a communicator among different components of Kubernetes.
The API which is getting added should be useful to more than 50% of the users. There is
no other way to implement the functionality in Kubernetes. Exceptional circumstances are
discussed in the community meeting of Kubernetes, and then API is added.
API Changes
In order to increase the capability of Kubernetes, changes are continuously introduced to
the system. It is done by Kubernetes team to add the functionality to Kubernetes without
removing or impacting the existing functionality of the system.
Now that we have the Pod object stored, a user can GET that object in any supported API
version. For example:
46
Kubernetes
The implication of this process is that API changes must be done carefully and backward-
compatibly.
API Versioning
To make it easier to support multiple structures, Kubernetes supports multiple API versions
each at different API path such as /api/v1 or /apsi/extensions/v1beta1
Alpha Level
This version contains alpha (e.g. v1alpha1)
This version may be buggy; the enabled version may have bugs.
Recommended to be used in short term testing only as the support may not be
present all the time.
Beta Level
The version name contains beta (e.g. v2beta3)
The code is fully tested and the enabled version is supposed to be stable.
The support of the feature will not be dropped; there may be some small changes.
Stable Level
The version name is vX where X is an integer.
Stable versions of features will appear in the released software for many
subsequent versions.
47
18. Kubernetes – Kubectl Kubernetes
Kubectl is the command line utility to interact with Kubernetes API. It is an interface which
is used to communicate and manage pods in Kubernetes cluster.
One needs to set up kubectl to local in order to interact with Kubernetes cluster.
Setting Kubectl
Download the executable to the local workstation using the curl command.
On Linux
$ curl -O https://storage.googleapis.com/kubernetes-
release/release/v1.5.2/bin/linux/amd64/kubectl
On OS X workstation
$ curl -O https://storage.googleapis.com/kubernetes-
release/release/v1.5.2/bin/darwin/amd64/kubectl
After download is complete, move the binaries in the path of the system.
$ chmod +x kubectl
$ mv kubectl /usr/local/bin/kubectl
Configuring Kubectl
Following are the steps to perform the configuration operation.
48
Kubernetes
Replace ${MASTER_HOST} with the master node address or name used in the
previous steps.
Replace ${CA_CERT} with the absolute path to the ca.pem created in the
previous steps.
49
19. Kubernetes – Kubectl Commands Kubernetes
Kubectl controls the Kubernetes Cluster. It is one of the key components of Kubernetes
which runs on the workstation on any machine when the setup is done. It has the capability
to manage the nodes in the cluster.
Kubectl commands are used to interact and manage Kubernetes objects and the cluster.
In this chapter, we will discuss a few commands used in Kubernetes via kubectl.
For example,
$ kubectl api-version
kubectl autoscale: This is used to auto scale pods which are defined such as Deployment,
replica set, Replication Controller.
50
Kubernetes
$ kubectl cluster-info
51
Kubernetes
52
Kubernetes
In the same way, we can create multiple things as listed using the create command along
with kubectl.
deployment
namespace
quota
secret docker-registry
secret
secret generic
secret tls
serviceaccount
service clusterip
service loadbalancer
service nodeport
kubectl delete: Deletes resources by file name, stdin, resource and names.
53
Kubernetes
kubectl drain: This is used to drain a node for maintenance purpose. It prepares the node
for maintenance. This will mark the node as unavailable so that it should not be assigned
with a new container which will be created.
kubectl edit: It is used to end the resources on the server. This allows to directly edit a
resource which one can receive via the command line tool.
kubectl expose: This is used to expose the Kubernetes objects such as pod, replication
controller, and service as a new Kubernetes service. This has the capability to expose it
via a running container or from a yaml file.
kubectl get: This command is capable of fetching data on the cluster about the
Kubernetes resources.
For example,
54
Kubernetes
kubectl logs: They are used to get the logs of the container in a pod. Printing the logs
can be defining the container name in the pod. If the POD has only one container there is
no need to define its name.
Example
$ kubectl logs tomcat.
$ kubectl logs –p –c tomcat.8
kubectl port-forward: They are used to forward one or more local port to pods.
55
Kubernetes
Apart from the above, we can perform multiple tasks using the rollout such as:
rollout history
rollout pause
rollout resume
rollout status
rollout undo
kubectl run: Run command has the capability to run an image on the Kubernetes cluster.
kubectl scale: It will scale the size of Kubernetes Deployments, ReplicaSet, Replication
Controller, or job.
56
Kubernetes
kubectl set resources: It is used to set the content of the resource. It updates
resource/limits on object with pod template.
kubectl top node: It displays CPU/Memory/Storage usage. The top command allows you
to see the resource consumption for nodes.
57
20. Kubernetes – Creating an App Kubernetes
In order to create an application for Kubernetes deployment, we need to first create the
application on the Docker. This can be done in two ways:
By downloading
From Docker file
By Downloading
The existing image can be downloaded from Docker hub and can be stored on the local
Docker registry.
The above screenshot shows a set of images which are stored in our local Docker registry.
If we want to build a container from the image which consists of an application to test, we
can do it using the Docker run command.
58
Kubernetes
FROM ubuntu:14.04
MAINTAINER [email protected]
ENV REFRESHED_AT 2017-01-15
RUN apt-get update -qq && apt-get install -qqy curl
RUN curl https://get.docker.io/gpg | apt-key add -
RUN echo deb http://get.docker.io/ubuntu docker main > /etc/apt/↩
sources.list.d/docker.list
RUN apt-get update -qq && apt-get install -qqy iptables ca-↩
certificates lxc openjdk-6-jdk git-core lxc-docker
ENV JENKINS_HOME /opt/jenkins/data
ENV JENKINS_MIRROR http://mirrors.jenkins-ci.org
RUN mkdir -p $JENKINS_HOME/plugins
RUN curl -sf -o /opt/jenkins/jenkins.war -L $JENKINS_MIRROR/war-↩
stable/latest/jenkins.war
RUN for plugin in chucknorris greenballs scm-api git-client git ↩
ws-cleanup ;\
do curl -sf -o $JENKINS_HOME/plugins/${plugin}.hpi \
-L $JENKINS_MIRROR/plugins/${plugin}/latest/${plugin}.hpi ↩
; done
ADD ./dockerjenkins.sh /usr/local/bin/dockerjenkins.sh
RUN chmod +x /usr/local/bin/dockerjenkins.sh
VOLUME /var/lib/docker
EXPOSE 8080
ENTRYPOINT [ "/usr/local/bin/dockerjenkins.sh" ]
Once the above file is created, save it with the name of Dockerfile and cd to the file path.
Then, run the following command.
59
Kubernetes
Once the image is built, we can test if the image is working fine and can be converted to
a container.
60
21. Kubernetes – App Deployment Kubernetes
In this setup, we can have a load balancer setting on top of one application diverting traffic
to a set of pods and later they communicate to backend pods. The communication between
pods happen via the service object built in Kubernetes.
61
Kubernetes
62
Kubernetes
- name: appname
image: IMAGE_TEMPLATE
imagePullPolicy: Always
ports:
- containerPort: 8080
resources:
requests:
memory: "request_mem"
cpu: "request_cpu"
limits:
memory: "limit_mem"
cpu: "limit_cpu"
env:
- name: BACKEND_HOST
value: oppv-env_name-node:3000
63
Kubernetes
apiVersion: v1
kind: ReplicationController
metadata:
name: Frontend
spec:
replicas: 3
template:
metadata:
name: frontend
labels:
k8s-app: Frontend
component: nodejs
env: Dev
spec:
nodeSelector:
resource-group: oppv
containers:
- name: appname
image: IMAGE_TEMPLATE
imagePullPolicy: Always
ports:
- containerPort: 3000
resources:
requests:
memory: "request_mem"
cpu: "limit_cpu"
limits:
memory: "limit_mem"
cpu: "limit_cpu"
env:
- name: ENV
valueFrom:
configMapKeyRef:
name: appname
key: config-env
64
Kubernetes
labels:
k8s-app: beckend
component: play
env: dev
65
Kubernetes
spec:
nodeSelector:
resource-group: oppv
containers:
- name: appname
image: IMAGE_TEMPLATE
imagePullPolicy: Always
ports:
- containerPort: 9000
command: [ "./docker-entrypoint.sh" ]
resources:
requests:
memory: "request_mem"
cpu: "request_cpu"
limits:
memory: "limit_mem"
cpu: "limit_cpu"
volumeMounts:
- name: config-volume
mountPath: /app/vipin/play/conf
volumes:
- name: config-volume
configMap:
name: appname
66
22. Kubernetes ─ Autoscaling Kubernetes
Autoscaling is one of the key features in Kubernetes cluster. It is a feature in which the
cluster is capable of increasing the number of nodes as the demand for service response
increases and decrease the number of nodes as the requirement decreases. This feature
of auto scaling is currently supported in Google Cloud Engine (GCE) and Google Container
Engine (GKE) and will start with AWS pretty soon.
In order to set up scalable infrastructure in GCE, we need to first have an active GCE
project with features of Google cloud monitoring, google cloud logging, and stackdriver
enabled.
First, we will set up the cluster with few nodes running in it. Once done, we need to set
up the following environment variable.
Environment Variable
export NUM_NODES=2
export KUBE_AUTOSCALER_MIN_NODES=2
export KUBE_AUTOSCALER_MAX_NODES=5
export KUBE_ENABLE_CLUSTER_AUTOSCALER=true
Once done, we will start the cluster by running kube-up.sh. This will create a cluster
together with cluster auto-scalar add on.
./cluster/kube-up.sh
On creation of the cluster, we can check our cluster using the following kubectl command.
Now, we can deploy an application on the cluster and then enable the horizontal pod
autoscaler. This can be done using the following command.
The above command shows that we will maintain at least one and maximum 10 replica of
the POD as the load on the application increases.
We can check the status of autoscaler by running the $kubclt get hpa command. We will
increase the load on the pods using the following command.
67
Kubernetes
We can check the number of pods running using the following command.
68
23. Kubernetes ─ Dashboard Setup Kubernetes
Setting up Kubernetes dashboard involves several steps with a set of tools required as the
prerequisites to set it up.
Docker (1.3+)
go (1.5+)
nodejs (4.2.2+)
npm (1.3+)
java (7+)
gulp (3.9+)
Kubernetes (1.1.2+)
Installing Python
$ sudo apt-get install python
$ sudo apt-get install python3
Installing GCC
$ sudo apt-get install gcc-4.8 g++-4.8
Installing make
$ sudo apt-get install make
Installing Java
$ sudo apt-get install openjdk-7-jdk
Installing Node.js
$ wget https://nodejs.org/dist/v4.2.2/node-v4.2.2.tar.gz
$ tar -xzf node-v4.2.2.tar.gz
$ cd node-v4.2.2
$ ./configure
$ make
69
Kubernetes
Installing gulp
$ npm install -g gulp
$ npm install gulp
Verifying Versions
Java Version
$ java –version
java version "1.7.0_91"
OpenJDK Runtime Environment (IcedTea 2.6.3) (7u91-2.6.3-1~deb8u1+rpi1)
OpenJDK Zero VM (build 24.91-b01, mixed mode)
$ node –v
V4.2.2
$ npn -v
2.14.7
$ gulp -v
[09:51:28] CLI version 3.9.0
Installing GO
$ git clone https://go.googlesource.com/go
$ cd go
$ git checkout go1.4.3
$ cd src
Building GO
70
Kubernetes
$ ./all.bash
$ vi /root/.bashrc
In the .bashrc
export GOROOT=$HOME/go
export PATH=$PATH:$GOROOT/bin
$ go version
go version go1.4.3 linux/arm
71
Kubernetes
72
Kubernetes
73
24. Kubernetes ─ Monitoring Kubernetes
Monitoring is one of the key component for managing large clusters. For this, we have a
number of tools.
Prometheus node explore: Gets the host level matrices and exposes them to
Prometheus.
InfuxDB: Time series database specifically used to store data from rancher.
74
Kubernetes
Docker containers. After its deployment, all logs and metrics are immediately available out
of the box.
Create an SPM App of type “Docker” to obtain the SPM App Token.
SPM App will hold your Kubernetes performance metrics and event.
Create a Logsene App to obtain the Logsene App Token. Logsene App will hold
your Kubernetes logs.
75
Kubernetes
- name: sematext-agent
image: sematext/sematext-agent-docker:latest
imagePullPolicy: "Always"
env:
- name: SPM_TOKEN
value: "REPLACE THIS WITH YOUR SPM TOKEN"
- name: LOGSENE_TOKEN
value: "REPLACE THIS WITH YOUR LOGSENE TOKEN"
- name: KUBERNETES
value: "1"
volumeMounts:
- mountPath: /var/run/docker.sock
name: docker-sock
- mountPath: /etc/localtime
name: localtime
volumes:
- name: docker-sock
hostPath:
path: /var/run/docker.sock
- name: localtime
hostPath:
path: /etc/localtime
Kubernetes Log
Kubernetes containers’ logs are not much different from Docker container logs. However,
Kubernetes users need to view logs for the deployed pods. Hence, it is very useful to have
Kubernetes-specific information available for log search, such as:
Kubernetes namespace
Kubernetes pod name
Kubernetes container name
Docker image name
Kubernetes UID
76
Kubernetes
The following code shows how to set up ELK cluster on Kubernetes and create service for
ElasticSearch:
apiVersion: v1
kind: Service
metadata:
name: elasticsearch
namespace: elk
labels:
component: elasticsearch
spec:
type: LoadBalancer
selector:
component: elasticsearch
ports:
- name: http
port: 9200
protocol: TCP
- name: transport
port: 9300
protocol: TCP
77
Kubernetes
template:
metadata:
labels:
component: elasticsearch
spec:
serviceAccount: elasticsearch
containers:
- name: es
securityContext:
capabilities:
add:
- IPC_LOCK
image: quay.io/pires/docker-elasticsearch-kubernetes:1.7.1-4
env:
- name: KUBERNETES_CA_CERTIFICATE_FILE
value: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
- name: NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: "CLUSTER_NAME"
value: "myesdb"
- name: "DISCOVERY_SERVICE"
value: "elasticsearch"
- name: NODE_MASTER
value: "true"
- name: NODE_DATA
value: "true"
- name: HTTP_ENABLE
value: "true"
ports:
- containerPort: 9200
name: http
protocol: TCP
- containerPort: 9300
78
Kubernetes
volumeMounts:
- mountPath: /data
name: storage
volumes:
- name: storage
emptyDir: {}
Kibana URL
For Kibana, we provide the Elasticsearch URL as an environment variable.
- name: KIBANA_ES_URL
value: "http://elasticsearch.elk.svc.cluster.local:9200"
- name: KUBERNETES_TRUST_CERT
value: "true"
Kibana UI will be reachable at container port 5601 and corresponding host/Node Port
combination. When you begin, there won’t be any data in Kibana (which is expected as
you have not pushed any data).
79