How to Use Docker as Agent in Jenkins for CI/CD
To use
Docker as an agent in Jenkins, configure Jenkins to launch build agents inside Docker containers using the Docker plugin or a Docker pipeline step. This setup allows Jenkins to run jobs in isolated containers, improving consistency and scalability.Syntax
Jenkins can use Docker agents in two main ways: through the Docker plugin or by using Docker inside a pipeline script. The key parts are:
- Docker Plugin: Configure a Docker cloud in Jenkins settings and define Docker agent templates.
- Pipeline Syntax: Use
agent { docker { image 'image-name' } }to run pipeline steps inside a Docker container.
groovy
pipeline {
agent {
docker {
image 'jenkins/inbound-agent:latest'
args '-v /var/run/docker.sock:/var/run/docker.sock'
}
}
stages {
stage('Build') {
steps {
sh 'echo Hello from Docker agent'
}
}
}
}Example
This example shows a Jenkins pipeline that runs inside a Docker container using the official Jenkins inbound agent image. It prints a message inside the container.
groovy
pipeline {
agent {
docker {
image 'jenkins/inbound-agent:latest'
args '-v /var/run/docker.sock:/var/run/docker.sock'
}
}
stages {
stage('Build') {
steps {
sh 'echo Hello from Docker agent'
}
}
}
}Output
Hello from Docker agent
Common Pitfalls
Common mistakes when using Docker as Jenkins agents include:
- Not mounting
/var/run/docker.sockwhen Docker commands are needed inside the container, causing failures. - Using images without required tools or Jenkins agent software, leading to connection errors.
- Not configuring proper resource limits, which can overload the host.
- Forgetting to install the Docker plugin in Jenkins before configuring Docker agents.
groovy
/* Wrong: Missing Docker socket mount */ pipeline { agent { docker { image 'jenkins/inbound-agent:latest' } } stages { stage('Build') { steps { sh 'docker ps' } } } } /* Right: Mount Docker socket for Docker commands */ pipeline { agent { docker { image 'jenkins/inbound-agent:latest' args '-v /var/run/docker.sock:/var/run/docker.sock' } } stages { stage('Build') { steps { sh 'docker ps' } } } }
Quick Reference
- Install the Jenkins Docker plugin to enable Docker agent support.
- Define Docker cloud and agent templates in Jenkins global configuration.
- Use
agent { docker { image 'image-name' } }in pipelines for containerized builds. - Mount
/var/run/docker.sockif Docker commands are needed inside the agent. - Choose lightweight images with required tools for faster startup.
Key Takeaways
Use the Jenkins Docker plugin or pipeline Docker agent syntax to run builds inside containers.
Always mount the Docker socket if your build needs to run Docker commands inside the agent.
Choose Docker images that include Jenkins agent software and required build tools.
Configure resource limits to avoid overloading the Jenkins host with containers.
Test your Docker agent setup with simple pipeline scripts before running complex builds.