How to Use Docker in Jenkins Pipeline: Simple Guide
To use
docker in a Jenkins pipeline, you can run Docker commands inside a sh step or use the docker pipeline plugin for better integration. Make sure Jenkins has Docker installed and the user running Jenkins has permission to access Docker.Syntax
In a Jenkins pipeline, Docker commands can be run inside a sh step for scripted pipelines or using the docker pipeline plugin for declarative pipelines.
- sh step: Runs shell commands, including Docker CLI commands.
- docker plugin: Provides methods like
docker.image()to pull and run containers.
groovy
pipeline {
agent any
stages {
stage('Run Docker Command') {
steps {
sh 'docker ps'
}
}
}
}Example
This example shows a Jenkins declarative pipeline that pulls a Docker image and runs a container to print 'Hello from Docker!'. It uses the docker pipeline plugin for clean syntax.
groovy
pipeline {
agent any
stages {
stage('Run Docker Container') {
steps {
script {
docker.image('alpine').inside {
sh 'echo Hello from Docker!'
}
}
}
}
}
}Output
Hello from Docker!
Common Pitfalls
Common mistakes when using Docker in Jenkins pipelines include:
- Jenkins user lacking permission to run Docker commands, causing permission denied errors.
- Not having Docker installed on the Jenkins agent or master node.
- Using
dockercommands without the pipeline plugin, leading to complex shell scripts. - Forgetting to wrap Docker commands inside
shorscriptblocks in declarative pipelines.
groovy
pipeline {
agent any
stages {
stage('Wrong Usage') {
steps {
// This will fail because docker commands need to be inside sh or script
// docker.image('alpine').inside {
// sh 'echo Hello'
// }
sh 'docker ps'
}
}
}
}Quick Reference
| Concept | Usage | Notes |
|---|---|---|
| Run Docker CLI | sh 'docker | Simple but less integrated |
| Use Docker Plugin | docker.image('name').inside { ... } | Cleaner, recommended for declarative pipelines |
| Permissions | Ensure Jenkins user in docker group | Avoid permission denied errors |
| Agent Setup | Docker installed on Jenkins node | Required to run Docker commands |
| Pipeline Type | Scripted or Declarative | Use script block for scripted commands in declarative pipelines |
Key Takeaways
Run Docker commands inside
sh steps or use the Jenkins Docker pipeline plugin for better integration.Ensure Docker is installed and Jenkins user has permission to run Docker commands.
Use
docker.image().inside for clean container execution in declarative pipelines.Wrap Docker commands inside
script blocks when using declarative pipelines.Check Jenkins agent setup to avoid common permission and installation issues.