Open In App

Node.Js Application Deployment in Kubernetes with Jenkins CI/CD Pipeline

Last Updated : 24 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

As we know in the modern world we use Continuous Integration and Continuous Deployment for fast and and efficient delivery of our application to the market. Here in this Article, we are deep-diving into how Actually we can deploy Nodejs applications on Kubernetes with the help of Jenkins CI/CD.

Primary Terminologies

  • Node.js: This is a free, open-source cross-platform and JavaScript runtime environment that executes JavaScript code outside the browser.
  • Jenkins: It’s also free, Open-source CI/CD tools that automate software development processes like Build, Test, and deployment.
  • Docker: Docker is a platform that allows you to put all applications and their dependencies in standardized units called containers. These containers are lightweight and portable, allowing for continuity across environments (operating systems and hardware).
  • Kubernetes: It is open-source containerized orchestration tool that basically uses it for ease of deployment, auto-scaling, auto-healing, and monitoring purposes.
  • GitHub: It is a free and open-source version control system which is developed by Microsoft. That provides,
    • Storage for our codes
    • Continuously track our code.
    • the capability of sharing with another
    • project collaboration support

Step-by-Step Guide For Nodejs application Deployment in Kubernetes with Jenkins CI/CD pipeline

Step 1: Update System packages

sudo apt-get update

The reason for updating is that sometimes some packages of Docker are not working well, so for that reason we update them.

APT stands for Advanced Packaging Tool.

sudo apt-get update

Step 2: setup your development environment

# Verify installation
node -v
npm -v

First check, Node is installed or not through node-v command or node version. If it is not installed then write below command,

sudo apt-get install -y nodejs

Second check, npm is installed or not through npm-v command or npm version. If it is not installed then write below command,

sudo apt-get install -y npm

Here we use -y means automatically assign yes permission for automation instead of manually assigning.

node - v

Step 3: Creating a simple Nodejs application

creating new project directory and initializing with npm.

mkdir nodejs-app
cd nodejs-app
npm init -y

Installing express: Express is a web framework of Node.Js.

sudo npm install express
sudo npm install express

Creating a app.js file which contain the code of your Node.Js application.

// app.js
const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
res.send('Hello welcome to my node application');
});

app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
creating app

Creating one more file called test.js file that tailored for testing.

const assert = require('assert');

describe('Sample Test', function() {
it('should return true', function() {
assert.equal(true, true);
});
});

after creating above file write below command.

npm install --save-dev mocha

Once write this command then run 'npm init -y' command.

Package.json file Before test.js file.

{
"name": "nodejs-app",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "node app.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
}
}

package.json file after test.js file.

{
"dependencies": {
"express": "^4.19.2"
},
"name": "nodejs-app",
"version": "1.0.0",
"main": "app.js",
"devDependencies": {
"mocha": "^10.4.0"
},
"scripts": {
"test": "mocha"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": ""
}
package.json

Step 4: Creating Dockerfile.

nano Dockerfile

Add configuration scripts in the Dockerfile,

# Use the official Node.js image from the Docker Hub
FROM node:14

# Set the working directory inside the container
WORKDIR /usr/src/app

# Copy package.json and package-lock.json
COPY package*.json ./


# Install dependencies
RUN npm install
RUN chmod -R +x node_modules/.bin

# Copy the rest of the application code
COPY . .

# Expose the application port
EXPOSE 3000

# Command to run the application
CMD [ "node", "app.js" ]
dockerfile

After writing above scripts then Save and Exit nano:

  • Press Ctrl + O to write out (save) the file.
  • Press Enter to confirm the filename.
  • Press Ctrl + X to exit nano.

Step 5: Installing Docker package

sudo apt install -y Docker.io
install docker

Step 6: Building docker image.

docker build -t nodejs-app .
docker build

check images that are presents in the docker by using below command

docker images

Step 7: Run docker container

docker run  -p 3000:3000 nodejs-app

once you write above command then check your docker container status using below command

docker ps
docker ps

if you want to run on daemon mode then write below command

docker run -d -p 3000:3000 nodejs-app

Step 8: Push image to DockerHub

Once completed the above process then send your Docker image to DockerHub.

docker login
docker push romil/nodejs-app:latest

Here romil is username and nodejs-app is repository name with latest tag for identification.

Step 9: Jenkinsfile creation

nano Jenkinsfile

Add pipeline configuration scripts in the Jenkinsfile,

pipeline {
agent any
environment {
DOCKER_IMAGE = "nodejs-app"
}
stages {
stage('Checkout') {
steps {
checkout scm
}
}
stage('Build') {
steps {
script {
dockerImage = docker.build("${env.DOCKER_IMAGE}:${env.BUILD_ID}")
}
}
}
stage('Test') {
steps {
script {
dockerImage.inside {
// Set execute permissions for node_modules/.bin
sh 'chmod +x node_modules/.bin/mocha'
sh 'npm test'
}
}
}
}
stage('Deploy to Kubernetes') {
steps {
script {

kubeconfig(credentialsId: 'kubeconfig', serverUrl: 'https://127.0.0.1:32769') {
sh 'kubectl apply -f kubernetes-deployment.yml'
}



}
}
}
}
}

After writing above scripts then Save and Exit nano:

  • Press Ctrl + O to write out (save) the file.
  • Press Enter to confirm the filename.
  • Press Ctrl + X to exit nano.
save and exit

Step 10: Creating kubernetes-deployment.yaml file.

nano kubernetes-deployment.yaml

Add deployment configuration scripts in the kubernetes-deployment.yaml file,

apiVersion: apps/v1
kind: Deployment
metadata:
name: nodejs-app
spec:
replicas: 3
selector:
matchLabels:
app: nodejs-app
template:
metadata:
labels:
app: nodejs-app
spec:
containers:
- name: nodejs-app
image: nodejs-app:latest
ports:
- containerPort: 3000
---
apiVersion: v1
kind: Service
metadata:
name: nodejs-app-service
spec:
type: LoadBalancer
selector:
app: nodejs-app
ports:
- protocol: TCP
port: 80
targetPort: 3000
nano

After writing above scripts then Save and Exit nano:

  • Press Ctrl + O to write out (save) the file.
  • Press Enter to confirm the filename.
  • Press Ctrl + X to exit nano.

Step 11: setup Kubernetes

installing latest minikube stable x86-64 Linux variant, Installation as per your requirement.

Follow Minikube for more detailed guidance.

curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64
sudo install minikube-linux-amd64 /usr/local/bin/minikube && rm minikube-linux-amd64
minikube start
minikube status

Step 12: Jenkins installation

 sudo apt update
sudo apt upgrade

update: It is basically used for refreshing list of available software packages and versions but it not download or install anything new by itself.

upgrade: It is installing newer version of software packages that are available on your system.

sudo apt update
sudo apt install openjdk-11-jdk -y
install java

We need to install openjdk for Jenkins after that run below commands

curl -fsSL https://pkg.jenkins.io/debian/jenkins.io-2023.key | sudo tee /usr/share/keyrings/jenkins-keyring.asc > /dev/null
echo deb [signed-by=/usr/share/keyrings/jenkins-keyring.asc] https://pkg.jenkins.io/debian binary/ | sudo tee /etc/apt/sources.list.d/jenkins.list > /dev/null

finally run below commands for jenkins installation.

sudo apt update
sudo apt install jenkins -y

Here we use -y means automatically assign yes permission for automation instead of manually assigning.

sudo systemctl start jenkins
sudo systemctl enable jenkins
sudo spt update

once you write above command then open the browser and write,

https://localhost:8080

Now Jenkins UI(First page) will display but it require the initialAdminPassword so that reason you need to write below command that will show the password.

sudo cat /var/lib/jenkins/secrets/initialAdminPassword
unlock jenkins
getting started
jenkins ready


Step 9: Configuring Jenkins

Once you done personal login or as a guest login, you will see the Jenkins Dashboard In that We need to install some necessary plugins: Go to Manage Jenkins > Manage Plugins. And installing following plugins:

  • Docker Pipeline
  • Kubernetes
  • Git
Configuring Jenkins
Docker Pipeline

Step 10: Create a New Pipeline Job

Create New Item:

Create a new jobs or new item from left-hand side menu on the Jenkins Dashboard.

Enter Job Details:

Name: Enter a name for your new job (e.g., NodeJS-Pipeline).

  • Type: Select Pipeline.
  • Click OK to proceed.
Enter Job Details

Step 11: Configure the Job

General Configuration:

Description: Optionally, provide a description for the job to explain what this pipeline does.

General Configuration

Pipeline Configuration:

  • Definition: Choose Pipeline script from SCM.
  • SCM: Select Git.
  • Repository URL: Enter your Git repository URL (e.g., https://github.com/your-username/your-repo.git).
Pipeline Configuration

Credentials:

If your repository requires authentication, you need to add credentials.

  1. Credentials: Click Add to add your credentials (e.g., GitHub username and password, or personal access token).
  2. Kind: Choose the appropriate kind (e.g., Username with password or SSH Username with private key).
  3. Scope: Set to Global.
  4. Username: Enter your GitHub username.
  5. Password: Enter your GitHub password or personal access token.

Click Add to save.

Credentials

Branch Specifier:

By default, this is set to */master. If you are using a different branch, update it accordingly (e.g., */main).

Script Path:

Specify the path to your Jenkinsfile if it's not in the root directory of your repository. By default, it is set to Jenkinsfile.

Adding Pipeline syntax:

click on pipeline syntax and setup the kubeconfig.

you need to add credentials for kubeconfige,

  1. Credentials: Click Add to add your credentials.
  2. Kind: Choose the appropriate kind (e.g., Secret text).
  3. Scope: Set to Global.
  4. Secret: Here you need to add the kubeconfig data which is present at .kube/config file in your local system.

if you want to check your config file's data then write below command,

ls -la

After that you can see many files from that you move to config file using below command,

cd .kube/config 
cd .kube/config
Dashboard
Set the configurations

Save Configuration:

Scroll down and click Save to save the job configuration.

Save Configuration

Build the Job:

After saving, you will be redirected to the job's main page.

Click on Build Now on the left-hand side to trigger the pipeline.

Build the Job

Monitor the Build:

You can monitor the progress of the build.

Click on the build number to see the console output and logs.

Monitor the Build
build the pipeline

You can check pipeline overview in your .

Jenkins completed

Conclusion

This article provides detailed instructions on deploying a Node.js application to Kubernetes using the Jenkins CI/CD pipeline. It includes designing the development environment, building the Node.js project, Dockerizing the project, and pushing Docker images to DockerHub. It then explains setting up Jenkins for continuous integration and deployment, including pipeline configuration and integration with Kubernetes for automated deployment This well-designed approach ensures smooth deployment, automated deployment and scaling of applications in a Kubernetes environment in.


Next Article

Similar Reads