Jenkins With Docker: Docker Agents, Building Images in Pipelines, Docker-in-Docker Choices and Caching

CI CD Pipelines with Jenkins 40 min min read Updated: Nov 17, 2026 Intermediate
Jenkins With Docker: Docker Agents, Building Images in Pipelines, Docker-in-Docker Choices and Caching
Intermediate Topic 2 of 3

Two Different Uses of Docker

UseMeaningExample
Docker as the build environmentEach stage runs inside a container made from an image that has the right toolsRun mvn inside maven:3.9-eclipse-temurin-21
Building Docker imagesThe pipeline's job is to create and push an image of your applicationdocker build and docker push

Docker Agent: Run a Stage in a Container

Needs the Docker Pipeline (docker-workflow) plugin and Docker installed on the agent machine, with the Jenkins user allowed to use it.

groovy pipeline { agent none stages { stage('Build Java') { agent { docker { image 'maven:3.9-eclipse-temurin-21' args '-v $HOME/.m2:/root/.m2' // cache dependencies between builds reuseNode true } } steps { sh 'mvn -B -DskipTests package' } } stage('Build Node') { agent { docker { image 'node:22-alpine' } } steps { sh 'npm ci && npm test' } } stage('Python in your own image') { agent { dockerfile { filename 'Dockerfile.ci' dir 'ci' additionalBuildArgs '--build-arg PY=3.12' } } steps { sh 'pytest -q' } } } }
  • Jenkins starts the container, mounts the workspace into it, runs your steps inside, then removes the container
  • The user in the container may differ from the Jenkins user. If files end up owned by root, add args '-u 1000:1000' or set the right user
  • Benefit: every developer and agent gets exactly the same tools just by using the same image. No tool installs on agents
  • reuseNode true runs the container on the same node and workspace as the surrounding stage when you set a top-level agent

Build and Push an Image

groovy pipeline { agent { label 'linux && docker' } environment { REGISTRY = 'registry.example.com' IMAGE = "${REGISTRY}/team/shop" TAG = "${env.BUILD_NUMBER}-${env.GIT_COMMIT.take(7)}" } stages { stage('Build image') { steps { script { docker.build("${IMAGE}:${TAG}", '--pull .') } } } stage('Scan') { steps { sh "trivy image --exit-code 1 --severity HIGH,CRITICAL --ignore-unfixed ${IMAGE}:${TAG}" } } stage('Push') { when { branch 'main' } steps { script { docker.withRegistry("https://${REGISTRY}", 'registry-credentials') { def img = docker.image("${IMAGE}:${TAG}") img.push() img.push('latest') } } } } } post { always { sh "docker rmi ${IMAGE}:${TAG} || true" } } }
TagUse
BUILD_NUMBER-GIT_SHATraceable and unique. Deploy this
1.4.2A release version from a tag
latestConvenience only. Do not deploy production from latest

How Does the Build Reach Docker?

A build inside a container cannot simply run docker build: it needs a Docker engine. There are several options with different security trade-offs.

OptionHowRisk and notes
Docker on the agent hostThe agent machine has Docker; the Jenkins user is in the docker groupSimple. The docker group is root-equivalent on that host. Use dedicated agents
Mount the Docker socket-v /var/run/docker.sock:/var/run/docker.sock into a build containerThe build can control the host Docker. Do not use for untrusted code
Docker-in-Docker (dind)A privileged docker:dind sidecar containerNeeds --privileged. Isolated daemon, but privileged and layer cache is lost each time unless a volume is used
Rootless Docker / PodmanA user-level engineSafer, some features limited
Kaniko / BuildKit / BuildahBuild images from a Dockerfile without a Docker daemonGood for Kubernetes agents; no privileged mode needed (Kaniko) or reduced privileges (rootless BuildKit)

Build With Kaniko Inside a Kubernetes Pod (Preview)

groovy pipeline { agent { kubernetes { yaml ''' apiVersion: v1 kind: Pod spec: containers: - name: kaniko image: gcr.io/kaniko-project/executor:debug command: ['sleep'] args: ['infinity'] volumeMounts: - name: docker-config mountPath: /kaniko/.docker volumes: - name: docker-config secret: secretName: regcred items: [{key: .dockerconfigjson, path: config.json}] ''' } } stages { stage('Build and push') { steps { container('kaniko') { sh '/kaniko/executor --context $WORKSPACE --dockerfile Dockerfile --destination registry.example.com/team/shop:$BUILD_NUMBER --cache=true' } } } } }

You will use this pattern again in the Kubernetes agents lesson.

Docker Layer Cache and Speed

  • Use persistent agents (or a volume) so Docker's layer cache survives between builds
  • In Dockerfiles, copy dependency files first, then source, so the cache works
  • With BuildKit use --cache-from and --cache-to type=registry to share cache across agents
  • Pre-pull base images on agents regularly
  • Run docker system prune -f --filter until=72h on agents on a schedule to control disk

Clean Up After Builds

groovy post { always { sh 'docker ps -aq --filter label=build=$BUILD_TAG | xargs -r docker rm -f' sh 'docker image prune -f' cleanWs() } }

Common Errors

ErrorCause and fix
docker: command not foundDocker is not installed on that agent, or you are inside a container without the CLI
permission denied ... docker.sockJenkins user not in the docker group; restart the agent after changing groups
Cannot connect to the Docker daemonDocker service stopped, or DOCKER_HOST points elsewhere
Files in the workspace owned by rootContainer ran as root. Use -u with the Jenkins user ID, or chown at the end
Image pulled every time and builds are slowNo cache. Keep agents persistent, use cache options
unauthorized: authentication required on pushWrong credential ID or registry URL in withRegistry

Practice Tasks

  1. Run a Maven or Node build inside a Docker agent and cache dependencies in a volume
  2. Write a pipeline that builds an image tagged with the build number and short SHA, scans it and pushes it from main only
  3. Use a dockerfile agent with your own CI image
  4. Compare the risks of the docker group, socket mount and Kaniko in a small table
  5. Add automatic image cleanup to the post section

Conclusion

Use Docker agents for repeatable build environments and the Docker Pipeline plugin to build and push images tagged with the build number and commit. Choose how builds reach Docker carefully: the docker group and socket mount are root-equivalent, so prefer isolated agents or daemonless builders such as Kaniko and rootless BuildKit.

Quick Summary: agent docker/dockerfile; cache volume; build+scan+push with withRegistry; tags; options table (group, socket, dind, rootless, kaniko); cache; cleanup; errors.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators