How to Target Agents by Label in a Jenkins Pipeline
The agent directive picks where a pipeline or stage runs - any node, a labeled node, or inside a Docker container.
Set agent { label '...' } to pin work to nodes with that label, or agent { docker 'image' } to run a stage inside a container. Stage-level agents override the pipeline default.
Label and Docker agents
The pipeline defaults to a linux node; the build stage runs inside a Node container.
Jenkinsfile
pipeline {
agent { label 'linux && docker' }
stages {
stage('Build') {
agent {
docker { image 'node:20'; reuseNode true }
}
steps {
sh 'npm ci && npm run build'
}
}
}
}Gotchas
- Label expressions support
&&and||;linux && dockerrequires both labels. reuseNode truekeeps the Docker stage on the same node/workspace as the surrounding pipeline.- Stage-level
agentoverrides the pipeline-level one for that stage only. - Teams outgrowing static Jenkins nodes can move the same labeled workloads to managed GitHub Actions runners (Latchkey) when they migrate to Actions.
Key takeaways
agent { label }pins work to matching nodes.agent { docker }runs a stage inside a container.- Stage agents override the pipeline default.
Related guides
How to Write a Declarative JenkinsfileWrite a declarative Jenkinsfile with the pipeline, agent, and stages blocks - the structured, opinionated syn…
How to Run Parallel Stages in a Jenkins PipelineRun parallel stages in a Jenkins declarative pipeline with the parallel block, executing independent test or…