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 28 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?

The Ultimate Guide: Getting Started with Jenkins Pipeline

Are you struggling to automate the application deployment? Why not use Jenkins and Jenkins Pipeline to automate all the deployments more easily and effectively.

With Jenkins Pipeline, the deployment process is earlier and gives you more features to incorporate while deploying or managing the infrastructure.

In this tutorial, you will learn what is Jenkins Pipeline in depth. Let’s get started.

Join 28 other followers

Table of Content

  1. What is CI/CD ( Continuous Integration and Continuous deployments)?
  2. What is Jenkins Pipeline?
  3. How to create a basic Jenkins Pipeline
  4. Handling Parameters in Jenkins Pipeline
  5. How to work with Input Parameters
  6. Conclusion

Prerequisites

What is CI/CD ( Continuous Integration and Continuous deployments)?

CI/CD products are delivered to clients ingeniously and effectively using different automated stages. CI/CD saves tons of time for both developer and operations team, and there are very few chances of human errors. CI/CD stands for continuous integration and continuous deployments. It automates everything starting from integrating to deployments.

Continuous Integration and Continuous deployments
Continuous Integration and Continuous deployments

What is Continuous Integration?

Continuous integration is primarily used by developers so that developers’ code is built, tested, and then pushed to a shared repository whenever there is a change in code.

For every code push to the repository, you can create a set of scripts to build and test your application automatically. These scripts help decrease the chances that you introduce errors in your application.

This practice is known as Continuous Integration. Each change submitted to an application, even to development branches, is built and tested automatically and continuously.

What is Continuous Delivery?

Continuous delivery is a step beyond continuous integration. With Continuous Delivery, the application is not only continuously built and tested each time the code is pushed but the application is also deployed continuously. However, with continuous delivery, you trigger the deployments manually.

Continuous delivery checks the code automatically, but it requires human intervention to deploy the changes.

What is Continuous Deployment

Continuous deployment is again a step beyond continuous integration and the only difference between deployment and delivery is: deployment automatically takes the code from a shared repository and deploys the changes to environments such as Production where customers can see those changes.

This is the final stage of the CI/CD pipeline. With Continous Deployment, it hardly takes a minute to deploy the code to the environments. It depends on heavy pre-automation testing.

Examples of CI/CD :

  • Spinnaker and Screwdriver built platform for CD
  • GitLab, Bamboo, CircleCI, Travis CI and GoCD are built platform for CI/CD.

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). Some of the benefits of the Jenkins pipeline are:

Jenkinsfile ( declarative vs scripted pipeline)

Jenkins pipeline is written in code with Jenkinsfile that is easier, gives more ability to review, and supports various extensions & plugins. Also if Jenkins stops you can still continue to write or update the Jenkinsfile. With code capabilities you can allow waiting, approvals, stop, and many other functionalities. Jenkinsfile follows two syntaxes:

  • Declarative Pipeline: This is newer and writing code with this is much easier.
  • Scripted Pipeline: This is older and writing code with this is a little complicated.

Scripted pipeline syntax

Jenkins provides you an easier way to generate the Scripted pipeline syntax by navigating to the below URL.

http://Jenkins-server:8080/pipeline-syntax/
Scripted pipeline syntax
Scripted pipeline syntax

Declarative Pipeline syntax

Jenkins also provides you a way to generate the Declarative pipeline syntax by navigating to the below URL.

http://Jenkins-server:8080/directive-generator/
Declarative Pipeline syntax
Declarative Pipeline syntax

Jenkins variables

Let’s quickly look at the Jenkins Pipeline environmental variables that are supported.

  • BUILD_NUMBER: Displays the build number
  • BUILD_TAG: Displays the tag which is jenkins-${JOB_NAME}-${BUILD_NUMBER}
  • BUILD_URL: Displays the URL of the result of Build
  • JAVA_HOME: Path of Java home
  • NODE_NAME: It specifics the name of the node. For example, set it to master is for Jenkins controller
  • JOB_NAME: Name of the Job

You can set the environmental variables dynamically in the Jenkins pipeline as well.

    environment {
        AWS_ACCESS_KEY_ID     = credentials('jenkins-aws-secret-key-id')
        AWS_SECRET_ACCESS_KEY = credentials('jenkins-aws-secret-access-key')
        MY_KUBECONFIG = credentials('my-kubeconfig')
   }

Jenkinsfile example

Previously you learned about Jenkinsfile syntax and variables that can be included in Jenkinfile. In this section lets learn by seeing a basic example declarative pipeline. 

Below are all the arguments that are used within the Jenkinsfile and their function is specified below.

  • agent: Agent allows Jenkins to allocate an executor or a node. For example Jenkins slave
  • Stages: It include multiple tasks which Pipeline needs to perform. It can have a single task as well.
  • Stage: Stage is one single task under stages.
  • steps: These are steps which needs to be executed in every stage.
  • sh: sh is one of the step which executes shell command.
pipeline {
   agent any 
    stages {
        stage('Testing the Jenkins Version') {
            steps {
                echo 'Hello, Jenkins'
                sh 'service jenkins status'
               //  sh("kubectl --kubeconfig $MY_KUBECONFIG get pods")
            }
        }
    }
}

Jenkins Job example to run Jenkins Pipeline

In this section, lets quickly learn how you can execute jenkins job with Jenkinsfile and Jenkins Pipeline. Lets create Jenkins job quickly.

  • Navigate to Jenkins URL and click on New Item.
Click on new item in Jenkins Job
Click on new item in Jenkins Job
  • Next, choose Pipeline as the type of Jenkins job from the option as shown below, provide the of Jenkins Job as pipeline-demo and click OK.
Choosing the Pipeline and naming the Jenkins Job
Choosing the Pipeline and naming the Jenkins Job
  • Now in the Jenkins job provide the description as my demo pipeline.
  • Further in the script copy/paste the below code.
pipeline {
   agent any 
    stages {
        stage('Testing the Jenkins Version') {
            steps {
                echo 'Hello, Jenkins'
                sh 'service jenkins status'
            }
        }
    }
}
  • Finally click on save & click on Build Now button.
Running the Jenkins Job to run Jenkins Pipeline
Running the Jenkins Job to run Jenkins Pipeline

Now that you have successfully run your first Jenkins Job using Jenkins Pipeline. lets verify the code execution from console output of the Job and to do that click on the build number from build history.

Build History of Jenkins Job
Build History of Jenkins Job
Verifying the Jenkins Job using console output
Verifying the Jenkins Job using console output

Handling Parameters in Jenkins Pipeline

If you wish to use Build with Parameters , so those parameters are accessible using params keyword in pipeline.

Lets see a quick example. In below code we have Profile as a parameter and it can be accessed as ${params.Profile} .Lets paste the code in pipeline script as we did earlier

pipeline {
  agent any
  parameters {
    string(name: 'Profile', defaultValue: 'devops-engineer', description: 'I am devops guy') 
}
 stages {
    stage('Testing DEVOPS') {
       steps {
          echo "${params.Profile} is a cloud profile"
       }
     }
   }
}
  • Lets build the Jenkins pipeline now.
  • Next verify the console output
  • Similarly we can use different parameters such
pipeline {
    agent any
    parameters {
        string(name: 'PERSON', defaultValue: 'AutomateInfra', description: 'PERSON')
        text(name: 'BIOGRAPHY', defaultValue: '', description: 'BIOGRAPHY')
        booleanParam(name: 'TOGGLE', defaultValue: true, description: 'TOGGLE')
        choice(name: 'CHOICE', choices: ['One', 'Two', 'Three'], description: 'CHOICE')
        password(name: 'PASSWORD', defaultValue: 'SECRET', description: 'PASSWORD')
    }
    stages {
        stage('All-Parameters') {
            steps {
                echo "I am ${params.PERSON}"
                echo "Biography: ${params.BIOGRAPHY}"
                echo "Toggle: ${params.TOGGLE}"
                echo "Choice: ${params.CHOICE}"
                echo "Password: ${params.PASSWORD}"
            }
        }
    }
}

How to work with Input Parameters

Input parameter allows you to provide an input using a input step. Unless input is provided the pipeline will be paused. Lets see a quick example in which Jenkins job will prompt for “should we continue” message. Unless we approve it will remain as it is else finally it will abort.

pipeline {
    agent any
    stages {
        stage('Testing input condition') {
            input {
                message "Should we continue?"
                ok "Yes, we should."
                submitter "automateinfra"
                parameters {
                    string(name: 'PERSON', defaultValue: 'Automate', description: 'Person')
                }
            }
            steps {
                echo "Hello, ${PERSON}, nice to meet you."
            }
        }
    }
}
  • Lets paste the content in Jenkins pipeline script and click on build now.
  • Let us verify by clicking on build Now

Conclusion

In this tutorial we learnt what is CI/CD and CI/CD open source tool Jenkins. We covered how to write pipeline and syntax of Jenkins pipeline using its language known as DSL ( domain specific language ) . Also we learnt in depth of Jenkins pipeline and created basic Jenkins pipeline and executed it.

Hope this tutorial will help you a kick start to how to work with Jenkins pipeline and execute them. If you like this please share it.