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.

How to Setup Docker step by step on Ubuntu machine

I am sure most of you have installed lots of application on single Virtual machine and faced challenges while maintaining them and facing memory or system issues and things become more ugly when you troubleshoot each application to fix the problem.

What should one do ? Cannot we isolate our apps so that we can easily find the problem ? Cant one app which is not working should be down and others should run as it is ? Yes, that correct that’s very much possible with docker and containers. They provide you isolated environment and are your friend for deploying many applications with each taking its own container.

In this tutorial, you’ll install and use Docker on Ubuntu 18.04. You’ll then work with containers , images and push an image to a Docker Repository. So lets get started.

Table of Content

  1. What is Docker ?
  2. Prerequisites
  3. How to Install Docker on ubuntu machine
  4. How to run Docker commands using Non Root user
  5. Working with docker images and containers
  6. Pushing docker images to docker hub
  7. Conclusion

What is Docker ?

🐟Docker is an open source tool for developing , shipping and running applications. It has ability to run applications in loosely isolated environment using containers. Docker is an application which helps in management of containers in a very smooth and effective way. In containers you can isolate your applications. Docker is quite similar to virtual machine but it is light weighted and can be ported easily.

Containers are light weighted as they are independent of hypervisors load and configuration. They directly connect with machines ie. hosts kernel.

Prerequisites

  • Ubuntu machine preferably 18.04 version + , 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
  • An account on Docker Hub if you wish to create your own images and push them to Docker Hub.

You may incur a small charge for creating an EC2 instance on Amazon Managed Web Service.

How to Install Docker on Ubuntu 18.04 LTS

sudo apt update
  •  Install some required packages for apt so that it can use over https
sudo apt install apt-transport-https ca-certificates curl software-properties-common
  • Add the GPG key for the official Docker repository to your system
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key --keyring /etc/apt/trusted.gpg.d/docker.gpg add -
  • Add the Docker repository to APT sources
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
sudo apt update
  • Now, Install docker
sudo apt-get update && sudo apt-get install -y \
  containerd.io=1.2.13-2 \
  docker-ce=5:19.03.11~3-0~ubuntu-$(lsb_release -cs) \
  docker-ce-cli=5:19.03.11~3-0~ubuntu-$(lsb_release -cs)
  • Docker should be started now, verify the status and version of docker.
  • Check the docker version
  • Docker is successfully installed and now you are reading to work with docker and containers.

How to run Docker commands using Non Root user

To enable users other than root and users with sudo access to be able to run Docker commands:

  1. Create the docker group
groupadd docker
  1. Add the users that should have Docker access to the docker group
sudo usermod -a -G docker jenkins   # To add Jenkins user to docker group
sudo usermod -a -G docker user1     # To add user1 to docker group
  1. Restart the docker service by following command
# The UNIX socket /var/run/docker.sock is now writable by members of the docker group.

service docker restart 

Working with docker images and containers

Most important part in docker is docker images which contains your code , environment to run it and several parameters. Docker images are stored on docker repository known as docker hub , though you can store it on your local machine as well.

  • To pull docker image ubuntu on your system
docker pull ubuntu
  • Now check the downloaded image.
docker images
  • In this tutorial we are providing the demo so we will use the same pulled docker image and run our first container , but you can update the same image with more configurations or as per requirements as well.
  • Run the first container
docker run -it ubuntu                # Here i and t provides you interactive shell access and ubuntu is image name
  • We used exit to come out of shell , so container has been exited. To check the containers details.
 docker ps -a

Pushing docker images to docker hub

  • Firstly you will need to login to docker hub with your credentials and then login.
docker login -u docker-registry-user
  • Before you push your docker image to docker hub , its highly recommended to to tag your image with your docker hub username .
docker tag ubuntu:latest  <dockerhub-username>/ubuntu:latest
  • After successful login in docker hub now push your docker image
docker push <dockerhub-username>/ubuntu:latest

Conclusion

In this tutorial you installed Docker, worked with images and containers, and pushed a image to Docker Hub

Hope this tutorial will help you in understanding and setting up Docker on ubuntu machine. Please share with your friends.