The agent Directive

The agent directive decides where a pipeline or stage runs — on any node, a labeled node, or inside a Docker container.

Syntaxagent { docker { image 'maven:3.9' } }

The agent directive tells Jenkins where to execute work. It is required at the top level of a declarative pipeline and can be overridden per stage.

Common agent forms

  • agent any — run on any available agent.
  • agent none — no global agent; each stage must define its own.
  • agent { label 'linux' } — run on an agent with that label.
  • agent { docker 'node:20' } — run inside a fresh Docker container.

Docker agents

Running inside a container gives every build a clean, reproducible environment with exactly the tools you need — no manual setup on the agent.

Example

Example · bash
pipeline {
    agent none
    stages {
        stage('Build') {
            agent { docker { image 'node:20-alpine' } }
            steps {
                sh 'node --version'
                sh 'npm ci && npm run build'
            }
        }
        stage('Test in Python') {
            agent { docker { image 'python:3.12' } }
            steps {
                sh 'python --version'
            }
        }
    }
}

When to use it

  • A pipeline uses agent { docker 'node:20' } so every build gets a fresh Node.js environment without installing Node on agents.
  • A stage overrides the top-level agent to run a database migration on a dedicated agent that has the DB client tools installed.
  • A team sets agent none at the top level and assigns each stage its own agent to save agent capacity during long pipelines.

More examples

Run pipeline on any agent

Uses agent any to schedule the pipeline on the first available Jenkins agent or built-in node.

Example · groovy
pipeline {
  agent any
  stages {
    stage('Build') {
      steps { sh 'mvn package' }
    }
  }
}

Run in a Docker container

Runs the entire pipeline inside a Node 20 Alpine container, mounting /tmp for caching.

Example · groovy
pipeline {
  agent {
    docker {
      image 'node:20-alpine'
      args  '-v /tmp:/tmp'
    }
  }
  stages {
    stage('Test') {
      steps { sh 'node --version && npm test' }
    }
  }
}

Per-stage agent with label

Assigns different labeled agents to each stage, routing Maven work to a Maven agent and Docker push to a Docker agent.

Example · groovy
pipeline {
  agent none
  stages {
    stage('Build') {
      agent { label 'maven && linux' }
      steps { sh 'mvn package' }
    }
    stage('Publish') {
      agent { label 'docker' }
      steps { sh 'docker push myapp:latest' }
    }
  }
}

Discussion

  • Be the first to comment on this lesson.