Jenkins normally run builds in the local machine. That means all the dependencies the build needs needs to be set up in the local machine. You can delegate these to other machines by setting up another host machine as jenkins slave.
Also check
- How to Install and Use Docker in Ubuntu 20.04
- Getting Started With Docker Compose With Examples
- How to install and configure docker In Centos 8
You can, however use Docker containers to build the jobs. You can delegating the compile, test, package and deploy steps to a Docker container meaning you wont need to set up the host with build tools such as npm or gradle.
You use preconfigured Docker images that contain all the build tools you want.
Steps
- Install Jenkins
- Install docker
- Add OS user
jenkins
todocker
group. - Add the Jenkins Docker plugin and Jenkins Docker pipeline plugin
- Reference Docker images in your Jenkinsfile builds
Adding Jenkins user to docker group
If running in the OS:
sudo usermod -aG docker jenkins
Install required plugins
Install these two plugins:
- docker-plugin (Docker)
- docker-workflow (Docker Pipeline)
Reference Docker images in your Jenkinsfile
Simple job
pipeline {
agent { docker { image 'maven:latest' } }
stages {
stage('log version info') {
steps {
sh 'mvn --version'
sh 'mvn clean install'
}
}
}
}
When this pipeline runs, the Jenkins build happens on a Docker container. The maven:latest
image is downloaded if it doesn’t exist locally then a container is created from it where the mvn
commands will be run. if any artifacts are created, the Jenkins Docker build places these in the workspace in the local file system so they persist after the container is taken offline.
Another job
pipeline {
environment {
registry = "username/app"
registryCredential = 'docker-registry-creds'
dockerImage = ''
}
agent any
stages {
stage('Cloning the project from git') {
steps {
git branch: 'main',
credentialsId: 'github-token-creds',
url: 'https://github.com/username/app.git'
}
}
stage('Building our image') {
steps {
script {
dockerImage = docker.build registry + ":${BUILD_NUMBER}"
}
}
}
stage('Push our image to the registry') {
steps {
script {
docker.withRegistry( '', registryCredential ) {
dockerImage.push()
}
}
}
}
stage('Using an image to execute some commands') {
steps {
script {
docker.image('maven:3.8.1-jdk-11-slim').inside {
sh """
mvn -DskipTests=true install
"""
}
}
}
}
stage('Cleaning up') {
steps {
sh "docker rmi ${registry}:${BUILD_NUMBER}"
}
}
}
}