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.
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.
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
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 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": ""
}
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" ]
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
Step 6: Building docker image.
docker build -t nodejs-app .
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
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.
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
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
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 install openjdk-11-jdk -y
We need to install openjdk for Jenkins after that run below commands
curl -fsSL https://pkg.origin.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.origin.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
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
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
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.
Step 11: Configure the Job
General Configuration:
Description: Optionally, provide a description for the job to explain what this pipeline does.
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).
Credentials:
If your repository requires authentication, you need to add credentials.
- Credentials: Click Add to add your credentials (e.g., GitHub username and password, or personal access token).
- Kind: Choose the appropriate kind (e.g., Username with password or SSH Username with private key).
- Scope: Set to Global.
- Username: Enter your GitHub username.
- Password: Enter your GitHub password or personal access token.
Click Add to save.
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,
- Credentials: Click Add to add your credentials.
- Kind: Choose the appropriate kind (e.g., Secret text).
- Scope: Set to Global.
- 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
Save Configuration:
Scroll down and click Save to save the job 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.
Monitor the Build:
You can monitor the progress of the build.
Click on the build number to see the console output and logs.
You can check pipeline overview in your .
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.
Similar Reads
DevOps Tutorial DevOps is a combination of two words: "Development" and "Operations." Itâs a modern approach where software developers and software operations teams work together throughout the entire software life cycle.The goals of DevOps are:Faster and continuous software releases.Reduces manual errors through a
7 min read
Introduction
What is DevOps ?DevOps is a modern way of working in software development in which the development team (who writes the code and builds the software) and the operations team (which sets up, runs, and manages the software) work together as a single team.Before DevOps, the development and operations teams worked sepa
10 min read
DevOps LifecycleThe DevOps lifecycle is a structured approach that integrates development (Dev) and operations (Ops) teams to streamline software delivery. It focuses on collaboration, automation, and continuous feedback across key phases planning, coding, building, testing, releasing, deploying, operating, and mon
10 min read
The Evolution of DevOps - 3 Major Trends for FutureDevOps is a software engineering culture and practice that aims to unify software development and operations. It is an approach to software development that emphasizes collaboration, communication, and integration between software developers and IT operations. DevOps has come a long way since its in
7 min read
Version Control
Continuous Integration (CI) & Continuous Deployment (CD)
Containerization
Orchestration
Infrastructure as Code (IaC)
Monitoring and Logging
Microsoft Teams vs Slack Both Microsoft Teams and Slack are the communication channels used by organizations to communicate with their employees. Microsoft Teams was developed in 2017 whereas Slack was created in 2013. Microsoft Teams is mainly used in large organizations and is integrated with Office 365 enhancing the feat
4 min read
Security in DevOps