How to Use docker.build in Jenkins Pipeline
In a Jenkins pipeline, use
docker.build('image-name') to build a Docker image from a Dockerfile in your workspace. This command returns a Docker image object you can use later to run containers or push the image.Syntax
The docker.build command in Jenkins pipeline builds a Docker image from the current workspace Dockerfile.
docker.build('image-name'): Builds the image with the given name.- The command returns a Docker image object for further actions like running or pushing.
- You can optionally specify a Dockerfile path and build arguments.
groovy
def image = docker.build('my-image-name')Example
This example shows a simple Jenkins pipeline that builds a Docker image named my-app from the Dockerfile in the workspace and then runs a container from it.
groovy
pipeline {
agent any
stages {
stage('Build Docker Image') {
steps {
script {
def myImage = docker.build('my-app')
myImage.inside {
sh 'echo Running inside the container'
}
}
}
}
}
}Output
[Pipeline] { (Build Docker Image)
[Pipeline] script
[Pipeline] {
[Pipeline] docker.build
Sending build context to Docker daemon 2.048kB
Step 1/2 : FROM alpine
---> a24bb4013296
Step 2/2 : CMD ["echo", "Hello from container"]
---> Running in 123abc456def
Removing intermediate container 123abc456def
Successfully built abcdef123456
Successfully tagged my-app:latest
[Pipeline] sh
Running inside the container
[Pipeline] }
[Pipeline] }
[Pipeline] }
Common Pitfalls
Common mistakes when using docker.build include:
- Not having a Dockerfile in the workspace, causing build failure.
- Using
docker.buildoutside ascriptblock in declarative pipelines. - Forgetting to tag the image properly, which can cause confusion later.
- Not handling credentials when pushing images to private registries.
groovy
/* Wrong: docker.build used outside script block in declarative pipeline */ pipeline { agent any stages { stage('Build') { steps { // docker.build('my-image') // This causes error } } } } /* Right: docker.build inside script block */ pipeline { agent any stages { stage('Build') { steps { script { docker.build('my-image') } } } } }
Quick Reference
Remember these tips when using docker.build in Jenkins pipelines:
- Always run
docker.buildinside ascriptblock in declarative pipelines. - Use descriptive image names and tags for clarity.
- Ensure your Jenkins agent has Docker installed and permissions to run Docker commands.
- Use the returned image object to run containers or push images.
Key Takeaways
Use docker.build('image-name') inside a script block to build Docker images in Jenkins pipelines.
The command returns an image object for running containers or pushing images.
Ensure a Dockerfile exists in the workspace before building.
Tag images clearly to avoid confusion.
Jenkins agents must have Docker installed and proper permissions.