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.

The Ultimate Guide for beginners: Getting started with Git commands

One of the best version control that I have used so far for managing multiple repositories and files in a smooth and distributed . The open source tool which we are talking here is Git the best control version. Please follow along to know the more on on how to work with Git , setup Git on ubuntu and windows machine & best commands and setup guide.

This tutorial is going to add a lot of valuable knowledge on Git in your pockets, Stay tuned !!

Table of Content

  1. Getting Started with Git
  2. Create a new git repository using graphical interface on GitHub
  3. Creating a new git repository using command line on ubuntu machine
  4. Getting Started with Git Commands for beginners
  5. Summary

Getting Started with Git

What is Repository ?

Repository is a place where you keep all your source code it could be project wise or you can create it for a particular technology or you can create even for a single file, it all depends on you and your requirement. Its always a good idea to provide the name of repository according to work which you are going to do. There are some cloud based source code tools which allows you to create your repositories such as bitbucket , GitLab, GitHub ,Subversion , SVN and Mercurial etc. where you can create your own repositories.

Create a new git repository using graphical interface on GitHub

  • Before we create the first repository make sure you have GitHub account created . If you don’t have please click here and Sign up.
  • If you have access to it then open your browser and go to GitHub website from here and click on Sign in.
  • Now click on New button to create a new repository
  • Now, provide a suitable name of the repository and you may keep it as public open to world if you wish people can see your code else keep it private. We are keeping as public as this is a demo tutorial and finally select create repository.
  • Now your repository is ready to be used. Please make sure you below steps which we will use later in this tutorial.
    • create a new repository on the command line and
    • push an existing repository from the command line

Creating a new git repository using command line on ubuntu machine

  • 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
  • Recommended to have 4GB RAM
  • At least 5GB of drive space
  • SSH into your ubuntu machine
  • Now create a folder under /opt directory
cd /opt
mkdir git-demo
cd git-demo/
  • Initialize your new repository
git init
  • Create a file inside the same directory using the command
echo "My first change" > adding-new-file.txt
  • Now check the status of git repository using the command
git status
  • Add the file in git repository using the command
git add .
  • Again check the status of git repository using the command
git status
  • Commit your changes in git repository using the command
 git commit -m "MY FIRST COMMIT"
  • Add the remote repository which we created earlier as a origin.
git remote add origin https://github.com/Engineercloud/git-demo.git
  • Push the changes in the remote branch ( Enter your credentials when prompted)
git push -u origin master
  • Now Verify if the text file which we created is present in repository

Getting Started with Git Commands for beginners

Here we will work with most important commands of Git. Let us work with same directory which we created earlier.

cd /opt
mkdir git-demo
cd git-demo/
This image has an empty alt attribute; its file name is image-300.png
  • Check the status of the repository
git status
  • Add a file in the directory and run the command
echo "Adding new file again" > second_file.txt
  • Now check the status of repository again, it should show untracked files as they are added in repo yet
  • Add files in repository by using command
git add .
  • Check the status of git again
  • To check the status of git with short status
git status -s
  • Now edit the file which we created and check the status .
    • You will notice that there will be two things one is changes to be committed because we already added them using git add.
    • Also you will notice changes not staged for commit because we recently edited our file but didn’t add it.
echo "I am editing my second file " >> second_file.txt
  • Add the file in repository which we modified.
git add .

git status
  • Although we know that we modified a line and checked the status , but if you want to check the difference between the two you can use command.
git diff        # Git diff provides the information which is not committed
  • Also you can check the committed change so far by using the command.
git diff --cached      # Git diff --cached provides the information what is committed
  • Commit all your changes
git commit -m "Committing all my changes" .       # m here means message
  • To delete your staged file properly, that is how to delete those files which are already committed
git rm second_file.txt  # This command will also remove the file from the directory
  • If you wish to delete your staged file properly but keep the file in the directory for future use
git rm --cached second_file.txt  # This command will not remove the file from the directory
  • To check history of your commits in a git repos use a command
git log  # The command gives the list of commits in reversal order which is expected.
  • To check history of your commits with the difference between each commit we use -p flag
 git log -p -2    # -p stands for patch that is difference and 2 here is last 2 commits
  • There are some more commands to view the commits in more presentable way , lets checkout.
git log --pretty=format

git log --pretty=format:"%h %s" --graph

Summary

You should now have a very sound knowledge of what Git is , how to create Git repository using graphical mode as well as using command line tool . Also we discussed how to work with Git repositories using different commands. This tutorial consists of all the practical’s which were done on our lab server with lots of hard work and efforts.

Please share the word if you like it and hoping you get benefit out of this tutorial.

You can also visit : Introduction-to-git-a-version-control-getting-started-with-git-step-by-step