Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 40 ยท Projects

Project: Node App with Docker Build and Deploy

Build a Jenkins pipeline for a Node app: npm tests, a tagged Docker image, a push to a registry and a production deploy stage behind an approval.

This project takes a small Node.js web service from source code to a running container. The pipeline installs dependencies, runs the tests, builds a Docker image with a unique tag, pushes it to a registry, deploys it to staging and, after a human approves, to production. It combines ideas from earlier lessons: Docker agents, credentials, tagging, and approvals.

The real Jenkins, Docker daemon and registry cannot run on this site, so the Jenkinsfile and commands are read-only. A JavaScript stand-in at the end runs the same stages as a simulation, so you can see the tag logic, the push, and the approval gate.

From commit to container

Test npm ci and npm test.
Build image Tag it with build and commit.
Push Send it to the registry.
Deploy Staging, then production after approval.

The image tag is the version you deploy and roll back to.

1 / 2

The application and its Dockerfile

Assume a Node service with package.json (scripts test and start), package-lock.json and a Dockerfile in the root. A multi-stage Dockerfile keeps the final image small (read-only):

DOCKERFILE
FROM node:22-slim AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev

FROM node:22-slim
WORKDIR /app
ENV NODE_ENV=production
COPY --from=deps /app/node_modules ./node_modules
COPY . .
USER node
EXPOSE 3000
CMD ["node", "server.js"]

Details of images and layers are covered in the Docker tutorial. Remember to have a .dockerignore that excludes node_modules and .git, so the build context stays small.

Credentials you need

Two credentials, created in Jenkins as described in Credentials and Secrets:

  • registry-login of kind username with password, for the container registry (use an access token rather than a personal password).
  • deploy-ssh-key of kind SSH key, if the deploy step connects to a server. Other platforms use a kubeconfig file credential or a cloud token.

The pipeline refers to them by ID only; the secrets themselves never appear in the Jenkinsfile.

The Jenkinsfile

Here is the complete pipeline (read-only). It builds on an agent that has Docker and Node available (an agent labeled docker).

GROOVY
pipeline {
  agent none

  options {
    timeout(time: 30, unit: 'MINUTES')
    buildDiscarder(logRotator(numToKeepStr: '30'))
  }

  environment {
    REGISTRY = 'registry.example.com'
    IMAGE    = 'registry.example.com/team/shop-api'
  }

  stages {
    stage('Test') {
      agent {
        docker { image 'node:22-slim' }
      }
      steps {
        sh 'npm ci'
        sh 'npm test'
      }
    }

    stage('Build image') {
      agent { label 'docker' }
      steps {
        script {
          env.SHORT_SHA = sh(returnStdout: true, script: 'git rev-parse --short=7 HEAD').trim()
          env.IMAGE_TAG = "${env.BUILD_NUMBER}-${env.SHORT_SHA}"
        }
        sh 'docker build -t "$IMAGE:$IMAGE_TAG" .'
      }
    }

    stage('Push image') {
      agent { label 'docker' }
      when { branch 'main' }
      steps {
        withCredentials([usernamePassword(credentialsId: 'registry-login',
                                          usernameVariable: 'REG_USER',
                                          passwordVariable: 'REG_PASS')]) {
          sh '''
            echo "$REG_PASS" | docker login "$REGISTRY" -u "$REG_USER" --password-stdin
            docker push "$IMAGE:$IMAGE_TAG"
            docker logout "$REGISTRY"
          '''
        }
      }
    }

    stage('Deploy to staging') {
      agent { label 'docker' }
      when { branch 'main' }
      steps {
        sh './deploy.sh staging "$IMAGE:$IMAGE_TAG"'
        sh './smoke-test.sh https://staging.example.com'
      }
    }

    stage('Approve production') {
      when { branch 'main' }
      agent none
      options { timeout(time: 2, unit: 'HOURS') }
      steps {
        input message: "Deploy ${env.IMAGE_TAG} to production?", submitter: 'release-managers'
      }
    }

    stage('Deploy to production') {
      agent { label 'docker' }
      when { branch 'main' }
      steps {
        lock('shop-api-production') {
          sh './deploy.sh production "$IMAGE:$IMAGE_TAG"'
          sh './smoke-test.sh https://shop.example.com'
        }
      }
    }
  }

  post {
    failure {
      echo "Pipeline failed: ${env.BUILD_URL}"
    }
  }
}

One caveat about this layout: with agent none at the top, each stage may run on a different machine, and the workspace is not shared between them. In practice Build image and later stages need the source code (Dockerfile, deploy.sh), so a real pipeline either checks out the code in each stage (the agent declaration of a stage in a Pipeline-from-SCM job does this automatically) or stashes it (see Artifacts, Stash and Fingerprints). Another approach is to use a single agent { label 'docker' } for everything except the approval stage. Choose whichever is simplest for your setup.

The decisions explained

  • Test in a throwaway container. The docker agent starts node:22-slim for the stage, so the agent needs no Node installation and every run starts from the same clean environment. See Docker Agents and Building Images.
  • A unique, traceable tag. BUILD_NUMBER-SHORTSHA tells you the order of builds and the exact commit inside the image. Avoid deploying latest: it tells you nothing and makes rollback guesswork.
  • Tag with returnStdout. The script block captures the command output (see Common Steps). .trim() removes the newline.
  • Push only from main. The when { branch 'main' } directive keeps feature branches and pull requests from filling the registry. They still run the tests and the image build, which is useful: a broken Dockerfile is caught before merge.
  • Credentials only where needed. withCredentials makes REG_USER and REG_PASS available just inside the block, and Jenkins masks their values in the log. Using --password-stdin keeps the password out of the process list. See the warning below about the limits of masking.
  • Approval without an agent. The approval stage uses agent none and a timeout, so waiting for a person does not hold an executor (see Deployment Pipelines and Approvals).
  • Lock around the production deploy. Only one pipeline deploys shop-api to production at a time.
  • Smoke tests after every deploy. A deploy that returns exit code 0 but serves errors is still a failure.

Giving a build access to the Docker socket (/var/run/docker.sock) effectively gives it root on that machine. Run Docker builds on dedicated, disposable agents, never on the controller, and consider daemonless builders such as Kaniko or BuildKit for shared infrastructure.

Rolling back

Because every image has an immutable tag, a rollback is the same deploy script with an older tag:

Terminal
./deploy.sh production registry.example.com/team/shop-api:41-3fa9c21

Keep a few recent tags in the registry and put a retention policy on old ones. If you deploy with Kubernetes, kubectl rollout undo does the same thing at the platform level.

A stand-in pipeline runner

This simulator runs the stages with fake Docker, registry and deploy actions, writing the commands it would execute. It shows how the tag is built, why a feature branch stops before pushing, and how the approval gate works. No image is built; it is a model of the control flow.

JS A stand-in runner for the Node and Docker pipeline

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Build 52 proves a feature branch is still tested and built but never pushed or deployed. Build 53 goes all the way. Build 54 is aborted at the gate when nobody answers in time; the image is in the registry and staging, but production is untouched. Build 55 fails at the tests, so no image is even built.

A stand-in for the tag and cache logic

Image tags and layer caching follow simple rules that are easy to check in code. This second stand-in builds tags from the build number and commit, and shows which layers would be rebuilt after a change, using the idea that a layer is reused only if the instruction and everything before it are unchanged.

JS A stand-in for tags and layer caching

Press Run (or Ctrl + Enter) to see the console output here.

No output.

When only the source changes, npm ci stays cached, which is why the Dockerfile copies package*.json before the rest of the code. Reordering those two lines would make every build reinstall all dependencies.

Extending the project

  • Run the test stage in parallel for several Node versions (see Stages, Parallel and Matrix).
  • Scan the image for vulnerabilities before pushing.
  • Replace deploy.sh with a Helm or Kubernetes step, and add a canary stage.
  • Send a Slack message after production deploys, and tag the release in Git.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why tag images with the build number and short commit instead of 'latest'?

    'latest' is a moving label. A unique tag names one immutable image you can deploy, trace to a commit and roll back to.
  2. 2. What does when { branch 'main' } on the push stage achieve?

    Directives such as when decide whether a stage runs. Feature branches stop before publishing.
  3. 3. Why does the approval stage use 'agent none'?

    Waiting for a human can take hours; without an agent, the executor stays available for other builds.
  4. 4. In the Dockerfile, why copy package.json and run npm ci before copying the rest of the code?

    Docker reuses a layer when the step and everything before it is unchanged. Source changes then rebuild only the layers after the dependency install.

Summary

  • The pipeline tests in a Docker agent, builds an image tagged BUILD_NUMBER-SHORTSHA, pushes from main only, deploys to staging, and waits for approval before production.
  • Credentials are referenced by ID and used inside withCredentials; use --password-stdin and remember masking has limits.
  • Approval stages should not hold an agent and should have a timeout; production deploys should be locked and smoke tested.
  • Immutable tags make rollbacks a re-run of the deploy script with an older tag.
  • Be careful with the Docker socket, and keep Docker builds off the controller.

Next, tackle a larger codebase in Project: A Monorepo Pipeline with Changed-Path Builds.