fbpx
bg_image
Comments Off on Simplified Application Deployment in Kubernetes Cluster with Jenkins Pipeline
Posted By

Muhammad Aqib

Avatar Of Muhammad Aqib

Application Deployment in Kubernetes Cluster


In the world of software development, automation is key to efficiency and reliability. Kubernetes with Jenkins Pipeline has emerged as a leading container orchestration platform, enabling developers to manage containerized applications seamlessly.

In this blog post, we will explore how to streamline the Application Deployment in Kubernetes Cluster with Jenkins Pipeline., Docker, and Jenkins Pipeline. We'll walk through the steps of creating a Docker image, pushing it to DockerHub, and deploying it to a Minikube cluster using Jenkins Pipeline.


Deployment On Jenkins Pipeline, Application Deployment In Kubernetes Cluster, Jenkins Pipeline
Application Deployment In Kubernetes Cluster

Setting up the Environment:

Before getting into the process, let's ensure our environment is properly configured. Make sure you have Docker, Minikube, and Jenkins installed and configured on your system. Additionally, you'll need to install the necessary plugins in Jenkins to enable Docker and Kubernete integration. If you don’t have setup environment go to this link Click here and setup environment first.

Create GitHub Repository:

  • Create a new Github repository into your personal account.
  • Click on settings tab and then click on Webhooks.
  • Add webhooks in your repository like this {here you provide your Jenkins url}/github-webhook/

Create Jenkins Pipeline:

  • Go to Jenkins Dashboard and Click on New Item.
  • Select a Pipeline and give it a name of your choice, then click on the OK button.
  • To configure the Pipeline Click on GitHub project checkbox and paste your GitHub repository url in the Project url text field.
  • For Building Triggers section, click on the GitHub hook trigger for GITScm polling checkbox.
  • In Pipeline section select Pipeline script from SCM from the Definition dropdown.
  • Paste your GitHub repository url that you created above into the Repository URL text field.
  • Select GitHub Credentials from the Credentials dropdown field. If you do not have credentials, click on the Add button, select Jenkins, paste your GitHub username in the Username text field, GitHub password in the Password field, provide Id and Description, then click on the Add button.
  • There is Branches to build section, provide a branch name where you will push code and click on the Save button.
  • Goto Jenkins Dashboard, Click on Manage Jenkins -> Credentials -> global and create credential for Docker hub.
  • Click on the Add Credentials button, select Secret text option from kind dropdown list, paste your docker hub Access Token in the Secret field, provide ID and Description, then click on the Create button.
  • To create a kubeconfig file in your Jenkins server, Make a copy of your Minikube cluster`s kubeconfig file in your local system and create a new credential for the config file in the jenkin server.
  • Click on Add Credentials button, select Secret file option from the kind dropdown list, Choose a file of kubeconfig from your local system, provide an ID and Description, then click on the Create button.
  • Create a Kubernetes cloud in your Jenkins server to connect with your Minikube cluster in jenkins. Before creating a cloud for, make sure you have installed plugin on the Jenkins server.
  • Goto Jenkins Dashboard, Click on Manage Jenkins -> Clouds -> New cloud, to create a new cloud provide a name of your cloud in cloud name text field , select Kubernetes and click on the Create button.
  • Click on Kubernete Cloud details, select a credential for your kubeconfig file that you created above from the Credentials dropdown and click on Test Connection button. If connection is successful, then click on the Save button.

Create a simple HelloWorld Application in NodeJs:

make a new folder named jenkins-deploy-nodejs in your local system. In the jenkins-deploy-nodejs folder, run the following command to create a simple helloworld nodejs application:

				
					npm install express nodemon
				
			

Build an index.js file and paste the following code:

				
					var express = require('express');
var app = express();
app.get('/', function(req, res){
   res.send(" Welcome to Hello world App! ");
});
app.listen(3000, () => {
    console.log("App is running on port 3000")
});
module.exports = app

				
			

Open package.json file and paste the following code in script object:
"start": "nodemon index.js"
Test application in your local system with the following command:

				
					npm run start
				
			

Create Docker File:

After creating a Dockerfile and paste the following code:

				
					FROM node:latest
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install 
COPY . .
EXPOSE 3000
CMD ["node", "index.js" ]

				
			

Create Kubernetes Manifest files:

Create a deployment.yml file and paste the following YAML snippet:

				
					---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: helloworld-app
spec:
  replicas: 2
  selector:
    matchLabels:
      app: helloworld-app
  template:
    metadata:
      labels:
        app: helloworld-app
    spec:
      containers:
      - name: helloworld-app
        image: <your docker hub image url>
        imagePullPolicy: Always
        ports:
        - containerPort: 3000

				
			

Form a service.yml file and paste the following YAML snippet:

				
					---
apiVersion: v1
kind: Service
metadata:
  name: node-app-service
spec:
  selector:
    app: helloworld-app
  ports:
    - protocol: TCP
      port: 80
      targetPort: 3000 
      nodePort: 31258            /* will allocate a port from a range (default: 30000-32767)*/
  type: NodePort

				
			

Create Jenkins Pipeline:

Create a Jenkinsfile and paste the following Jenkins snippet. Ensure you replace github repository url and credentials Id with your actual repository Url and credentials Id in the Git Checkout Stage, and add your actual dockerhub credentials Id and username in the Push image to Docker Hub Stage.

				
					pipeline {
    agent any
    stages{
        stage('Git CheckOut'){
            steps{
                cleanWs()
                checkout scmGit(branches: [[name: '*/main']], extensions: [], userRemoteConfigs: [[credentialsId: '<your github credential id>', url: '<your github repository url>']])
            }
        stage('Build docker image'){
            steps{
                script{
                    sh 'docker build -t helloworld/node-app:latest .'
                }
            }
        }      
        stage('Push image to Docker Hub'){
            steps{
                script{
                    withCredentials([string(credentialsId: '<your dockerhub credential id>', variable: 'dockerpwd')]) {
                        sh 'docker login -u <your dockerhub user name> -p ${dockerpwd}'
                    }
                    sh 'docker push helloworld/node-app:latest'
                }
            }
        }        
        stage('Deploy to k8s'){
            steps{
                script{
                    kubeconfig(credentialsId: 'mykubeconfig', serverUrl: 'https://172.31.54.73:8443') {
                        sh 'kubectl apply -f deployment.yml'
                        sh 'kubectl rollout restart -f deployment.yml'
                        sh 'kubectl apply -f service.yml'
                    }
                }
            }
        }

				
			

The Jenkinsfile will create a Jenkins Pipeline with four stages:

  • Git CheckOut
  • Build docker image
  • Push image to Docker Hub
  • Deploy to k8s

Git CheckOut Stage:

This Jenkins Pipeline stage will use Github repository url as the GitHub repository. It will pull and scan all the files in this GitHub repository.

Build docker image Stage:

This Jenkins Pipeline stage will use to build a Docker image using the provided Dockerfile named helloworld/node-app:latest.

Push image to Docker Hub Stage:

This Jenkins Pipeline stage will push the helloworld/node-app:latest Docker image to a Docker registry, such as Docker Hub.

Deploy to k8s Stage:

This Jenkins Pipeline stage applies the Kubernetes deployment YAML file to deploy the Docker image to the Kubernetes cluster.

Push all the application files to your GitHub Repository. After pushing the files on GitHub repository goto your Jenkins pipeline and check the status of pipeline. If pipeline status is success goto aws ec2 instance console and copy the public ip of that instance in which you installed Minikube. Paste this public ip with port 31258 in the browser and check application result.

Conclusion:

We’ve demonstrated how to streamline the deployment process using Kubernetes, Docker, and Jenkins Pipeline. By automating the steps of creating a Docker image, pushing it to DockerHub, and deploying it to a Minikube cluster, developers can save time and ensure consistency in their deployment workflow. With the power of automation, managing containerized applications in Kubernetes becomes more efficient and reliable.