How to create Node.js Docker Image and Push to Docker Hub using Jenkins Pipeline

Creating a application on docker is a huge benefit because of its light weighted technology and security. Docker images are stored safely on docker hub . But how can we create docker images and push to docker hub automatically ? Its possible with none other than JENKINS

In this tutorial we will learn how to create docker images for node.js application and using Jenkins pushing it to docker hub.

Table of content

  1. What is Jenkins Pipeline?
  2. What is Node.js?
  3. Prerequisites
  4. How to Install node.js and node.js framework on ubuntu machine
  5. Create Node.js Application
  6. Create Docker file for Node.js application
  7. Push the code and configuration to GIT Repository
  8. Create Jenkins file for creating a docker image of Node.js application and pushing to Docker hub
  9. Configure Jenkins to Deploy Docker Image and Push to Docker Hub
  10. Conclusion

What is Jenkins Pipeline?

Jenkins Pipeline are group of plugins which helps to deliver a complete continuous delivery pipeline into Jenkins. Jenkins Pipeline plugin is automatically installed while installing the Jenkins with suggested plugins. This starts from building the code till deployment of the software right up to the customer. Jenkins pipeline allows you to write complex operations and code deployment as code with DSL language ( Domain specific language ) where we define a text file called “JENKINSFILE” which is checked into the repository.

  • Benefits of Jenkins pipeline
    • Pipeline can be written in code which can be more easier and gives more ability to review.
    • In case Jenkins stop you can still continue to write Jenkins file
    • With code capabilities you can allow waiting, approvals , stop and many other functionalities.
    • It support various extensions & plugins.

Related: the-ultimate-guide-getting-started-with-Jenkins-pipeline

What is Node.js?

Node.js is an open source JavaScript runtime environment. Now, what is JavaScript ? Basically JavaScript is a language which is used with other languages to create a web page and add some dynamic features such as roll over and graphics.

Node.js runs as a single process without wasting much of memory and CPU and never blocks any threads or process which is why its performance is very efficient. Node.js also allows multiple connections at the same time.

With the Node.js it has become one of the most advantage for JavaScript developer as now they can create any apps utilizing it as both frontend or as a backend.

Building applications that runs in the any browser is a completely different story than than creating a Node.js application although both uses JavaScript language.

Prerequisites

  • You must have ubuntu machine preferably 18.04 version + and if you don’t have any machine you can create a ec2 instance on AWS account
  • Docker must be installed on ubuntu machine.
  • Make sure you have git hub account and a repository created . If you don’t have follow here

How to Install node.js and node.js framework on ubuntu machine

  • Create a folder under opt directory
cd /opt
mkdir nodejs-jenkins
cd nodejs-jenkins
  • Install node.js on ubuntu machine
sudo apt install nodejs
  • Install node js package manager. This will install modules node_modules inside the same directory.
sudo apt install npm
  • Install Nodejs Express Web Framework and initialize it. This command will generate package.json file containing the project and metadata required details.
npm init

package.json which got created after initializing the Nodejs framework will have all the dependencies which are required to run. Let us add one dependency which is highly recommended.

npm install express --save

Create Node.js Application

  • Create a node.js application . So lets create a file main.js and name it as main.js on the same folder /opt/nodejs-jenkins
var express = require('express')    //Load express module with `require` directive
var app = express() 

//Define request response in root URL (/)
app.get('/', function (req, res) {
  res.send('Hello Welcome to Automateinfra.com')
})


app.listen(8081, function () {
  console.log('app listening on port 8081!')
})

Create Dockerfile for Node.js application

Docker file is used to create a customized docker images on top of basic docker image. It is a text file that contains all the commands to build or assemble a new docker image. Using docker build command we can create new customized docker images . Its basically another layer which sits on top of docker image. Using newly built docker image we can run containers in similar way.

This image has an empty alt attribute; its file name is image-43.png
  • Create docker file under the same folder/opt/nodejs-jenkins
FROM node:7              # Sets the base image

RUN mkdir -p /app
WORKDIR /app             # Sets the working directory in the container
COPY package.json /app   # copy the dependencies file to the working directory
RUN npm install          # Install dependencies
COPY . /app       # Copy the content of the local src directory to the working directory
EXPOSE 4200
CMD ["npm", "run", "start"]
  • Verify this Docker file on ubuntu machine by running the following command.
docker build .

Push the code and configuration to GIT Repository

  • Now we are ready with our code and configurations as below.
    • Dockerfile
    • main.js
    • package.json
    • node_modules

Now push all the code into GIT repository by performing below steps

  • Initialize your new repository in the same directory /opt/nodejs-jenkins
git init
  • Add the file in git repository using the command in the same directory /opt/nodejs-jenkins
git add .
  • Again check the status of git repository using the command in the same directory /opt/nodejs-jenkins
git status
  • Commit your changes in git repository using the command in the same directory /opt/nodejs-jenkins
 git commit -m "MY FIRST COMMIT"
  • Add the remote repository which we created earlier as a origin in the same directory /opt/nodejs-jenkins
git remote add origin https://github.com/Engineercloud/nodejs-jenkins.git
  • Push the changes in the remote branch ( Enter your credentials when prompted)
git push -u origin master
  • Verify the code on GIT HUB by visiting the repository link

Create Jenkins file for creating a docker image of Node.js application and pushing to dockerhub

  • Create a file and name it as Jenkins file your favorite editor and paste the below content.
    • Make sure to change the sXXXXXXX410/dockerdemo as per you’re docker hub username and repository name
node {
     def app 
     stage('clone repository') {
      checkout scm  
    }
     stage('Build docker Image'){
      app = docker.build("sXXXXX410/dockerdemo")
    }
     stage('Test Image'){
       app.inside {
         sh 'echo "TEST PASSED"' 
      }  
    }
     stage('Push Image'){
       docker.withRegistry('https://registry.hub.docker.com', 'git') {            
       app.push("${env.BUILD_NUMBER}")            
       app.push("latest")   
   }
}
  • Now push this file as well in github using git commands or simply create this file directly in the repository. Finally repository should something like this.

Configure Jenkins to Deploy Docker Image and Push to Docker Hub

  • Assuming you have Jenkins installed.
  • Now, Create a multibranch pipeline Jenkins Job and provide it a name as nodejs-image-dockerhub by clicking on new item and selecting multibranch pipeline on the Dashboard.
  • Now click on nodejs-image-dockerhub job and click on configure it with git URL and then hit save.
  • As we will connect with docker hub we would need to add docker hub credentials. Now we will click on Dashboard >>Manage Jenkins >>Manage credentials >> click on global >> Add credentials
  • Now go to Jenkins server and make sure Jenkins user is added in docker group
sudo groupadd docker
sudo usermod -a -G docker jenkins
service docker restart
  • Make sure Jenkins users has sudo permissions
sudo vi  /etc/sudoers

jenkins ALL=(ALL) NOPASSWD: ALL

Now we are all set to run our First Jenkins Pipeline. Click on Scan Multibranch pipeline job and then you will notice your branch name. Then click on Branch and then click on Build Now.

  • Now verify if Docker image has been successfully pushed to docker hub by visiting Dockerhub repository.

Conclusion

In this tutorial we covered what is Jenkins pipeline, what is node.js. Also we demonstrated how to create a docker file, Jenkins file and node.js application and pushed it into repository and finally using Jenkins created docker image and pushed it in docker hub.

This tutorial is in depth and very knowledgeable post if somebody wants to work on docker and Jenkins together for automations. Hope you liked it and if so please share it.