Agents from Docker images

Jenkins CI/CD Course · lesson 10 of 15 · 5 min read

Running a stage inside a container makes the toolchain part of the repo instead of part of the machine.

Open this lesson in the learning hub

Key points

  • A docker agent runs every step of that stage inside a container started from the image you name.
  • Jenkins mounts the workspace into the container and runs it as the agent user id, so files stay writable afterwards.
  • The args string is passed straight to docker run, which is how you mount a dependency cache.
  • dockerfile true builds the image from a Dockerfile in the repo, versioning the toolchain with the code.
  • The host still needs a Docker daemon, and the Jenkins user must have permission to talk to its socket.
  • Pin maven:3.9-eclipse-temurin-17 rather than latest, which changes under you with no commit.

Example

pipeline {
  agent none
  stages {
    stage('Build') {
      agent {
        docker {
          image 'maven:3.9-eclipse-temurin-17'
          // reuse the dependency cache across builds on this agent
          args  '-v $HOME/.m2:/var/maven/.m2 -e MAVEN_CONFIG=/var/maven/.m2'
          label 'docker'
        }
      }
      steps { sh 'mvn -B -ntp -Duser.home=/var/maven verify' }
    }
    stage('Package') {
      agent { label 'docker' }   // needs the real daemon, not a container
      steps { sh 'docker build -t $IMAGE .' }
    }
  }
}

Put the toolchain in a pinned image so upgrading it is a commit, and keep daemon access on trusted agents.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Jenkins CI/CD Course course, and every lesson in it is listed on the Jenkins CI/CD Course contents page.