kubernetes-icon Kubernetes Quick Start

Installation & Setup

When working with a tool like kubernetes it is very important to make a good friendship with its documentation link
to setup kubernetes we will need two main components

  • kubectl
  • minikube
  • virtual box(optional)
if you have any problem or error during the setup you can refer to google.....

Setup guide for kubernetes

Installation

Step One

First we need to install kubectl through which we will manage kubernetes.
if you are using linux just copy and paste these commands one by one.

Commands:

sudo apt-get install curl

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

To test run below command

kubectl version --client

Step Two

Now we will install minikube, when using minikube 8Gb RAM is recommended.
if you are using linux then just copy and paste these commands one by one.

Commands:

curl -Lo minikube https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64

chmod +x minikube

sudo mkdir -p /usr/local/bin/

sudo install minikube /usr/local/bin/

Step Three

In this step we will install virtual box which is optional, if you want to use virtual box then make sure your machine supports virtualization
To check that your system supports virtualization or not run the command below

grep -E --color 'vmx|svm' /proc/cpuinfo

if this command returns some output then you are good to go else continue without install virtual box.

Commands:

sudo apt-get update

sudo apt-get upgrade

wget -q https://www.virtualbox.org/download/oracle_vbox_2016.asc -O- | sudo apt-key add -

wget -q https://www.virtualbox.org/download/oracle_vbox.asc -O- | sudo apt-key add -

sudo add-apt-repository "deb http://download.virtualbox.org/virtualbox/debian xenial contrib"

sudo apt-get update

sudo apt-get install virtualbox

Step Four

Lets check that we installed all 3 or 2 main tools correctly or not.
Run the commands that is based on your criteria.
if one fails because of any error use the command below and then try next command.

minikube delete

Commands:

minikube start

above command will start minikube using virtual box

minikube start --driver=none

if you have not installed virtual box then use the above command, if it also not works the try the below command.

minikube start --driver=docker

above command will start minikube using docker

If none of the above command worked for you then try adding --force flag to command
example :

minikube start --driver=docker --force

If minikube Starts

If minikube starts then you can type the below command to get its status

minikube status

this command will return result similler to
host: Running kubelet: Running apiserver: Running

Now its all set to us kubernetes :-)

Pod

it is a resource of Kubernetes that isolates container or group of containers, every pod has its own ip address and each container in it has different port number.

Pod basic template

kind: Pod
apiVersion: v1
metadata:
  name: <pod-name>
spec:
  containers:
  - name: <container-name>
    image: <image>
    ports:
    - containerPort: 80                                        
Simple pod using command line
kubectl run <name of pod> --image=<name of the image from registry>
Port forward pod
kubectl port-forward <pod-name> <desired-port>:<pod-exposed-port>
List pods

kubectl get pods --show-labels                                      // display all pods with their labels
kubectl get pods -L <label key>                                    // display pods with the spicfied label key as heading
kubectl get pods -l <label key>=<value>                           // display pods with the spicfied label key & value
kubectl get pods -l '<label key>in<(val1,val2)>' --show-labels    // display pods with the spicfied label key & value could be either of them
                                        

ReplicaSet

it is a resource of kubernetes that maintain the number of currently running copies of a pod.

ReplicaSet basic template

apiVersion: apps/v1
kind: ReplicaSet
metadata:
    name: frontend
    labels:
      app: guestbook
spec:
    # modify replicas according to your case
    replicas: 3
    selector:
      matchLabels:
        app: frontend
    template:
      metadata:
          labels:
            app: frontend
      spec:
        containers:
        - name: <container-name>
          image: <image>
          ports:
          - containerPort: 80
Ceate ReplicaSet
kubectl create -f <name of yaml file>
List ReplicaSet
kubectl get rs
Scale ReplicaSet

it will increase or decrease the number of pods that are managed by a ReplicaSet

kubectl scale rs <ReplicaSet-name> --replicas=<desired-number>
Delete ReplicaSet

This command will delete replicaset without deleting pods generated by that replica set

kubectl delete rs <Replicaset-name> --cascade=false

Job

it is a resource of kubernetes that creates a pod that does a specific task and gets terminated.

Job basic template

apiVersion: batch/v1
kind: Job
metadata:
  name: <job-name>
spec:
  template:
    spec:
      containers:
      - name: <container-name>
        image: <image>
        command: ["echo",  "Hello world"]
      restartPolicy: Never
  backoffLimit: 4

Cron Job

it is a resource of kubernetes that creates a job that can repeat after certain time.
first it creats a job then a pod that does the specified work.

Cron job basic template

    apiVersion: batch/v1beta1
    kind: CronJob
    metadata:
    name: <cron job name>
    spec:
    schedule: "*/1 * * * *"
    jobTemplate:   # job
        spec:
        template:  # pod template
            spec:
            containers:
            - name: <container-name>
                image: <image>
                command: ["echo",  "Hello world"]
            restartPolicy: OnFailure
                                        

Note : here ***** reprisents minute | hour | day | month | year

Service

it is a resource of kubernetes that allows us to manage routing.
There are mainly 2 type of services

  1. External-ip
  2. LoadBalancer

Service basic template

apiVersion: v1
kind: Service
metadata:
  name: <service-name>
spec:
  selector:
  <label-key>: <label-value>
  ports:
    - port: <Pod-port>
      targetPort: <container-exposed-port>
  type: LoadBalancer
Service using command line

For this you should have a ReplicaSet managing one or more pods.

kubectl expose rs <ReplicaSet-name> --name=<Service-name> --selector=<label-key>=<label-value> --port=<Pod-port> --target-port=<container-exposed-port> --type=LoadBalancer

Probes

Probe means to inspect,probe checks our application again and again after specific period of time to check if it is working correctly.
link to official documentation of probes link
There are 2 types of Probes

  1. Liveness probe (re-starts the container if fails)
  2. Readiness probe (restricts access to container if fails)

  1. Liveness probe

    liveness probe checks our application again and again after a spicific period of time to check if it is working correctly
    If it fails it restarts the container.
    There are 3 types of liveness probe

    1. http get => sends a http request and checks for response
    2. tcp socket => tries to make connection on container port
    3. exec => executes a command in the application container to check if it is hanged

    HTTP GET basic template
    
    apiVersion: v1
    kind: Pod
    metadata:
      labels:
      <key>: <value>
      name: <Pod-name>
    spec:
      containers:
      - name: <container-name>
        image: <container-image>
        livenessProbe:
          httpGet:
            path: /   #root
            port: <Pod-port or container-port>
          initialDelaySeconds: <delay before first check>
          periodSeconds: <time to wait after each check>
                                                    
    TCP socket basic template
    
    apiVersion: v1
    kind: Pod
    metadata:
      name: <pod-name>
    spec:
      containers:
      - name: <container-name>
        image: <container-image>
        ports:
        - containerPort: 8080
        livenessProbe:
          tcpSocket:
            port: <container-port>
          initialDelaySeconds: <delay before first check>
          periodSeconds: <time to wait after each check>
                                                    
    EXEC basic template
    
    apiVersion: v1
    kind: Pod
    metadata:
      name: <pod-name>
    spec:
      containers:
      - name: <container-name>
        image: <container-image>
        livenessProbe:
          exec:
            command:
            - <command eg: ls>
          initialDelaySeconds: <delay before first check>
          periodSeconds: <time to wait after each check>
                                                    
  2. Readiness probe

    Readiness checks our application again and again after a spicific period of time to check if its is working correctly
    If it fails it restricts access to container.
    There are 3 types of readiness probe

    1. http get => sends a http request and checks for response
    2. tcp socket => tries to make connection on container port
    3. exec => executes a command in the application container to check if it is hanged

    Note:

    All 3 templates are same as the liveness probe except:
    use readinessProbe: instead of livenessProbe:

Volumes

actually it is not a resource of kubernetes it is mostly written or defined in the spec: of Pods.
it actually helps us to share data between containers or whole cluster, not only that but also allow us to retain data if the pod or the container is deleted. you can say that it store & share data on the pod level
there are many types of volumes.

  • empty dir
  • configmam, secret, downward API
  • presistant vloumes
  • git repo
  • gce presistant disk
  • aws Elastic block storage
  • Azure disk

emptyDir volume basic template

it is usually used to share data b/w two or more containers in a single pod, as it makes a directory shared b/w containers.


apiVersion: v1
kind: Pod
metadata:
  name: <pod-name>
spec:
  volumes:
  - name: <volume-name>
    emptyDir: {}
  containers:
  - image: <container-image>
    name: <container-name>
    volumeMounts:
    - mountPath: <path>   #path of dir to share
      name: <volume-name>    #that is mentioned above
  - image: <container-image>
    name: <container-name>
    volumeMounts:
    - mountPath: <path>   #path of dir to share
      name: <volume-name>    #that is mentioned above

persistent Volumes

presistant volumes are a little different than other volumes as the store & share data on the cluster level
it also works a little differently. Below are the steps to use and work with persistent volume (pv).

  1. Make a persistent volume (pv)
  2. Make a persistent volume claim (pvc)
  3. Mount it in a pod as volume using (pvc)

persistent Volume basic template

you can access host file system by minikube ssh command


apiVersion: v1
kind: PersistentVolume
metadata:
  name: <pv-name>
spec:
  capacity:
    storage: <storage size eg: 5Gi>
  hostPath:
    path: <path> #pth where to store data on cluster
  accessModes:
    - ReadWriteOnce
  persistentVolumeReclaimPolicy: <Recycle or Retain or Delete>
persistent Volume claim basic template

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: <pvc-name>
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: <storage size eg: 100M>
  storageClassName: ""
Pod mounting persistent Volume basic template

apiVersion: v1
kind: Pod
metadata:
  name: <pod-name>
spec:
  volumes:
    - name: <volume-name>
      persistentVolumeClaim:
        claimName: <pvc-name>    #use pvc name that you have created
  containers:
    - name: <container-name>
      image: <container-image>
      volumeMounts:
      - mountPath: <path>    #path of dir to share
        name: <volume-name>    #that is mentioned above

Configuration

In this section we will see tools for configuration and deployments provided by kubernetes.

ConfigMap

It is a resource that can hold some configurations of your application so that you don't have to mess with application code to make some configuration changes
There are two types of config map.

  1. One that can be made as text file and can be mounted on a pod as volume
  2. One that can be made as env file and can be attached to a pod

Config map using cmd
kubectl create configmap <resource-name> --from-literal=<key1>=<val1> --from-literal=<key2>=<val2>
Config map using txt file

  1. create a text file abc.txt
  2. write :
    ke1=value1
    ke2=value2
  3. save the file.
  4. use command
    kubectl create cm <resource-name> from-file=<file-name.txt>
  5. now mount it on pod as volume
    Template
    
    kind: Pod
    apiVersion: v1
    metadata:
      name: <pod-name>
    spec:
      volumes:
      - name: <volume-name>
      configMap:
          name: <confifMap-name>
      containers:
      - name: <container-name>
        image: <image>
        ports:
        - containerPort: 80 
        volumeMounts:
        - name: <volume-name>
          mountPath: /path/to/mount
                                                            
                                                        
  6. create this pod any you are done.

Config map using env file

  1. create a text file abc.env
  2. write :
    ke1=value1
    ke2=value2
  3. save the file.
  4. use command
    kubectl create cm <resource-name> from-env-file=<file-name.env>
  5. link a pod with configMap
    Template
    
    kind: Pod
    apiVersion: v1
    metadata:
        name: <pod-name>
    spec:
      containers:
      - name: <container-name>
        image: <image>
        ports:
        - containerPort: 80
        envFrom:
        - configMapRef:
            name: <configMap-name>
                                                            
                                                        
  6. create this pod any you are done.

Secret

It is a resource that can hold some secret configurations that your app needs to run such as api keys, passwords, access tokens etc
There are two types of secets.

  1. One that can be made as text file and can be mounted on a pod as volume
  2. One that can be made as env file and can be attached to a pod

Secret using cmd
kubectl create secret generic <resource-name> --from-literal=<key1>=<val1> --from-literal=<key2>=<val2>

Note:

Method to write and create secreat env or txt file are same as configMap.
except:

when using env file:
  • use secretRef: instead of configMapRef: when creating Pod through env file.
  • use kubectl create secret generic <resource-name> from-env-file=<file-name.env> command when creating through env file.

when using txt file:
  • use secret: instead of configMap: & secretName: instead of name: when creating Pod through txt file.
  • use kubectl create secret generic <resource-name> from-file=<file-name.txt> command when creating through txt file.

Deployment

It is a resource of kuberenetes that helps us to deploy update application very easily by providing some strategies.
basically it makes a replica-set and manages that. it does not interact with any pod directly. link to documentation

Deployment basic template

apiVersion: apps/v1
kind: Deployment
metadata:
  name: <deployment-name>
  labels: #optional
    <key>: <value>
spec:
  replicas: <number-of-pods>
  selector: #optional
    matchLabels:
      <key>: <value>
  template:
    metadata:
      labels: #optional
        <key>: <value>
    spec:
      containers:
      - name: <container-name>
        image: <image>
        ports:
        - containerPort: 80
  strategy:
    type: <Recreate> or <RollingUpdate>
                                                        
                                                    
Stratergies
  • RollingUpdate

    It is the default stratergy of kubernetes deployment, according to it when we update any thing one old pod is deleted and one updated pod is created this process is repeated until all pods are replaced by newer version.
    we need to define some properties when using it. Those properties are listed below.

    • maxSurge ==> how many pods we can add at a time
    • maxUnavailable ==> maxUnavailable define how many pods can be unavailable during the rolling update
    In the last it should look like:
    
    strategy:
      type: RollingUpdate
      rollingUpdate:
        maxSurge: <any-number>
        maxUnavailable: <any-number>
                                                

  • Recreate

    In this strategy all pods all deleted at once and then newwer pods are created.
    in short your application have to face some down-time.
    In the last it should look like:

    
    strategy:
      type: Recreate
                                                

Other info about deployment can be found on the officilal link.

Others

Properties of kubernetes resources that can be added to any resource.

Labels

labels are key:value pair that help us to group different resources, we can perform different opperations on those resources using labels.
labels are defined under metadata of a resource. There can be one or more labels of a resource.
e.g type: frontend

Add label to running resource
kubectl label <resource-type> <resource-name> <key>=<value>
Remove label from a resource
kubectl label <resource-type> <resource-name> <key>-

Annotations

Annotations are also key:value pair but it is used to give a describe a resource or give any information about the resource.
annotations are also defined under metadata of a resource. There can be one or more labels of a resource.
e.g purpose: "this resource can do _____ work"

Add annotation to running resource
kubectl annotate <resource-type> <resource-name> <key>="<value>"
Remove annotation from a resource
kubectl annotate <resource-type> <resource-name> <key>-

Output | Info | Description about a resource

This command helps to get information about any resource in kubernetes in json or yaml format.
it is mostly used to debug a resource.

output of a resource
kubectl get <resource-type> <resource-name> -o <formet json or yaml>
short useful description
kubectl describe <resource-type> <resource-name>

Edit a resource during runtime

This command helps to change or edit configuration or properties of a resource while it is running.

Edit a resource
kubectl edit <resource-type> <resource-name>

Delete a resource

This command deletes a resource.

Delete a resource
kubectl delete <resource-type> <resource-name>