Using Jenkins to build a Node.js and React application with npm

This tutorial shows you how to use Jenkins to orchestrate building a simple Node.js and React application with the Node Package Manager (npm).

If you are a Node.js and React developer who is new to CI/CD concepts, or you might be familiar with these concepts but don’t know how to implement building your application using Jenkins, then this tutorial is for you.

The simple Node.js and React application (which you’ll obtain from a sample repository on GitHub) generates a web page with the content "Welcome to React" and is accompanied by a test to check that the application renders satisfactorily.

Duration: This tutorial takes 20-40 minutes to complete (assuming you’ve already met the prerequisites below). The exact duration will depend on the speed of your machine and whether or not you’ve already run Jenkins in Docker from another introductory tutorial.

You can stop this tutorial at any point in time and continue from where you left off.

Prerequisites

For this tutorial, you will require:

  • A macOS, Linux or Windows machine with:

    • 256 MB of RAM, although more than 512MB is recommended.

    • 10 GB of drive space for Jenkins and your Docker images and containers.

  • The following software installed:

    • Docker - Read more about installing Docker in the Installing Docker section of the Installing Jenkins page.
      Note: If you use Linux, this tutorial assumes that you are not running Docker commands as the root user, but instead with a single user account that also has access to the other tools used throughout this tutorial.

    • Git and optionally GitHub Desktop

Run Jenkins in Docker

In this tutorial, you’ll be running Jenkins as a Docker container from the jenkinsci/blueocean Docker image. Read more about these concepts in the Docker and Downloading and running Jenkins in Docker sections of the Installing Jenkins page.

Tip: If you’ve already run though this procedure (perhaps from another introductory tutorial), then you can skip this section and jump to the next. However, if it’s been a while since you last ran through this procedure, then it is recommended that you re-run docker run ... command below again (if you haven’t already done so recently) to acquire any updates to this Docker image.

On macOS and Linux

  1. Open up a terminal window.

  2. Run the jenkinsci/blueocean image as a container in Docker using the following docker run command (bearing in mind that this command automatically downloads the image if this hasn’t been done):

    docker run \
      --rm \
      -u root \
      -p 8080:8080 \
      -v jenkins-data:/var/jenkins_home \ (1)
      -v /var/run/docker.sock:/var/run/docker.sock \
      -v "$HOME":/home \ (2)
      jenkinsci/blueocean
    1 Maps the /var/jenkins_home directory in the container to the Docker volume with the name jenkins-data. If this volume does not exist, then this docker run command will automatically create the volume for you.
    2 Maps the $HOME directory on the host (i.e. your local) machine (usually the /Users/<your-username> directory) to the /home directory in the container.

    Note: If copying and pasting the command snippet above doesn’t work, try copying and pasting this annotation-free version here:

    docker run \
      --rm \
      -u root \
      -p 8080:8080 \
      -v jenkins-data:/var/jenkins_home \
      -v /var/run/docker.sock:/var/run/docker.sock \
      -v "$HOME":/home \
      jenkinsci/blueocean
  3. Proceed to the Setup wizard.

On Windows

  1. Open up a command prompt window.

  2. Run the jenkinsci/blueocean image as a container in Docker using the following docker run command (bearing in mind that this command automatically downloads the image if this hasn’t been done):

    docker run ^
      --rm ^
      -u root ^
      -p 8080:8080 ^
      -v jenkins-data:/var/jenkins_home ^
      -v /var/run/docker.sock:/var/run/docker.sock ^
      -v "%HOMEPATH%":/home ^
      jenkinsci/blueocean

    For an explanation of these options, refer to the macOS and Linux instructions above.

  3. Proceed to the Setup wizard.

Accessing the Jenkins/Blue Ocean Docker container

If you have some experience with Docker and you wish or need to access the Jenkins/Blue Ocean Docker container through a terminal/command prompt using the docker exec command, you can add an option like --name jenkins-tutorials (with the docker run above), which would give the Jenkins/Blue Ocean Docker container the name "jenkins-tutorials".

This means you could access the Jenkins/Blue Ocean container (through a separate terminal/command prompt window) with a docker exec command like:

docker exec -it jenkins-tutorials bash

Setup wizard

Before you can access Jenkins, there are a few quick "one-off" steps you’ll need to perform.

Unlocking Jenkins

When you first access a new Jenkins instance, you are asked to unlock it using an automatically-generated password.

  1. After the 2 sets of asterisks appear in the terminal/command prompt window, browse to http://localhost:8080 and wait until the Unlock Jenkins page appears.

    Unlock Jenkins page

  2. From your terminal/command prompt window again, copy the automatically-generated alphanumeric password (between the 2 sets of asterisks).

    Copying initial admin password

  3. On the Unlock Jenkins page, paste this password into the Administrator password field and click Continue.

Customizing Jenkins with plugins

After unlocking Jenkins, the Customize Jenkins page appears.

On this page, click Install suggested plugins.

The setup wizard shows the progression of Jenkins being configured and the suggested plugins being installed. This process may take a few minutes.

Creating the first administrator user

Finally, Jenkins asks you to create your first administrator user.

  1. When the Create First Admin User page appears, specify your details in the respective fields and click Save and Finish.

  2. When the Jenkins is ready page appears, click Start using Jenkins.
    Notes:

    • This page may indicate Jenkins is almost ready! instead and if so, click Restart.

    • If the page doesn’t automatically refresh after a minute, use your web browser to refresh the page manually.

  3. If required, log in to Jenkins with the credentials of the user you just created and you’re ready to start using Jenkins!

Stopping and restarting Jenkins

Throughout the remainder of this tutorial, you can stop the Jenkins/Blue Ocean Docker container by typing Ctrl-C in the terminal/command prompt window from which you ran the docker run ... command above.

To restart the Jenkins/Blue Ocean Docker container:

  1. Run the same docker run ... command you ran for macOS, Linux or Windows above.

  2. Browse to http://localhost:8080.

  3. Wait until the log in page appears and log in.

Fork and clone the sample repository on GitHub

Obtain the simple "Welcome to React" Node.js and React application from GitHub, by forking the sample repository of the application’s source code into your own GitHub account and then cloning this fork locally.

  1. Ensure you are signed in to your GitHub account. If you don’t yet have a GitHub account, sign up for a free one on the GitHub website.

  2. Fork the simple-node-js-react-npm-app on GitHub into your local GitHub account. If you need help with this process, refer to the Fork A Repo documentation on the GitHub website for more information.

  3. Begin cloning your forked simple-node-js-react-npm-app repository (on GitHub) locally to your machine by opening up a terminal/command line window to the directory in which the repository will be cloned. This tutorial assumes that simple-node-js-react-npm-app will be cloned within the following directories on these platforms, which you should cd into now:

    • macOS - /Users/<your-username>/Documents/GitHub

    • Linux - /home/<your-username>/GitHub

    • Windows - C:\Users\<your-username>\Documents\GitHub

      where <your-username> is your user account’s name on your operating system.

      Note:

      • On a Windows machine, use a Git bash command line window (as opposed to the usual Microsoft command prompt).

      • Alternatively, and in particular if you have the GitHub Desktop app installed on your machine, in GitHub, you can click the green Clone or download button on your forked repository and follow the instructions to clone the repository locally. If you use GitHub Desktop, you can omit the following step.

  4. Run the following command to continue/complete cloning your forked repo:
    git clone https://github.com/YOUR-GITHUB-ACCOUNT-NAME/simple-node-js-react-npm-app
    where YOUR-GITHUB-ACCOUNT-NAME is the name of your GitHub account.

Create your Pipeline project in Jenkins

  1. Go back to Jenkins, log in again if necessary and click create new jobs under Welcome to Jenkins!
    Note: If you don’t see this, click New Item at the top left.

  2. In the Enter an item name field, specify the name for your new Pipeline project (e.g. simple-node-js-react-npm-app).

  3. Scroll down and click Pipeline, then click OK at the end of the page.

  4. ( Optional ) On the next page, specify a brief description for your Pipeline in the Description field (e.g. An entry-level Pipeline demonstrating how to use Jenkins to build a simple Node.js and React application with npm.)

  5. Click the Pipeline tab at the top of the page to scroll down to the Pipeline section.

  6. From the Definition field, choose the Pipeline script from SCM option. This option instructs Jenkins to obtain your Pipeline from Source Control Management (SCM), which will be your locally cloned Git repository.

  7. From the SCM field, choose Git.

  8. In the Repository URL field, specify the directory path of your locally cloned repository above, which is from your user account/home directory on your host machine, mapped to the /home directory of the Jenkins/Blue Ocean container - i.e.

    • For macOS - /home/Documents/GitHub/simple-node-js-react-npm-app

    • For Linux - /home/GitHub/simple-node-js-react-npm-app

    • For Windows - /home/Documents/GitHub/simple-node-js-react-npm-app

  9. Click Save to save your new Pipeline project. You’re now ready to begin creating your Jenkinsfile, which you’ll be checking into your locally cloned Git repository.

Create your initial Pipeline as a Jenkinsfile

You’re now ready to create your Pipeline that will automate building your Node.js and React application in Jenkins. Your Pipeline will be created as a Jenkinsfile, which will be committed to your locally cloned Git repository (simple-node-js-react-npm-app).

This is the foundation of "Pipeline-as-Code", which treats the continuous delivery pipeline a part of the application to be versioned and reviewed like any other code. Read more about Pipeline and what a Jenkinsfile is in the Pipeline and Using a Jenkinsfile sections of the User Handbook.

First, create an initial Pipeline to download a Node Docker image and run it as a Docker container (which will build your simple Node.js and React application). Also add a "Build" stage to the Pipeline that begins orchestrating this whole process.

  1. Using your favorite text editor or IDE, create and save new text file with the name Jenkinsfile at the root of your local simple-node-js-react-npm-app Git repository.

  2. Copy the following Declarative Pipeline code and paste it into your empty Jenkinsfile:

    pipeline {
        agent {
            docker {
                image 'node:6-alpine' (1)
                args '-p 3000:3000' (2)
            }
        }
        stages {
            stage('Build') { (3)
                steps {
                    sh 'npm install' (4)
                }
            }
        }
    }
    1 This image parameter (of the agent section’s docker parameter) downloads the node:6-apline Docker image (if it’s not already available in your Docker host) and runs this image as a separate container. This means that:
    • You’ll have separate Jenkins/Blue Ocean and Node containers running locally in Docker.

    • The Node container becomes the agent that Jenkins uses to build your Pipeline project. However, this container is short-lived - its lifespan is only that of the duration of your Pipeline’s execution.

    2 This args parameter makes the Node container (temporarily) accessible through port 3000. The significance of this is explained in the jenkins/scripts/deliver.sh file of your cloned repository, and is covered in a subsequent section of this tutorial.
    3 Defines a stage called Build that appears on the Jenkins UI.
    4 This sh step (of the steps section) executes the npm command to ensure that all dependencies required to run your application have been downloaded to the local node_modules directory (i.e. within the /var/jenkins_home/workspace/simple-node-js-react-npm-app directory in the Jenkins/Blue Ocean container).
  3. Save your amended Jenkinsfile and commit it to your local simple-node-js-react-npm-app Git repository. E.g. Within the simple-node-js-react-npm-app directory, run the commands:
    git add .
    then
    git commit -m "Add initial Jenkinsfile"

  4. Go back to Jenkins again, log in again if necessary and click Open Blue Ocean on the left to access Jenkins’s Blue Ocean interface.

  5. In the This job has not been run message box, click Run, then quickly click the OPEN link which appears briefly at the lower-right to see Jenkins building your Pipeline project. If you weren’t able to click the OPEN link, click the row on the main Blue Ocean interface to access this feature.
    Note: You may need to wait several minutes for this first run to complete. After making a clone of your local simple-node-js-react-npm-app Git repository itself, Jenkins:

    1. Initially queues the project to be built on the agent.

    2. Downloads the Node Docker image and runs it in a container on Docker.

      Downloading Node Docker image

    3. Executes the Build stage (defined in the Jenkinsfile) on the Node container. During this time, npm downloads many dependencies necessary to run your Node.js and React application, which will ultimately be stored in the local node_modules directory (within the Jenkins home directory).

      Downloading <em>npm</em> dependencies

    The Blue Ocean interface turns green if Jenkins built your Node.js and React application successfully.

    Initial Pipeline runs successfully

  6. Click the X at the top-right to return to the main Blue Ocean interface.

    Main Blue Ocean interface

Add a test stage to your Pipeline

  1. Go back to your text editor/IDE and ensure your Jenkinsfile is open.

  2. Copy and paste the following Declarative Pipeline syntax immediately under the agent section of your Jenkinsfile:

        environment {
            CI = 'true'
        }

    as well as the following immediately under the Build stage:

            stage('Test') {
                steps {
                    sh './jenkins/scripts/test.sh'
                }
            }

    so that you end up with:

    pipeline {
        agent {
            docker {
                image 'node:6-alpine'
                args '-p 3000:3000'
            }
        }
        environment {
            CI = 'true' (1)
        }
        stages {
            stage('Build') {
                steps {
                    sh 'npm install'
                }
            }
            stage('Test') { (2)
                steps {
                    sh './jenkins/scripts/test.sh' (3)
                }
            }
        }
    }
    1 The environment directive sets the environment variable CI with a boolean value of true, which is available to all steps in this Pipeline. When the npm test command in test.sh (which is run during the Test stage defined further down the Pipeline) detects the environment variable CI with a value of true, then this command is run in "non-watch" (i.e. non-interactive) mode. In "watch" mode, npm test expects user input, which can pause running builds of CI/CD applications indefinitely. As an alternative to specifying the environment directive in a Jenkins Pipeline, you could also specify this environment variable in the package.json file (to pass on to the npm test command) by:
    1. Uncommenting the npm install --save-dev cross-env command in jenkins/scripts/test.sh (to install the cross-env dependency during the Test stage). Read more about this in the test.sh file itself.

    2. Updating the following line in the package.json file (at the root of the simple-node-js-react-npm-app repository) from:

      • "test": "react-scripts test --env=jsdom",
        to

      • "test": "cross-env CI=true react-scripts test --env=jsdom",

    2 Defines a new stage called Test that appears on the Jenkins UI.
    3 This sh step (of the steps section) runs the shell script test.sh located in the jenkins/scripts directory from the root of the simple-node-js-react-npm-app repository. Explanations about what this script does are covered in the test.sh file itself. As a general principle, it’s a good idea to keep your Pipeline code (i.e. the Jenkinsfile) as tidy as possible and place more complex build scripting steps into separate shell script files like the test.sh file. This ultimately facilitates the maintenance of your Pipeline, especially if it gains more complexity.
  3. Save your amended Jenkinsfile and commit it to your local simple-node-js-react-npm-app Git repository. E.g. Within the simple-node-js-react-npm-app directory, run the commands:
    git stage .
    then
    git commit -m "Add 'Test' stage"

  4. Go back to Jenkins again, log in again if necessary and ensure you’ve accessed Jenkins’s Blue Ocean interface.

  5. Click Run at the top left, then quickly click the OPEN link which appears briefly at the lower-right to see Jenkins building your amended Pipeline project. If you weren’t able to click the OPEN link, click the top row on the Blue Ocean interface to access this feature.
    Note: You’ll notice from this run that Jenkins no longer needs to download the Node Docker image. Instead, Jenkins only needs to run a new container from the Node image downloaded previously. Also, from now on, no (new) npm dependencies should need to be downloaded during the "Build" stage. Therefore, running your Pipeline this subsequent time should be much faster.
    If your amended Pipeline ran successfully, here’s what the Blue Ocean interface should look like. Notice the additional "Test" stage. You can click on the previous "Build" stage circle to access the output from that stage.

    Test stage runs successfully (with output)

  6. Click the X at the top-right to return to the main Blue Ocean interface.

Add a final deliver stage to your Pipeline

  1. Go back to your text editor/IDE and ensure your Jenkinsfile is open.

  2. Copy and paste the following Declarative Pipeline syntax immediately under the Test stage of your Jenkinsfile:

            stage('Deliver') {
                steps {
                    sh './jenkins/scripts/deliver.sh'
                    input message: 'Finished using the web site? (Click "Proceed" to continue)'
                    sh './jenkins/scripts/kill.sh'
                }
            }

    so that you end up with:

    pipeline {
        agent {
            docker {
                image 'node:6-alpine'
                args '-p 3000:3000'
            }
        }
        environment { (1)
            CI = 'true'
        }
        stages {
            stage('Build') {
                steps {
                    sh 'npm install'
                }
            }
            stage('Test') {
                steps {
                    sh './jenkins/scripts/test.sh'
                }
            }
            stage('Deliver') { (2)
                steps {
                    sh './jenkins/scripts/deliver.sh' (3)
                    input message: 'Finished using the web site? (Click "Proceed" to continue)' (4)
                    sh './jenkins/scripts/kill.sh' (5)
                }
            }
        }
    }
    1 This environment directive might not be present in your Pipeline if you chose to specify the CI environment variable in the package.json file above.
    2 Defines a new stage called Deliver that appears on the Jenkins UI.
    3 This sh step (of the steps section) runs the shell script deliver.sh located in the jenkins/scripts directory from the root of the simple-node-js-react-npm-app repository. Explanations about what this script does are covered in the deliver.sh file itself.
    4 This input step (of the Pipeline: Input Step plugin, which was installed with the "suggested plugins" above) pauses the running build prompts the user (with a custom message) to proceed or abort.
    5 This sh step runs the shell script kill.sh, also located in the jenkins/scripts directory. Explanations about what this script does are covered in the kill.sh file itself.
  3. Save your amended Jenkinsfile and commit it to your local simple-node-js-react-npm-app Git repository. E.g. Within the simple-node-js-react-npm-app directory, run the commands:
    git stage .
    then
    git commit -m "Add 'Deliver' stage"

  4. Go back to Jenkins again, log in again if necessary and ensure you’ve accessed Jenkins’s Blue Ocean interface.

  5. Click Run at the top left, then quickly click the OPEN link which appears briefly at the lower-right to see Jenkins building your amended Pipeline project. If you weren’t able to click the OPEN link, click the top row on the Blue Ocean interface to access this feature.
    If your amended Pipeline ran successfully, here’s what the Blue Ocean interface should look like. Notice the additional "Deliver" stage. Click on the previous "Test" and "Build" stage circles to access the outputs from those stages.

    Deliver stage pauses for user input

  6. Ensure you are viewing the "Deliver" stage (click it if necessary), then click the green ./jenkins/scripts/deliver.sh step to expand its content and scroll down until you see the http://localhost:3000 link.

    Deliver stage output only

  7. Click the http://localhost:3000 link to view your Node.js and React application running (in development mode) in a new web browser tab. You should see a page/site with the title Welcome to React on it.
    Tip: If you’re feeling a little adventurous, you can try accessing the terminal/command prompt of your Jenkins/Blue Ocean Docker container, then using vi editor, tweak and save the App.js source file and see the results appear on the Welcome to React page. To do this, enter the following commands:

    docker exec -it <docker-container-name> bash (1)
    cd /var/jenkins_home/workspace/simple-node-js-react-npm-app/src (2)
    vi App.js (3)
    1 This command provides access to the terminal/command prompt of your Jenkins/Blue Ocean Docker container. The <docker-container-name> can be obtained using the command docker ps. Otherwise, it would be jenkins-tutorials (if you specified this in the command you used to run this container above - i.e. --name jenkins-tutorials).
    2 Once in the container, change directory to the Node.js and React source directory (in the Jenkins workspace directory within Jenkins home).
    3 Access, edit and save changes to your application’s App.js file using vi editor.
  8. When you are finished viewing the page/site, click the Proceed button to complete the Pipeline’s execution.

    Deliver stage runs successfully

  9. Click the X at the top-right to return to the main Blue Ocean interface, which lists your previous Pipeline runs in reverse chronological order.

    Main Blue Ocean interface with all previous runs displayed

Wrapping up

Well done! You’ve just used Jenkins to build a simple Node.js and React application with npm!

The "Build", "Test" and "Deliver" stages you created above are the basis for building more complex Node.js and React applications in Jenkins, as well as Node.js and React applications that integrate with other technology stacks.

Because Jenkins is extremely extensible, it can be modified and configured to handle practically any aspect of build orchestration and automation.

To learn more about what Jenkins can do, check out:


Was this page helpful?

Please submit your feedback about this page through this quick form.

Alternatively, if you don't wish to complete the quick form, you can simply indicate if you found this page helpful?

    


See existing feedback here.