Sunday 25 December 2022

Add Swap Space on CentOS 9 Stream


To Add 1GB Swap Space 


#create swap file

 sudo dd if=/dev/zero of=/swapfile bs=1024 count=1048576

1048576+0 records in

1048576+0 records out

1073741824 bytes (1.1 GB, 1.0 GiB) copied, 19.8022 s, 54.2 MB/s


#set permission

sudo chmod 600 /swapfile


#set up swap area file

sudo mkswap /swapfile

Setting up swapspace version 1, size = 1024 MiB (1073737728 bytes)

no label, UUID=53c7c8d2-ed2d-4f61-b263-79a4dcd94304


#activate swap

 sudo swapon /swapfile


sudo swapon --show

NAME      TYPE       SIZE USED PRIO

/dev/dm-1 partition  2.1G   4M   -2

/swapfile file      1024M   0B   -3


sudo free -h

               total        used        free      shared  buff/cache   available

Mem:           1.7Gi       898Mi        69Mi        12Mi       970Mi       852Mi

Swap:          3.1Gi       4.0Mi       3.1Gi


#make permenant entry

sudo vim /etc/fstab

/swapfile swap swap defaults 0 0



Monday 19 December 2022

How Kube-Proxy handles the traffic between the containers and the virtual machine by creating IP table rules in Kubernetes.


Demonstration


kubectl get svc





#to view any traffic sent to the IP sent to the following Rule

sudo iptables -S -t nat | grep IP





#inspect the rule





#the above rule diverts the traffic to the VM IP





#find the container using kube-apiserver

docker ps











#monitor kube-apiserver container

docker top container_id









#inspect the container to confirm IP used

docker inspect fcec33b58cbb | grep "address="

 





Tuesday 13 December 2022

Configuring Jenkins ThinBackup and Restore


Create a backup directory 









Install Thinbackup Plugin










Navigate to ThinBackup and configure









Configure the settings


















Full backup happens every 5mins and Incremental backup every 2mins






Restore backup from the dropdown.








Backup any location

mkdir -p /opt/backup

chown -R jenkins:jenkins /opt/backup

ls -lsrt /opt/backup/

total 8

4 drwxr-xr-x 6 jenkins jenkins 4096 Dec 13 10:05 FULL-2022-12-13_10-05

4 drwxr-xr-x 3 jenkins jenkins 4096 Dec 13 10:06 DIFF-2022-12-13_10-06


Wednesday 30 November 2022

Building Spring boot application manually and run it with the Docker Container


git clone https://github.com/callicoder/spring-boot-websocket-chat-demo.git

 cd spring-boot-websocket-chat-demo/

 cat Dockerfile

# Start with a base image containing Java runtime

FROM openjdk:11


# Add Maintainer Info

MAINTAINER Rajeev Kumar Singh <callicoder@gmail.com>


# Add a volume pointing to /tmp

VOLUME /tmp


# Make port 8080 available to the world outside this container

EXPOSE 8080


# The application's jar file

ARG JAR_FILE=target/websocket-demo-0.0.1-SNAPSHOT.jar


# Add the application's jar to the container

ADD ${JAR_FILE} websocket-demo.jar


# Run the jar file

ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/websocket-demo.jar"]


mvn clean package


sudo docker build -t webchat .


sudo docker images


sudo docker run -p 5000:8080 --name web_chat webchat


http://localhost:5000/


Building a Spring Boot application in Jenkins using pipeline Groovy script and run with Docker Container

 

This Jenkins job will be building the docker image from the Git repo.

Create a pipeline job with Jenkins and add Pipeline Script.

pipeline {

    agent any


    tools {

        // Install the Maven version configured as "M3" and add it to the path.

        maven "M3"

    }


    stages {

        

        stage('Preparation') {

            steps {

                // Get some code from a GitHub repository

                git 'https://github.com/callicoder/spring-boot-websocket-chat-demo.git'


            }

        }

        

        stage('Build') {

            steps {


                // To run Maven on a Windows agent, use

                sh "mvn -Dmaven.test.failure.ignore=true clean package"

            }

            


            post {

                // If Maven was able to run the tests, even if some of the test

                // failed, record the test results and archive the jar file.

                success {

                    junit '**/target/surefire-reports/TEST-*.xml'

                    archiveArtifacts 'target/*.jar'

                }

            }

        }

 stage('Docker Build') {

   

          steps {

          sh 'docker build -t spring-boot-websocket-chat-demo .'

          }

        }

        

         

        stage('Deploy') {

   

          steps {

               sh 'docker stop app_container'

               sh 'docker rm app_container'

          sh 'docker run -d -p 5001:8080 --name app_container spring-boot-websocket-chat-demo'

          }

        }

    }

}















Tuesday 29 November 2022

Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock:

 

Error: - While running pipeline groovy script to build a docker image for spring boot chat demo.

+ docker build -t spring-boot-websocket-chat-demo .
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post "http://%2Fvar%2Frun%2Fdocker.sock/v1.24/build?buildargs=%7B%7D&cachefrom=%5B%5D&cgroupparent=&cpuperiod=0&cpuquota=0&cpusetcpus=&cpusetmems=&cpushares=0&dockerfile=Dockerfile&labels=%7B%7D&memory=0&memswap=0&networkmode=default&rm=1&shmsize=0&t=spring-boot-websocket-chat-demo&target=&ulimits=null&version=1": dial unix /var/run/docker.sock: connect: permission denied
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Deploy)
Stage "Deploy" skipped due to earlier failure(s)
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: script returned exit code 1
Finished: FAILURE
solution:- 
sudo chmod 777 /var/run/docker.sock

How to check a Linux system is Little endian or Big

Example from Ubuntu System

#lscpu

lscpu | grep Endian

lscpu | grep -i byte




#python3

python3 -c "import sys; print(sys.byteorder)"




#Example from a little-endian system

echo -n I | od -to2 | head -n1 | cut -f2 -d" " | cut -c6

#using awk

echo -n I | od -to2 | awk '{ print substr($2,6,1); exit}'

echo -n I | od -to2 | awk 'FNR==1{ print substr($2,6,1)}'

#on all unix systems

echo I | tr -d [:space:] | od -to2 | head -n1 | awk '{print $2}' | cut -c6





#with hexdump

echo -n I | hexdump -o | awk '{ print substr($2,6,1); exit}'

hexdump -s 5 -n 1 -C /bin/busybox

hexdump -s 5 -n 1 /bin/sh





# apt install dpkg-dev on ubuntu

dpkg-architecture | grep -i end





#take advantage of ELF file format

xxd -c 1 -l 6 /bin/ls






Ref:- how-to-tell-if-a-linux-system-is-big-endian-or-little-endian


Wednesday 23 November 2022

Build a Java Application with Jenkins in Docker


cat Dockerfile

from jenkins/jenkins:lts

USER root

RUN apt-get update -qq && apt-get install wget

RUN wget http://apache.cs.utah.edu/maven/maven-3/3.8.6/binaries/apache-maven-3.8.6-bin.tar.gz

RUN tar xzf apache-maven-3.8.6-bin.tar.gz -C /opt/

RUN ln -s /opt/apache-maven-3.8.6 /opt/maven

RUN ln -s /opt/maven/bin/mvn /usr/local/bin

RUN rm -f apache-maven-3.8.6-bin.tar.gz

ENV MAVEN_HOME /opt/maven

RUN chown -R jenkins:jenkins /opt/maven

RUN apt clean

USER jenkins


sudo docker image build -t jenkins-docker .


 sudo docker images

REPOSITORY        TAG       IMAGE ID       CREATED          SIZE

jenkins-docker    latest    ca1cb1129c7e   38 seconds ago   505MB

jenkins/jenkins   lts       25fa92c47840   8 days ago       463MB


sudo docker run -it -d -p 8080:8080 -p 50000:50000 -v jenkins_home:/var/jenkins_home -v /var/run/docker.sock:/var/run/docker.sock --restart unless-stopped jenkins-docker


sudo docker ps

CONTAINER ID   IMAGE            COMMAND                  CREATED         STATUS         PORTS                                                                                      NAMES

7333f25c2524   jenkins-docker   "/usr/bin/tini -- /u…"   4 minutes ago   Up 4 minutes   0.0.0.0:8080->8080/tcp, :::8080->8080/tcp, 0.0.0.0:50000->50000/tcp, :::50000->50000/tcp   silly_sanderson


http://localhost:8080/


#get the admin password




Jenkins global configurations

sudo docker exec -it 7333f25c2524 /bin/bash

jenkins@7333f25c2524:/$ mvn --version

Apache Maven 3.8.6 (84538c9988a25aec085021c365c560670ad80f63)

Maven home: /opt/maven

Java version: 11.0.16.1, vendor: Eclipse Adoptium, runtime: /opt/java/openjdk

Default locale: en, platform encoding: UTF-8

OS name: "linux", version: "5.15.0-52-generic", arch: "amd64", family: "unix"

jenkins@7333f25c2524:/$ java --version

openjdk 11.0.16.1 2022-08-12

OpenJDK Runtime Environment Temurin-11.0.16.1+1 (build 11.0.16.1+1)

OpenJDK 64-Bit Server VM Temurin-11.0.16.1+1 (build 11.0.16.1+1, mixed mode)































Execute shell commands in Jenkins by  Creating a Job



































Example using jenkins-docker-maven-github













    














Saturday 2 July 2022

Basic Commands of Kubernetes


#Creating the Deployment

kubectl create deployment myapp2 --image=docker.io/openshift/hello-openshift

deployment.apps/myapp2 created


#Verify the Deployment and Pods’ states 

kubectl get po

NAME                      READY   STATUS    RESTARTS       AGE

myapp2-757cc77ff9-lnzwc   1/1     Running   0              8s


#describe Pod content

kubectl describe po  myapp2-757cc77ff9-lnzwc

Name:         myapp2-757cc77ff9-lnzwc

Namespace:    default

Priority:     0

Node:         node-2.example.com/172.31.55.63

Start Time:   Thu, 30 Jun 2022 22:52:42 +0000

Labels:       app=myapp2

              pod-template-hash=757cc77ff9

Annotations:  <none>

Status:       Running

IP:           10.36.0.5

IPs:

  IP:           10.36.0.5

Controlled By:  ReplicaSet/myapp2-757cc77ff9

Containers:

  hello-openshift:

    Container ID:   docker://f39e3bfb9b6b4cdf127dfd8368ec76610078d64c79516e70848b884d2e6e4be7

    Image:          docker.io/openshift/hello-openshift

    Image ID:       docker-pullable://openshift/hello-openshift@sha256:aaea76ff622d2f8bcb32e538e7b3cd0ef6d291953f3e7c9f556c1ba5baf47e2e

    Port:           <none>

    Host Port:      <none>

    State:          Running

      Started:      Thu, 30 Jun 2022 22:52:44 +0000

    Ready:          True

    Restart Count:  0

    Environment:    <none>

    Mounts:

      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-x5skk (ro)

Conditions:

  Type              Status

  Initialized       True 

  Ready             True 

  ContainersReady   True 

  PodScheduled      True 

Volumes:

  kube-api-access-x5skk:

    Type:                    Projected (a volume that contains injected data from multiple sources)

    TokenExpirationSeconds:  3607

    ConfigMapName:           kube-root-ca.crt

    ConfigMapOptional:       <nil>

    DownwardAPI:             true

QoS Class:                   BestEffort

Node-Selectors:              <none>

Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s

                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s

Events:

  Type    Reason     Age   From               Message

  ----    ------     ----  ----               -------

  Normal  Scheduled  98s   default-scheduler  Successfully assigned default/myapp2-757cc77ff9-lnzwc to node-2.example.com

  Normal  Pulling    98s   kubelet            Pulling image "docker.io/openshift/hello-openshift"

  Normal  Pulled     97s   kubelet            Successfully pulled image "docker.io/openshift/hello-openshift" in 827.570703ms

  Normal  Created    97s   kubelet            Created container hello-openshift

  Normal  Started    97s   kubelet            Started container hello-openshift


#to get running Deployment 

kubectl get deployment

NAME     READY   UP-TO-DATE   AVAILABLE   AGE

myapp2   1/1     1            1           4m14s


#to describe content

kubectl describe deployment myapp2

Name:                   myapp2

Namespace:              default

CreationTimestamp:      Thu, 30 Jun 2022 22:52:42 +0000

Labels:                 app=myapp2

Annotations:            deployment.kubernetes.io/revision: 1

Selector:               app=myapp2

Replicas:               1 desired | 1 updated | 1 total | 1 available | 0 unavailable

StrategyType:           RollingUpdate

MinReadySeconds:        0

RollingUpdateStrategy:  25% max unavailable, 25% max surge

Pod Template:

  Labels:  app=myapp2

  Containers:

   hello-openshift:

    Image:        docker.io/openshift/hello-openshift

    Port:         <none>

    Host Port:    <none>

    Environment:  <none>

    Mounts:       <none>

  Volumes:        <none>

Conditions:

  Type           Status  Reason

  ----           ------  ------

  Available      True    MinimumReplicasAvailable

  Progressing    True    NewReplicaSetAvailable

OldReplicaSets:  <none>

NewReplicaSet:   myapp2-757cc77ff9 (1/1 replicas created)

Events:

  Type    Reason             Age   From                   Message

  ----    ------             ----  ----                   -------

  Normal  ScalingReplicaSet  10m   deployment-controller  Scaled up replica set myapp2-757cc77ff9 to 1


#create a yaml file 

kubectl create deployment myhttpd --image=docker.io/httpd --dry-run=client -o yaml > mydep.yaml


cat mydep.yaml 

apiVersion: apps/v1

kind: Deployment

metadata:

  creationTimestamp: null

  labels:

    app: myhttpd

  name: myhttpd

spec:

  replicas: 1

  selector:

    matchLabels:

      app: myhttpd

  strategy: {}

  template:

    metadata:

      creationTimestamp: null

      labels:

        app: myhttpd

    spec:

      containers:

      - image: docker.io/httpd

        name: httpd

        resources: {}

status: {}


#Create the Deployment 

kubectl apply -f mydep.yaml 

deployment.apps/myhttpd created


kubectl get deployment

NAME                  READY   UP-TO-DATE   AVAILABLE   AGE

myhttpd               1/1     1            1           11s


#Expose the Deployment to create a service

kubectl expose deployment myhttpd --port=8080

service/myhttpd exposed


#Verify the created services

kubectl get svc

NAME                     TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE

kubernetes               ClusterIP   10.96.0.1        <none>        443/TCP        7d9h

myhttpd                  ClusterIP   10.110.234.236   <none>        8080/TCP       9s


#Describe the service 

kubectl describe svc myhttpd

Name:              myhttpd

Namespace:         default

Labels:            app=myhttpd

Annotations:       <none>

Selector:          app=myhttpd

Type:              ClusterIP

IP Family Policy:  SingleStack

IP Families:       IPv4

IP:                10.110.234.236

IPs:               10.110.234.236

Port:              <unset>  8080/TCP

TargetPort:        8080/TCP

Endpoints:         10.36.0.5:8080

Session Affinity:  None

Events:            <none>


Creating the namespaces


#create specific namespaces

kubectl create namespace mynamespace

namespace/mynamespace created


#Verify the namespace

kubectl get namespace

NAME              STATUS   AGE

default           Active   7d9h

kube-node-lease   Active   7d9h

kube-public       Active   7d9h

kube-system       Active   7d9h

mynamespace       Active   8s


Scaling and deleting the Deployment


#create a Deployment in a particular namespace

kubectl create deployment myhttpd --image=docker.io/httpd -n mynamespace

deployment.apps/myhttpd created


kubectl get deployment -n mynamespace

NAME      READY   UP-TO-DATE   AVAILABLE   AGE

myhttpd   1/1     1            1           2m39s


kubectl get pods -n mynamespace

NAME                       READY   STATUS    RESTARTS   AGE

myhttpd-78f86b45d5-pd2ph   1/1     Running   0          3m5s


#Scale the Deployment 

kubectl scale --replicas=3 deployment myhttpd -n  mynamespace

deployment.apps/myhttpd scaled


kubectl get deployment -n mynamespace

NAME      READY   UP-TO-DATE   AVAILABLE   AGE

myhttpd   3/3     3            3           4m49s


#get the endpoints

kubectl get endpoints

NAME                     ENDPOINTS                       AGE

kubernetes               172.31.54.141:6443              7d10h

myhttpd                  10.36.0.5:8080                  39m


kubectl describe endpoints

Name:         kubernetes

Namespace:    default

Labels:       endpointslice.kubernetes.io/skip-mirror=true

Annotations:  <none>

Subsets:

  Addresses:          172.31.54.141

  NotReadyAddresses:  <none>

  Ports:

    Name   Port  Protocol

    ----   ----  --------

    https  6443  TCP


Events:  <none>


Name:         myhttpd

Namespace:    default

Labels:       app=myhttpd

Annotations:  endpoints.kubernetes.io/last-change-trigger-time: 2022-07-03T01:32:13Z


Delete the created Pods, Deployment, service, and namespace 


kubectl delete deployment myhttpd

deployment.apps "myhttpd" deleted


kubectl delete svc myhttpd

service "myhttpd" deleted


kubectl get svc

NAME                     TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE

kubernetes               ClusterIP   10.96.0.1        <none>        443/TCP        7d10h


kubectl delete namespace mynamespace

namespace "mynamespace" deleted


#Verify the events 

kubectl get events

LAST SEEN   TYPE      REASON                    OBJECT                                          MESSAGE

57m         Normal    Starting                  node/main.example.com                         Starting kubelet.

57m         Normal    NodeHasSufficientMemory   node/main.example.com                         Node main.example.com status is now: NodeHasSufficientMemory

57m         Normal    NodeHasNoDiskPressure     node/main.example.com                         Node main.example.com status is now: NodeHasNoDiskPressure

57m         Normal    NodeHasSufficientPID      node/main.example.com                         Node main.example.com status is now: NodeHasSufficientPID

57m         Normal    NodeAllocatableEnforced   node/main.example.com                         Updated Node Allocatable limit across pods

<...>


#Verify the Nodes’ state 

kubectl get nodes

NAME                        STATUS   ROLES                  AGE     VERSION

node.example.com          Ready    control-plane,main   7d10h   v1.23.4

node-1.example.com   Ready    <none>                 7d10h   v1.23.4

node-2.example.com   Ready    <none>                 7d10h   v1.23.4


#describe Nodes’ 

kubectl describe node node-1.example.com

Name:               node-1.example.com

Roles:              <none>

Labels:             beta.kubernetes.io/arch=amd64

                    beta.kubernetes.io/os=linux

                    kubernetes.io/arch=amd64

                    kubernetes.io/hostname=worker-node-1.example.com

                    kubernetes.io/os=linux

Annotations:        kubeadm.alpha.kubernetes.io/cri-socket: /var/run/dockershim.sock

                    node.alpha.kubernetes.io/ttl: 0

                    volumes.kubernetes.io/controller-managed-attach-detach: true

<...>


Thursday 30 June 2022

Creating and Configuring the Deployment in Kubernetes using OpenShift


Creating the Deployment


kubectl create deployment myapp1 --image=docker.io/openshift/hello-openshift 

deployment.apps/myapp1 created


kubectl get deployment

NAME     READY   UP-TO-DATE   AVAILABLE   AGE

myapp1   1/1     1            1           14s


kubectl get po

NAME                     READY   STATUS    RESTARTS       AGE

myapp1-bcb89d7dd-hvxgk   1/1     Running   0              101s


Accessing the Pod


kubectl expose deployment myapp1 --port=8080

service/myapp1 exposed


kubectl get svc

NAME              TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE

kubernetes        ClusterIP   10.96.0.1       <none>        443/TCP        5d6h

myapp1            ClusterIP   10.111.40.120   <none>        8080/TCP       33s


curl 10.111.40.120:8080

Hello OpenShift!


Create OpenShift Kubernetes Pod Example


 ls

openshift-pod.yaml  openshift1-pod.yaml


 cat openshift-pod.yaml 

apiVersion: v1

kind: Pod

metadata:

  name: mypod1

  labels:

    mycka: round-robin

spec:

  containers:

  - name: mycontainer

    image: openshift/hello-openshift

    ports:

    - containerPort: 8080


kubectl create -f openshift-pod.yaml

pod/mypod1 created


cat openshift1-pod.yaml 

apiVersion: v1

kind: Pod

metadata:

  name: mypod2

  labels:

    mycka: round-robin

spec:

  containers:

  - name: mycontainer

    image: openshift/hello-openshift

    ports:

    - containerPort: 8080


kubectl create -f openshift1-pod.yaml

pod/mypod2 created


kubectl get pods -o wide

NAME                    READY   STATUS    RESTARTS       AGE    IP          NODE                 NOMINATED NODE   READINESS GATES

mypod1                  1/1     Running   0              33s    10.44.0.3   node-1.example.com   <none>           <none>

mypod2                  1/1     Running   0              9s     10.44.0.4   node-1.example.com   <none>           <none>


curl 10.44.0.3:8080

Hello OpenShift!


curl 10.44.0.4:8080

Hello OpenShift!


Configure Pods in Kubernetes Cluster | Label and Service Example with apache


 ls

pod.yaml  pod1.yaml  service.yaml


Configuring and setting up the apache Pods


cat pod.yaml 

apiVersion: v1

kind: Pod

metadata:

  name: apache2

  labels:

    mycka: mylabel

spec:

  containers:

  - name: mycontainer

    image: docker.io/httpd

    ports:

    - containerPort: 80


kubectl create -f pod.yaml 

pod/apache2 created


 cat pod1.yaml 

apiVersion: v1

kind: Pod

metadata:

  name: apache3

  labels:

    mycka: mylabel

spec:

  containers:

  - name: mycontainer

    image: docker.io/httpd

    ports:

    - containerPort: 80


kubectl create -f pod1.yaml 

pod/apache3 created


kubectl get po

NAME                    READY   STATUS    RESTARTS       AGE

apache2                 1/1     Running   0              70s

apache3                 1/1     Running   0              15s


Configuring and setting up the Service 


cat service.yaml 

kind: Service

apiVersion: v1

metadata:

  name: myservice

spec:

  selector: 

      mycka: mylabel

  ports:

    - protocol: TCP

      port: 8081

      targetPort: 80


 kubectl create -f service.yaml 

service/myservice created


 kubectl get svc

NAME              TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)        AGE

kubernetes        ClusterIP   10.96.0.1      <none>        443/TCP        5d5h

myservice         ClusterIP   10.98.192.24   <none>        8081/TCP       8s


Executing the Apache services 


kubectl exec -it apache2 bash

kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.

root@apache2:/usr/local/apache2# echo \342\200\234Hello from pod1 \342\200\235 > htdocs/index.html

root@apache2:/usr/local/apache2# cat htdocs/index.html

“Hello from pod1 ”

root@apache2:/usr/local/apache2# exit

exit


kubectl exec -it apache3 bash

kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.

root@apache3:/usr/local/apache2# echo \342\200\234Hello from pod2 \342\200\235 > htdocs/index.html

root@apache3:/usr/local/apache2# cat htdocs/index.html

“Hello from pod2 ”

root@apache3:/usr/local/apache2# exit

exit


#myservice is connected to apache2 and apache3 

kubectl get svc -o wide

NAME              TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)        AGE     SELECTOR

kubernetes        ClusterIP   10.96.0.1      <none>        443/TCP        5d5h    <none>

myservice         ClusterIP   10.98.192.24   <none>        8081/TCP       3m43s   mycka=mylabel


#service can call from both pods

curl 10.98.192.24:8081

“Hello from pod1 ”


curl 10.98.192.24:8081

“Hello from pod2 ”


Wednesday 29 June 2022

Kubernetes Demo | Pod Deployment | Web application with MySQL


Ref: - https://www.youtube.com/watch?v=0j-iIW3_sbg&t=1291s


ls

mysqldatabase.yaml  mysqlservice.yml  webapplication.yaml  webservice.yml


cat webapplication.yaml

apiVersion: apps/v1

kind: Deployment

metadata:

  name: webapp1

  labels:

    app: webapp-sql

    tier: frontend

spec:

  replicas: 1

  selector:

    matchLabels:

      app: webapp-sql

      tier: frontend

  template:

    metadata:

      labels:

        app: webapp-sql

        tier: frontend

    spec:

      containers:

      - name: webapp1

        image: hshar/webapp

        ports:

        - containerPort: 8081


 cat mysqldatabase.yaml

apiVersion: apps/v1

kind: Deployment

metadata:

  name: sqldb

  labels:

    app: webapp-sql

    tier: backend

spec:

  replicas: 1

  selector:

    matchLabels:

      app: webapp-sql

      tier: backend

  template:

    metadata:

      labels:

        app: webapp-sql

        tier: backend

    spec:

      containers:

        - name: mysql

          image: hshar/mysql:5.5

          ports:

            - containerPort: 3306


cat webservice.yml

apiVersion: v1

kind: Service

metadata:

  name: webapp-sql

spec:

  selector:

    app: webapp-sql

    tier: frontend

  ports:

  - port: 80

  type: NodePort


 cat mysqlservice.yml

apiVersion: v1

kind: Service

metadata:

  name: webapp-sql1

spec:

  selector:

    app: webapp-sql

    tier: backend

  ports:

    - port: 3306

  clusterIP:


kubectl apply -f webapplication.yaml

deployment.apps/webapp1 created


kubectl apply -f mysqldatabase.yaml

deployment.apps/sqldb created


kubectl get deployment

NAME      READY   UP-TO-DATE   AVAILABLE   AGE

sqldb     1/1     1            1           69s

webapp1   1/1     1            1           80s


kubectl apply -f webservice.yml

service/webapp-sql created


kubectl apply -f mysqlservice.yml

service/webapp-sql1 created


kubectl get service

NAME          TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE

kubernetes    ClusterIP   10.96.0.1       <none>        443/TCP        5d7h

webapp-sql    NodePort    10.98.200.159   <none>        80:32025/TCP   19s

webapp-sql1   ClusterIP   10.97.173.97    <none>        3306/TCP       7s


kubectl get po

NAME                       READY   STATUS    RESTARTS   AGE

sqldb-6777dc65bb-ttkwk     1/1     Running   0          2m

webapp1-6996dfc8d8-2kl4q   1/1     Running   0          2m11s


kubectl exec -it webapp1-6996dfc8d8-2kl4q bash                   

kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.

root@webapp1-6996dfc8d8-2kl4q:/# nano var/www/html/index.php

<...>

$servername = "webapp-sql1";

$username = "root";

$password = "edureka";

$dbname = "Product_Details";

<...>

root@webapp1-6996dfc8d8-2kl4q:/# exit

exit


kubectl exec -it sqldb-6777dc65bb-ttkwk bash

root@sqldb-6777dc65bb-ttkwk:/# mysql -u root -pedureka

<...>

mysql> CREATE DATABASE Product_Details;

Query OK, 1 row affected (0.00 sec)

mysql> USE Product_Details;

Database changed

mysql> CREATE TABLE products ( product_name VARCHAR(10), product_id VARCHAR(15) );

Query OK, 0 rows affected (0.01 sec)

mysql> exit

Bye

root@sqldb-6777dc65bb-ttkwk:/# exit

exit


kubectl get services

NAME          TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE

kubernetes    ClusterIP   10.96.0.1       <none>        443/TCP        5d7h

webapp-sql    NodePort    10.98.200.159   <none>        80:32025/TCP   9m38s

webapp-sql1   ClusterIP   10.97.173.97    <none>        3306/TCP       9m26s


kubectl get po

NAME                       READY   STATUS    RESTARTS   AGE

sqldb-6777dc65bb-ttkwk     1/1     Running   0          28m

webapp1-6996dfc8d8-2kl4q   1/1     Running   0          29m


kubectl describe po/webapp1-6996dfc8d8-2kl4q | grep Node:

Node:         minikube-m02/192.168.49.3


http://192.168.49.3:32025/index.php


Monday 27 June 2022

Create Pods with namespace in Kubernetes


#default namespace

kubectl get ns

NAME                   STATUS   AGE

default                Active   4d7h

kube-node-lease        Active   4d7h

kube-public            Active   4d7h

kube-system            Active   4d7h

kubernetes-dashboard   Active   4d7h


#to create a namespace

kubectl create ns mynamespace

namespace/mynamespace created


kubectl get ns

NAME                   STATUS   AGE

default                Active   4d7h

kube-node-lease        Active   4d7h

kube-public            Active   4d7h

kube-system            Active   4d7h

kubernetes-dashboard   Active   4d7h

mynamespace            Active   7s


#create a pod with mynamespace

kubectl run nginx --image=nginx --namespace mynamespace

pod/nginx created


kubectl get pods --namespace mynamespace

NAME    READY   STATUS    RESTARTS   AGE

nginx   1/1     Running   0          13s


#add 2nd pod with mynamespace

kubectl run nginx2 --image=nginx --namespace mynamespace

pod/nginx2 created


kubectl get pods --namespace mynamespace

NAME     READY   STATUS    RESTARTS   AGE

nginx    1/1     Running   0          76s

nginx2   1/1     Running   0          17s


#delete mynamespace

kubectl delete ns mynamespace

namespace "mynamespace" deleted


#all resources listed are deleted from the mynamespace

kubectl delete ns mynamespace

Error from server (NotFound): namespaces "mynamespace" not found


Use Label to Add Remove Filter Pods in Kubernetes


kubectl run nginx1 --image=nginx

pod/nginx1 created


#see Labels

kubectl describe pod nginx1

Name:         nginx1

Namespace:    default

Priority:     0

Node:         minikube-m02/192.168.49.3

Start Time:   Mon, 27 Jun 2022 17:35:39 -0700

Labels:       run=nginx1

Annotations:  <none>

Status:       Running

IP:           172.17.0.5

IPs:

  IP:  172.17.0.5

Containers:

  nginx1:

    Container ID:   docker://876631db265761b3dbe3170433210257470606f776dff93ffd6                                                                                                             aca3a3ec8b8f9

    Image:          nginx

    Image ID:       docker-pullable://nginx@sha256:10f14ffa93f8dedf1057897b745e5                                                                                                             ac72ac5655c299dade0aa434c71557697ea

    Port:           <none>

    Host Port:      <none>

    State:          Running

      Started:      Mon, 27 Jun 2022 17:35:48 -0700

    Ready:          True

    Restart Count:  0

    Environment:    <none>

    Mounts:

      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-8ddm2 (ro)

Conditions:

  Type              Status

  Initialized       True

  Ready             True

  ContainersReady   True

  PodScheduled      True

Volumes:

  kube-api-access-8ddm2:

    Type:                    Projected (a volume that contains injected data fro                                                                                                             m multiple sources)

    TokenExpirationSeconds:  3607

    ConfigMapName:           kube-root-ca.crt

    ConfigMapOptional:       <nil>

    DownwardAPI:             true

QoS Class:                   BestEffort

Node-Selectors:              <none>

Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s

                             node.kubernetes.io/unreachable:NoExecute op=Exists                                                                                                              for 300s

Events:

  Type    Reason     Age   From               Message

  ----    ------     ----  ----               -------

  Normal  Scheduled  17s   default-scheduler  Successfully assigned default/ngin                                                                                                             x1 to minikube-m02

  Normal  Pulling    17s   kubelet            Pulling image "nginx"

  Normal  Pulled     8s    kubelet            Successfully pulled image "nginx"                                                                                                              in 8.887080516s

  Normal  Created    8s    kubelet            Created container nginx1

  Normal  Started    8s    kubelet            Started container nginx1


#add label to a pod

kubectl label pod nginx1 envronment=development

pod/nginx1 labeled


kubectl describe pod nginx1 | grep Labels

Labels:       envronment=development


kubectl run nginx2 --image=nginx

pod/nginx2 created


kubectl label pod nginx2 envronment=production

pod/nginx2 labeled


kubectl describe pod nginx2 | grep Labels

Labels:       envronment=production


kubectl get pods

NAME                        READY   STATUS      RESTARTS   AGE

nginx1                      1/1     Running     0          5m50s

nginx2                      1/1     Running     0          36s


kubectl get pods --show-labels

NAME                        READY   STATUS      RESTARTS   AGE     LABELS

nginx1                      1/1     Running     0          6m11s   envronment=development,run=nginx1

nginx2                      1/1     Running     0          57s     envronment=production,run=nginx2


kubectl label pod nginx2 projectcode=3344

pod/nginx2 labeled


kubectl get pods --show-labels

NAME                        READY   STATUS      RESTARTS   AGE     LABELS

nginx1                      1/1     Running     0          7m      envronment=development,run=nginx1

nginx2                      1/1     Running     0          106s    envronment=production,projectcode=3344,run=nginx2


#remove label

kubectl label pod nginx1 run-

pod/nginx1 unlabeled


kubectl get pods --show-labels

NAME                        READY   STATUS      RESTARTS   AGE     LABELS

nginx1                      1/1     Running     0          7m39s   envronment=development

nginx2                      1/1     Running     0          2m25s   envronment=production,projectcode=3344,run=nginx2


kubectl label pod nginx2 run-

pod/nginx2 unlabeled


kubectl get pods --show-labels

NAME                        READY   STATUS      RESTARTS   AGE     LABELS

nginx1                      1/1     Running     0          8m3s    envronment=development

nginx2                      1/1     Running     0          2m49s   envronment=production,projectcode=3344


kubectl get pods --show-labels | grep development

nginx1                      1/1     Running     0          64m     envronment=development


Kubernetes Pod Deployment and Edit Replication


kubectl create deploy myweb --image=nginx

deployment.apps/myweb created


kubectl get deploy

NAME    READY   UP-TO-DATE   AVAILABLE   AGE

myweb   1/1     1            1           8s


kubectl get deploy myweb

NAME    READY   UP-TO-DATE   AVAILABLE   AGE

myweb   1/1     1            1           21s


kubectl describe deploy myweb

Name:                   myweb

Namespace:              default

CreationTimestamp:      Mon, 27 Jun 2022 17:18:35 -0700

Labels:                 app=myweb

Annotations:            deployment.kubernetes.io/revision: 1

Selector:               app=myweb

Replicas:               1 desired | 1 updated | 1 total | 1 available | 0 unavai                                                                                                             lable

StrategyType:           RollingUpdate

MinReadySeconds:        0

RollingUpdateStrategy:  25% max unavailable, 25% max surge

Pod Template:

  Labels:  app=myweb

  Containers:

   nginx:

    Image:        nginx

    Port:         <none>

    Host Port:    <none>

    Environment:  <none>

    Mounts:       <none>

  Volumes:        <none>

Conditions:

  Type           Status  Reason

  ----           ------  ------

  Available      True    MinimumReplicasAvailable

  Progressing    True    NewReplicaSetAvailable

OldReplicaSets:  <none>

NewReplicaSet:   myweb-58d88b7dfb (1/1 replicas created)

Events:

  Type    Reason             Age   From                   Message

  ----    ------             ----  ----                   -------

  Normal  ScalingReplicaSet  43s   deployment-controller  Scaled up replica set                                                                                                              myweb-58d88b7dfb to 1


#edit no of replicas to 2

kubectl edit deploy myweb

deployment.apps/myweb edited


kubectl get deploy

NAME    READY   UP-TO-DATE   AVAILABLE   AGE

myweb   2/2     2            2           118s


kubectl get pods

NAME                        READY   STATUS      RESTARTS   AGE

myweb-58d88b7dfb-6lj6k      1/1     Running     0          24s

myweb-58d88b7dfb-bxcj6      1/1     Running     0          2m4s


#replicas 3

kubectl edit deploy myweb

deployment.apps/myweb edited


kubectl get pods

NAME                        READY   STATUS      RESTARTS   AGE

myweb-58d88b7dfb-6lj6k      1/1     Running     0          65s

myweb-58d88b7dfb-bxcj6      1/1     Running     0          2m45s

myweb-58d88b7dfb-wb7jj      1/1     Running     0          11s


kubectl describe deploy myweb

Name:                   myweb

Namespace:              default

CreationTimestamp:      Mon, 27 Jun 2022 17:18:35 -0700

Labels:                 app=myweb

Annotations:            deployment.kubernetes.io/revision: 1

Selector:               app=myweb

Replicas:               3 desired | 3 updated | 3 total | 3 available | 0 unavai                                                                                                             lable

StrategyType:           RollingUpdate

MinReadySeconds:        0

RollingUpdateStrategy:  25% max unavailable, 25% max surge

Pod Template:

  Labels:  app=myweb

  Containers:

   nginx:

    Image:        nginx

    Port:         <none>

    Host Port:    <none>

    Environment:  <none>

    Mounts:       <none>

  Volumes:        <none>

Conditions:

  Type           Status  Reason

  ----           ------  ------

  Progressing    True    NewReplicaSetAvailable

  Available      True    MinimumReplicasAvailable

OldReplicaSets:  <none>

NewReplicaSet:   myweb-58d88b7dfb (3/3 replicas created)

Events:

  Type    Reason             Age    From                   Message

  ----    ------             ----   ----                   -------

  Normal  ScalingReplicaSet  3m15s  deployment-controller  Scaled up replica set                                                                                                         myweb-58d88b7dfb to 1

  Normal  ScalingReplicaSet  95s    deployment-controller  Scaled up replica set                                                                                                              myweb-58d88b7dfb to 2

  Normal  ScalingReplicaSet  41s    deployment-controller  Scaled up replica set                                                                                                              myweb-58d88b7dfb to 3


kubectl get pods

NAME                        READY   STATUS      RESTARTS   AGE

myweb-58d88b7dfb-6lj6k      1/1     Running     0          111s

myweb-58d88b7dfb-bxcj6      1/1     Running     0          3m31s

myweb-58d88b7dfb-wb7jj      1/1     Running     0          57s


#delete one pod, it maintains the no of pods

kubectl delete pod myweb-58d88b7dfb-6lj6k

pod "myweb-58d88b7dfb-6lj6k" deleted


kubectl get pods

NAME                        READY   STATUS      RESTARTS   AGE

myweb-58d88b7dfb-bxcj6      1/1     Running     0          4m1s

myweb-58d88b7dfb-k5dwk      1/1     Running     0          5s

myweb-58d88b7dfb-wb7jj      1/1     Running     0          87s