How to Use Agent with Docker in Jenkins for Containerized Builds
In Jenkins, you can use a
docker agent in your pipeline to run build steps inside a Docker container by specifying agent { docker { image 'your-image' } }. This runs the pipeline or stage inside the specified Docker container, isolating the environment and dependencies.Syntax
The agent directive in Jenkins pipeline defines where the build runs. Using docker inside agent tells Jenkins to run the build inside a Docker container.
agent { docker { image 'image-name' } }: Runs entire pipeline in the Docker container.agent { docker { image 'image-name' args '-v /host/path:/container/path' } }: Runs with extra Docker arguments like volume mounts.agent { dockerfile true }: Builds Docker image from a Dockerfile in the repo and runs inside it.
groovy
pipeline {
agent {
docker {
image 'node:18-alpine'
args '-v /tmp:/tmp'
}
}
stages {
stage('Build') {
steps {
sh 'node --version'
}
}
}
}Example
This example shows a Jenkins pipeline that uses a Docker agent with the official Node.js image. The build runs inside the container and prints the Node.js version.
groovy
pipeline {
agent {
docker {
image 'node:18-alpine'
label 'docker-agent'
args '-u root:root'
}
}
stages {
stage('Check Node Version') {
steps {
sh 'node --version'
}
}
}
}Output
v18.x.x
Common Pitfalls
- Docker not installed or accessible: Jenkins agent must have Docker installed and permission to run Docker commands.
- Incorrect image name: Using a non-existent or misspelled Docker image causes build failure.
- Volume mounts missing: If your build needs files from the host, you must specify
argsto mount volumes. - Running as wrong user: Some images require running as root or specific user; use
args '-u root'if needed.
groovy
pipeline {
agent {
docker {
image 'nonexistent-image'
}
}
stages {
stage('Test') {
steps {
sh 'echo Hello'
}
}
}
}
// This will fail because the image does not exist.
// Correct usage:
// image 'node:18-alpine'Quick Reference
| Directive | Description | Example |
|---|---|---|
| agent | Defines where the pipeline or stage runs | agent { docker { image 'alpine' } } |
| docker.image | Docker image to use for the agent | image 'node:18-alpine' |
| docker.args | Extra Docker run arguments like volume mounts | args '-v /host:/container' |
| docker.label | Label to select Jenkins node with Docker | label 'docker-agent' |
| dockerfile | Build image from Dockerfile in repo | agent { dockerfile true } |
Key Takeaways
Use the Jenkins pipeline
agent { docker { image 'image-name' } } to run builds inside Docker containers.Ensure Docker is installed and Jenkins has permission to run Docker commands on the agent node.
Use
args to pass extra Docker options like volume mounts or user settings.Verify the Docker image name is correct and accessible from the Jenkins agent.
You can build a Docker image from a Dockerfile in your repo using
agent { dockerfile true }.