Skip to main content
In this guide, we’ll walk through building a Docker image in a Jenkins CI/CD pipeline, tagging each build with the Git commit SHA for traceability.

Add the Build Docker Image Stage

Open your Jenkinsfile and, right after the SonarQube stage, insert a new stage named Build Docker Image. This stage prints all environment variables and then builds the Docker image using the current Git commit hash (GIT_COMMIT) as the tag.
GIT_COMMIT is a built-in Jenkins variable provided when you use the checkout step. It resolves to the current commit SHA, ensuring each Docker image is uniquely tagged.

Jenkinsfile Reference

For more information on pipeline syntax and environment variables, see the Jenkins Pipeline Syntax documentation.

Dockerfile Breakdown

Your repository includes this Dockerfile, which defines how to build the Node.js application image.
Key steps:
  1. FROM: Start from the lightweight node:18-alpine3.17 base image.
  2. WORKDIR: Set /usr/app as the working directory.
  3. COPY package*.json: Copy dependency manifests and install packages.
  4. COPY . .: Add application source code.
  5. ENV: Define placeholders for MongoDB connection.
  6. EXPOSE: Open port 3000.
  7. CMD: Launch the app with npm start.
For complete details, refer to the Dockerfile reference.

.dockerignore

Optimize build context by excluding unnecessary files. Place this .dockerignore in the project root:
Be cautious when excluding files. Make sure you don’t accidentally omit critical configuration, scripts, or assets required at runtime.
See the Dockerignore reference for patterns and best practices.

Jenkins Pipeline Environment Variables

Jenkins exposes numerous environment variables in multibranch pipelines. Visit Pipeline SyntaxGlobal variables reference to explore them all.
The image shows a Jenkins Pipeline Syntax page detailing environment variables available for multibranch projects, such as BRANCH_NAME, CHANGE_ID, and CHANGE_AUTHOR.

Pipeline Execution

After committing and pushing the updated Jenkinsfile, Jenkins triggers a new run. Once earlier stages finish, the Build Docker Image stage will begin:
This step logs all environment variables visible to the build stage:

Docker Build Logs

Jenkins streams the Docker build output, showing layer creation and tagging:
Verify the image tag in your registry or local Docker daemon to ensure it matches the commit SHA.
The image shows a code repository interface with a list of files and recent commits, including a branch named "feature/enabling-cicd."

Next Steps

You’ve successfully built and tagged a Docker image via Jenkins. In the next tutorial, we’ll scan this image for vulnerabilities and push it to Docker Hub.

Watch Video