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

If you plan to run your node.js application, nothing could be better than running on the docker and safely storing it on Dockerhub.

Running an application on docker is a huge benefit because of its light-weighted technology and security. Docker images are stored safely on the dockerhub

In this tutorial, you will learn how to create a docker image for node.js applications and push it to dockerhub using the Jenkins pipeline.

Let’s get started.

Join 50 other followers

Table of Content

  1. What is Jenkins Pipeline?
  2. What is Jenkinsfile?
  3. What is node.js server-side javascript?
  4. Prerequisites
  5. How to Install node.js and node.js framework on ubuntu machine
  6. Creating Node.js Application
  7. How to create dockerfile for Node.js application
  8. Pushing all the code to GIT Repository: Git Push
  9. Creating Jenkinsfile to run docker image of Node.js application
  10. Configure Jenkins to Deploy Node.js Docker Image and Push to Dockerhub
  11. Conclusion

What is Jenkins Pipeline?

Jenkins Pipeline uses a group of plugins that help deliver a complete continuous delivery pipeline starting from building the code till deployment of the software right up to the customer.

Jenkins Pipeline plugin is automatically installed while installing the Jenkins with suggested plugins and allows you to write complex operations and code deployment as code using DSL language ( Domain-specific language).

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

What is Jenkinsfile?

Jenkins Pipelines uses a text file called Jenkinsfile, which is checked into the repository. You define each stage and steps that need to be executed, such as building and compiling code to deploy in respective environments.

Jenkinsfile allows you to define steps in code format, which is easier and gives more ability to review. In case Jenkins stops, you can still continue to write Jenkinsfile. It can hold, wait, approve, stop Jenkins job and many other functionalities.

What is node.js server-side javascript?

JavaScript is a language used with other languages to create a web page add some dynamic features such as rollover or graphics, and Node.js is an open-source JavaScript runtime environment.

Node.js performs well as it contains only a single process without wasting much memory, CPU and never blocks any threads or processes and furthermore allows multiple connections simultaneously.

Node.js allows JavaScript developers to create apps in the front and backend.

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 and Jenkins 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

Now that you know what is node.js and what are benefits of having node.js. In this section, let’s dive into how to Install node.js and node.js frameworks on ubuntu machines.

  • Log in to the Ubuntu machine using your favorite SSH client.
  • Now, create a folder named nodejs-jenkins under opt directory in the ubuntu machine.
cd /opt
mkdir nodejs-jenkins
cd nodejs-jenkins
  • Now install node.js on ubuntu machine using the below command.
sudo apt install nodejs
  • Next, Install node.js package manager. Installing node.js package manager allows to install modules node_modules inside the same directory.
sudo apt install npm
  • Further install Nodejs express Web Framework and initialize it. This command will generate package.json file containing the project, all the dependencies and metadata details that will be used to create a project and further application.
npm init
  • Further, add one dependency which is required by node.js application.
npm install express --save

Creating Node.js Application

Now that you have successfully installed the node.js application and framework required to create a node.js application. Let’s create a node.js application.

Assuming you are still logged into the ubuntu machine.

  • Firstly, create a file named main.js in the /opt/nodejs-jenkins directory and copy/paste the below code.
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!')
})

How to create dockerfile for Node.js application

Previously you created a node.js application, which is great, but to deploy node.js on docker, you will need to create a dockerfile. Docker file creates customized docker images on top of docker images.

After creating the dockerfile, you can use the docker build command to create a new customized docker image.

Running docker containers using dockerfile
Running docker containers using dockerfile

Let’s jump in and create a dockerfile for the node.js application.

  • Create a file named dockerfile in the same /opt/nodejs-jenkins directory and copy/paste the below content.
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"]
  • Next, to create a node.js docker image using above dockerfile run the below command on ubuntu machine.
docker build .
Building the docker image using dockerfile
Building the docker image using dockerfile

Pushing all the code to GIT Repository: Git Push

Earlier, you created the node.js application and manually built the docker image to confirm that your code is absolutely fine and works. Let’s push all the files and code in the Git repository using various commands so that later Jenkins can use these files and build the application.

  • Now your directory /opt/nodejs-jenkins should have look as below.
checking the content of the directory
checking the content of the directory
  • Initialize a new repository in the same directory /opt/nodejs-jenkins by running git init command.
git init
  • Add all the file in git repository using the below command in the same directory /opt/nodejs-jenkins
git add .
  • Now, check the status of git repository with below command. If there are any errors they will appear else you are good to go to the next step.
git status
  • Commit your changes in git repository using the git commit command in the same directory /opt/nodejs-jenkins
 git commit -m "MY FIRST COMMIT"
  • Add the remote repository that you already had as a origin by running git remote add command.
git remote add origin https://github.com/Engineercloud/nodejs-jenkins.git
Adding the remote origin
Adding the remote origin
  • Finally push the changes in the remote branch . Once prompted specify your credentials.
git push -u origin master
Pushing the code in git repository
Pushing the code in git repository
  • Now, verify the code on github by navigating to the repository link.
Verifying the git repository
Verifying the git repository

Creating Jenkinsfile to run docker image of Node.js application

Let’s quickly jump into the creation of Jenkinsfile to run docker image of Node.js application to deploy an application using Jenkins.

  • Create a file named Jenkinsfile in the same /opt/nodejs-jenkins directory and copy/paste the below content. Make sure to change the sXXXXXXX410/dockerdemo as per you’re dockerhub 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 the Jenkinsfile as well in github in the same repository that you used earlier. Now, your repository should look something like below.
Pushing the Jenkinsfile in the git repository
Pushing the Jenkinsfile in the git repository

Configure Jenkins to Deploy Node.js Docker Image and Push to Dockerhub

Now that you have all the code, including Jenkinsfile, in the Github repository and deploy the node.js application on docker using Jenkinsfile, you need to create a Jenkins Job. Let’s configure Jenkins by creating a new multi-branch pipeline Jenkins Job.

  • Create a new multibranch pipeline Jenkins Job named nodejs-image-dockerhub by clicking on new item and selecting multibranch pipeline on the Dashboard.
Creating a new multibranch pipeline Jenkins Job
Creating a new multibranch pipeline Jenkins Job
  • Now click on nodejs-image-dockerhub job and click on configure it with git URL and then hit save.
Configuring the Git URL in the Jenkins
Configuring the Git URL in the Jenkins
  • To connect to dockerhub you would need to add dockerhub credentials by clicking on the Dashboard ➔ Manage Jenkins ➔ Manage credentials ➔ click on global ➔ Add credentials.
Adding the dockerhub credentials in the Jenkins
Adding the dockerhub credentials in the Jenkins
  • Next, on Jenkins server add Jenkins user in the docker group so that Jenkins user has access to run docker commands.
sudo groupadd docker
sudo usermod -a -G docker jenkins
service docker restart
  • Further, make sure Jenkins users has sudo permissions by running below commands.
sudo vi  /etc/sudoers
jenkins ALL=(ALL) NOPASSWD: ALL
  • Now you are ready to run your first jenkins job. click on scan Multibranch pipeline job that will scan your branches in the repository. Then click on Branch and then click on Build Now.
Running the Jenkins Job
Running the Jenkins Job
  • The Jenkins job is completed successfully. Lets verify if Docker image has been successfully pushed to dockerhub by visiting Dockerhub repository.
Checking the docker image in dockerhub

Conclusion

In this tutorial, you learned what the Jenkins pipeline is, node.js is, and how to create a dockerfile, Jenkins file, and node.js application. Finally, you pushed the docker image to dockerhub using Jenkins.

So now you know how to deploy the node.js application on docker; which application do you plan to deploy next?

Advertisement

How to Install Docker ubuntu step by step

If you want to deploy multiple applications in an isolated environment, consider using Docker and containers where applications have their own container.

In this tutorial, you’ll install the Docker ubuntu machine. You’ll then work with docker containers and docker images and push an image to a Docker Repository. So let’s get started.

Let’s dive in.

Join 50 other followers

Table of Content

  1. What is Docker?
  2. Prerequisites
  3. How to Install Docker on Ubuntu 18.04 LTS
  4. How to run Docker command using Non-Root user (run docker commands without sudo)
  5. Working with docker command ( docker pull command, docker ps, docker image)
  6. Tag Docker image using docker tag and push docker image to docker hub
  7. Conclusion

What is Docker?

Docker is an open-source tool for developing, shipping, and running applications. It has the ability to run applications in a loosely isolated environment using containers. Docker is an application that helps manage containers in a very smooth and effective way. In containers, you can isolate your applications. Docker is quite similar to a virtual machine, but it is lightweight and easily ported.

Containers are light weighted as they are independent of hypervisors load and configuration. They directly connect with machines, i.e., the host’s kernel.

What is Docker?
What is Docker?

Prerequisites

  • Ubuntu machine preferably 18.04 version +, if you don’t have any machine you can create an ec2 instance on AWS account
  • Recommended to have 4GB RAM and 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

Let’s kick off this tutorial by installing docker on ubuntu. Installing docker on the ubuntu machine is a straightforward task. The Docker installation package is available in the official Ubuntu repository may not be the latest version.

This tutorial will install Docker from the official Docker repository to ensure you get the latest version. To do that, add a new package source, add the GPG key from Docker to ensure the downloads are valid, and then install the package.

  • Login to your Ubuntu machine using your favorite SSH client.
  • First, update your existing list of packages by running the below command
sudo apt update
  • Install the below prerequisites software so that apt uses packages over the https protocol. The apt transport software allows your machine to connect with external repositories over HTTPS or HTTP over TLS.
sudo apt install apt-transport-https ca-certificates curl software-properties-common

  • Next, add the GPG key for the official Docker repository to your system. This key builds the trust of your machine with the docker official repository.
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

  • Now, add the Docker repository to APT sources so that you can install the docker installation package.
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu bionic stable"

  • Next, update the package database with the Docker packages from the newly added repo using the following command.
sudo apt update
  • Finally, Install the docker on the ubuntu machine using the apt install command.
sudo apt install docker-ce

  • Docker should be started by now; verify the status and version of docker by using service docker status the command.
Checking the docker service using service docker status command
Checking the docker service using the service docker status command

How to run Docker command using Non-Root user (run docker commands without sudo)

The docker command can only be run by the root user or by a user in the docker group, automatically created during Docker’s installation process. If you attempt to run the docker command without prefixing it with sudo or without being in the docker group, it will give you a permission denied error message.

  • To enable users other than root or to run docker commands without sudo, first create the docker group using the groupadd docker command.
groupadd docker
  • Next, add the users in the docker group that you created earlier and can run Docker commands.
sudo usermod -aG docker jenkins   # To add Jenkins user to docker group
sudo usermod -aG docker user1     # To add user1 to docker group
sudo usermod -aG docker ubuntu    # To add ubuntu user  to docker group
  • Restart the docker service by service docker restart command.
service docker restart 
  • Check the docker version by running the below command.
docker version

Your docker commands should now run succesfully now without giving any permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock like this, if you continue to get this message make sure to logout and login back on your machine.

Verifying the docker version using docker version command
Verifying the docker version using the docker version command

Working with docker command ( docker pull command, docker ps, docker image)

The most important part of docker is to run several docker commands such as docker pull which fetches docker images that contain your code, the environment to run it, and several parameters. Docker images are stored on the Docker repository known as the docker hub, though you can also store them on your local machine.

Docker architecture
Docker architecture
  • Use the docker pull command to pull the docker image on your ubuntu machine.
docker pull ubuntu
Pulling an image from docker repository using docker pull command on ubuntu machine
Pulling an image from docker repository using docker pull command on ubuntu machine
  • Now check the downloaded image on your ubuntu machine and run the docker images command.
docker images
Checking all docker images in the system
Checking all docker images in the system
  • Now, run the first docker container by using the below command.
docker run -it ubuntu # Here i,t provides you interactive shell access and ubuntu is image name
Running docker container using docker run command
Running docker container using docker run command.
  • To check all container details ( Exited, running, etc.), run the docker ps -a command.
 docker ps -a
Checking details of all container details
Checking details of all container details

Tag Docker image using docker tag and push docker image to docker hub

Now, let’s learn how to push the docker image to the docker hub. You need a docker hub account to push the docker image to the docker hub.

Assuming you are still logged into the Ubuntu machine using the SSH client.

  • Login to docker hub with your credentials and then login.
docker login -u docker-registry-user
Login to docker hub using docker login -u command
Login to docker hub using docker login -u command
  • Before you push your docker image to the docker hub, it’s highly recommended to tag your image with your docker hub username using the docker tag command. The syntax of the docker tag command is docker tag image.
docker tag ubuntu:latest  <dockerhub-username>/ubuntu:latest
  • After successful login in docker hub, now push your docker image using the following command.
docker push <dockerhub-username>/ubuntu:latest
Running docker push command
Running docker push command.

As you can see below, the docker image is successfully pushed into the docker hub that you created on the ubuntu machine.

successfully pushed docker image into docker hub
successfully pushed docker image into docker hub

Join 50 other followers

Conclusion

In this tutorial, you learned how to install Docker, learned several docker commands such as docker images, docker tag, docker pull, and how to push docker image to docker hub.

Docker is a great way to host your applications separately and efficiently. So which applications are you planning to run in docker?