The end of module 7 exposed a weakness: linux-agent-01 is a permanent agent that shares its workspace, caches and tools across every build, and each new tool means rebuilding its image. Containers solve both problems at once. Each stage can run in an image that brings exactly the tools it needs (Maven, Node, Python, a browser...) and disappears when it finishes, and the build itself can produce a container image, which is how orders-api will reach Kubernetes in the next lesson. In this lesson you will give TecnoShop's builds an isolated Docker daemon (docker-dind), publish version 2 of the agent image with the Docker client, set up the registry.tecnoshop.local registry on top of the Nexus docker-tecnoshop repository, learn the Docker Pipeline plugin (agent { docker }, agent { dockerfile }, docker.build, withRegistry, withRun) and build, scan with Trivy and publish the orders-api image with two new tecnoshop-lib steps. catalog-web, for its part, will stop depending on the agent's Node installations.

Why Containers in Builds

Problem with the permanent agent What running the stage in a container brings
Tools are installed in the agent image and every project inherits all of them Each stage declares its image (maven:3.9-eclipse-temurin-21, node:22-bookworm-slim): the project picks its tools without asking the platform team for anything
Changing a tool means rebuilding and restarting the agent Changing the image is changing one line of the Jenkinsfile, reviewed in a PR
Two versions of the same tool do not coexist well (Node 20 and 22, JDK 17 and 21) Each container has its own, with no conflicts
Leftovers from one build affect the next (files in /tmp, orphaned processes) The container is destroyed when the stage ends
"It works on my machine" Developers can run the same image on their laptops

And there is a second reason, independent of the first: the product of orders-api is going to be a container image. To build it, the build needs an image engine.

Two ideas that are best kept apart:

  • Containers to run the build: the agent is still linux-agent-01, but it launches containers for some stages. This is what you will see in this lesson.
  • Agents that are ephemeral containers: the whole agent is born for a build and dies when it finishes. With Docker, the Docker plugin does this (Docker Cloud), introduced in Scaling Jenkins; with Kubernetes, the Kubernetes plugin does it, in Jenkins and Kubernetes.

How Docker Reaches a Build: Options and Risks

For a build to use docker, the client (the docker command) needs to talk to a daemon (dockerd), which is what creates containers and builds images. The key question is which daemon:

Option How it works Risk Assessment at TecnoShop
Mount the host's /var/run/docker.sock into the agent The agent uses the daemon of the machine that hosts it Whoever talks to the socket can run docker run -v /:/host --privileged ... and is root on the host. Any PR with an sh 'docker ...' would have that power. It can also see and stop the Jenkins, Nexus... containers Discouraged: you will see it in many tutorials precisely because it is the easiest
Docker-in-Docker (docker:dind) A container runs its own dockerd; the agent talks to it over TCP with TLS The dind container must be privileged, which loosens its isolation from the host kernel. But the builds do not see the platform's containers Lab: a bounded, controlled risk
Rootless Docker / Podman The daemon (or Podman, which has no daemon) runs without root Much lower; some features (networking, certain storage drivers) have limitations. Running it inside a container still requires loosening part of the isolation A good option on agents in a dedicated virtual machine
Daemonless builders: Kaniko, rootless BuildKit, Buildah They build images from a Dockerfile without dockerd Low; they cannot run containers, only build images Kaniko will be used in 08-02
Agent in a virtual machine dedicated to Docker builds The daemon belongs to a VM that only runs builds The VM provides the isolation: if a build compromises it, it is destroyed and recreated The robust option for production with Docker

The underlying rule: giving Docker to a build means giving the build control of that daemon. That is why the builds' daemon must never be the same as the platform's.

An Isolated Daemon for the Lab: docker-dind with TLS

flowchart LR
    subgraph compose["Compose network (~/tecnoshop-jenkins)"]
        C["jenkins-controller"]
        A["linux-agent-01<br/>tecnoshop/linux-agent:2<br/>docker client"]
        D["docker-dind<br/>dockerd privileged<br/>:2376 TLS"]
        R["registry (nginx)<br/>alias registry.tecnoshop.local"]
        N["nexus<br/>docker-tecnoshop :8083"]
    end
    V[("volume linux_agent_01<br/>/home/jenkins/agent")]
    CERT[("docker_certs_client")]
    C -->|"WebSocket"| A
    A -->|"DOCKER_HOST=tcp://docker-dind:2376"| D
    D -->|"push / pull"| R --> N
    V --- A
    V --- D
    CERT --- A
    CERT --- D

Add the service to the docker-compose.yml in ~/tecnoshop-jenkins:

  docker-dind:
    image: docker:<version>-dind          # pin a specific version, as in 05-04
    container_name: docker-dind
    hostname: docker-dind
    privileged: true                      # required to run dockerd inside a container
    restart: unless-stopped
    command: ["--insecure-registry=registry.tecnoshop.local"]   # LAB ONLY (section 5)
    environment:
      DOCKER_TLS_CERTDIR: /certs
    volumes:
      - docker_dind_data:/var/lib/docker
      - docker_certs_ca:/certs/ca
      - docker_certs_client:/certs/client
      - linux_agent_01:/home/jenkins/agent

volumes:
  # ... the existing volumes ...
  docker_dind_data:
    name: docker_dind_data
  docker_certs_ca:
    name: docker_certs_ca
  docker_certs_client:
    name: docker_certs_client

Line by line:

  • image: docker:<version>-dind: the official Docker image with the daemon. Replace the placeholder with a specific version.
  • hostname: docker-dind: on first start, the image generates a certificate authority plus server and client certificates. The server certificate includes the container's host name; setting it makes it match the name the agent will use to reach it (docker-dind), so TLS verification works.
  • privileged: true: dockerd needs to create namespaces, mount file systems and manage networks, things a regular container cannot do. A privileged container has almost the same powers as a root process on the host: the risk does not go away, it is contained. We accept it in the lab because the daemon only serves the builds, is not published on the host and shares nothing with the platform.
  • command: ["--insecure-registry=registry.tecnoshop.local"]: arguments for dockerd (the image prepends dockerd when the first argument starts with -). It allows talking to the lab registry over HTTP. At TecnoShop the registry has HTTPS with a company certificate and this line does not exist.
  • DOCKER_TLS_CERTDIR: /certs: enables TLS. The daemon listens on port 2376 and only accepts clients with a certificate signed by its authority.
  • docker_dind_data: downloaded images and layers. It survives the container being recreated (it is the base image cache for every build).
  • docker_certs_client: the client certificate and key, which the agent will mount.
  • linux_agent_01:/home/jenkins/agent: the agent's volume, at the same path. This is the least obvious piece and the most important one: when the Docker Pipeline plugin launches a container for a stage, it asks the daemon to mount the workspace (-v /home/jenkins/agent/workspace/...:...). That path is looked up in the daemon's file system, not the agent's. If it does not exist there, the container starts with an empty directory and the build cannot find its code.

No port is published: the daemon is only reachable inside the Compose network.

tecnoshop/linux-agent:2: The Agent with the Docker Client

Following the rule from 07-05 (nothing is installed by hand), Laura adds the client to the image and, while she is at it, takes care of what was left pending in 06-02: pinning the exact version of the base image, and with it the JDK version. ~/tecnoshop-jenkins/linux-agent/Dockerfile:

# TecnoShop agent image v2: pinned inbound-agent + gitleaks + Trivy + Docker client.
FROM jenkins/inbound-agent:<version>-jdk21

ARG GITLEAKS_VERSION=X.Y.Z
ARG GITLEAKS_SHA256=replace-with-the-sha256-of-the-linux_x64-tar-gz
ARG TRIVY_VERSION=X.Y.Z
ARG TRIVY_SHA256=replace-with-the-sha256-of-the-Linux-64bit-tar-gz
# Package versions from the Docker repository (apt-cache madison docker-ce-cli)
ARG DOCKER_CLI_VERSION=replace-with-the-package-version
ARG DOCKER_BUILDX_VERSION=replace-with-the-package-version

USER root
# 1. gitleaks and Trivy: same as in version 1 (07-05)
RUN set -eu; \
    cd /tmp; \
    curl -fsSLo gitleaks.tar.gz \
      "https://github.com/gitleaks/gitleaks/releases/download/v${GITLEAKS_VERSION}/gitleaks_${GITLEAKS_VERSION}_linux_x64.tar.gz"; \
    echo "${GITLEAKS_SHA256}  gitleaks.tar.gz" | sha256sum -c -; \
    tar -xzf gitleaks.tar.gz gitleaks; install -m 0755 gitleaks /usr/local/bin/gitleaks; \
    curl -fsSLo trivy.tar.gz \
      "https://github.com/aquasecurity/trivy/releases/download/v${TRIVY_VERSION}/trivy_${TRIVY_VERSION}_Linux-64bit.tar.gz"; \
    echo "${TRIVY_SHA256}  trivy.tar.gz" | sha256sum -c -; \
    tar -xzf trivy.tar.gz trivy; install -m 0755 trivy /usr/local/bin/trivy; \
    rm -f /tmp/gitleaks* /tmp/trivy*

# 2. Docker client and buildx from the official repository (signed packages)
RUN set -eu; \
    install -m 0755 -d /etc/apt/keyrings; \
    curl -fsSL https://download.docker.com/linux/debian/gpg -o /etc/apt/keyrings/docker.asc; \
    echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] \
https://download.docker.com/linux/debian $(. /etc/os-release && echo "$VERSION_CODENAME") stable" \
      > /etc/apt/sources.list.d/docker.list; \
    apt-get update; \
    apt-get install -y --no-install-recommends \
      "docker-ce-cli=${DOCKER_CLI_VERSION}" "docker-buildx-plugin=${DOCKER_BUILDX_VERSION}"; \
    rm -rf /var/lib/apt/lists/*; \
    gitleaks version; trivy --version; docker --version; docker buildx version

ENV TRIVY_CACHE_DIR=/home/jenkins/agent/.cache/trivy
USER jenkins

What is new:

  • FROM jenkins/inbound-agent:<version>-jdk21: an exact tag (you will find it on Docker Hub; for example, the one matching the agent.jar version of your LTS). From now on, the JDK used by the Maven builds on the agent is pinned as well.
  • The Docker repository is added with its key in /etc/apt/keyrings and signed-by: apt will reject any package not signed with that key. Check the key's fingerprint against the official Docker documentation the first time.
  • Only the client (docker-ce-cli) and docker-buildx-plugin are installed, the latter being the modern BuildKit-based builder that docker build uses by default. The daemon is not installed: the agent does not run containers, it asks docker-dind to.
  • Package versions are pinned with package=version; apt-cache madison docker-ce-cli inside a test container shows you the available ones.

In the agent's service, the tag, the variables and one volume change:

  linux-agent-01:
    build: ./linux-agent
    image: tecnoshop/linux-agent:2
    container_name: linux-agent-01
    restart: unless-stopped
    depends_on:
      - jenkins-controller
      - docker-dind
    environment:
      JENKINS_URL: http://jenkins-controller:8080/
      JENKINS_AGENT_NAME: linux-agent-01
      JENKINS_SECRET: ${LINUX_AGENT_01_SECRET}
      JENKINS_WEB_SOCKET: "true"
      JENKINS_AGENT_WORKDIR: /home/jenkins/agent
      DOCKER_HOST: tcp://docker-dind:2376
      DOCKER_TLS_VERIFY: "1"
      DOCKER_CERT_PATH: /certs/client
    volumes:
      - linux_agent_01:/home/jenkins/agent
      - docker_certs_client:/certs/client:ro
  • DOCKER_HOST: where the daemon is. Any docker ... on the agent (and in its builds, which inherit the environment of the agent process) will go to docker-dind.
  • DOCKER_TLS_VERIFY: "1" and DOCKER_CERT_PATH: use TLS, verify the server certificate against ca.pem and present cert.pem/key.pem.
  • docker_certs_client:/certs/client:ro: the agent only reads the certificates.
cd ~/tecnoshop-jenkins
docker compose up -d docker-dind
docker compose up -d --build linux-agent-01
docker compose exec linux-agent-01 docker version
docker compose exec linux-agent-01 docker run --rm hello-world

docker version must show two blocks, Client (the agent's) and Server (that of docker-dind). In Manage Jenkins → Nodes → linux-agent-01 → Configure, add the docker label (the labels become linux docker): this way pipelines can ask for "an agent that can run Docker" without knowing which one it is.

The Lab Registry: registry.tecnoshop.local on Top of Nexus

In 06-05 you created the docker-tecnoshop repository in Nexus (hosted, HTTP connector on port 8083, Disable redeploy) and said that registry.tecnoshop.local would be that repository published behind a proxy. In the lab, that proxy is an nginx with the network alias registry.tecnoshop.local, so that image references are the same as at TecnoShop (registry.tecnoshop.local/orders-api).

~/tecnoshop-jenkins/lab/registry/nginx.conf:

server {
    listen 80;
    server_name registry.tecnoshop.local localhost;

    client_max_body_size 0;          # no limit: layers can take up hundreds of MB
    proxy_request_buffering off;     # sends the layers to Nexus as they arrive

    location / {
        proxy_pass http://nexus:8083;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_read_timeout 900;
    }
}
  registry:
    image: nginx:<version>-alpine
    container_name: registry
    restart: unless-stopped
    volumes:
      - ./lab/registry/nginx.conf:/etc/nginx/conf.d/default.conf:ro
    ports:
      - "127.0.0.1:5000:80"      # to push images from your machine (localhost:5000)
    networks:
      default:
        aliases:
          - registry.tecnoshop.local
Name At TecnoShop From the agent and docker-dind From your machine
Image registry https://registry.tecnoshop.local registry.tecnoshop.local (HTTP, an insecure registry for the daemon) localhost:5000
  • Docker tries HTTPS on port 443 first; since the daemon has the registry marked as insecure and nginx does not listen on 443, it falls back to HTTP on port 80. Lab only: over HTTP, credentials travel in clear text.
  • Docker treats localhost as insecure without any configuration, which is why you will use localhost:5000 from your machine. The image is the same: Nexus stores tecnoshop/linux-agent:2 regardless of the host name it arrived through.

The jenkins-push User and the registry-tecnoshop Credential

In 06-05 you created registry-tecnoshop with a fake value. Now it gets a real one, with least privilege:

  1. In Nexus, Security → Roles → Create role: ID tecnoshop-images, privilege nx-repository-view-docker-docker-tecnoshop-* except delete.
  2. Security → Users → Create local user: ID jenkins-push, role tecnoshop-images, a long random password.
  3. Remove the docker-tecnoshop privilege from the tecnoshop-publishing role: jenkins-deployer publishes jars, jenkins-push publishes images. If a credential leaks, the damage is limited to one type of artifact.
  4. In Jenkins, Update registry-tecnoshop: username jenkins-push, the new password, description Registry registry.tecnoshop.local (push to docker-tecnoshop, no delete). Owner: Laura.

Publishing the Agent Image

As promised in 07-05: the agent image is stored in the registry, versioned, so it can be used as the base for ephemeral agents.

cd ~/tecnoshop-jenkins
docker login localhost:5000            # with your Nexus user
docker tag tecnoshop/linux-agent:2 localhost:5000/tecnoshop/linux-agent:2
docker push localhost:5000/tecnoshop/linux-agent:2

In Nexus, Browse → docker-tecnoshop shows tecnoshop/linux-agent with the 2 tag. From the Compose network (and from Kubernetes in the next lesson) it is registry.tecnoshop.local/tecnoshop/linux-agent:2.

The Docker Pipeline Plugin

Install Docker Pipeline (ID docker-workflow) using the procedure from 05-04: add it to plugins.txt with its version, validate it on jenkins-test and rebuild the controller image. It provides:

Element Type What for
agent { docker { ... } } Declarative Run a stage (or the pipeline) inside a container
agent { dockerfile { ... } } Declarative The same, with an image built from a Dockerfile in the repository
docker.image('...').inside { } docker variable (in script) Run steps inside a container
docker.build(...), image.push() docker variable Build and push images
docker.withRegistry(url, credential) { } docker variable Authenticate to a registry for the duration of a block
image.withRun('...') { c -> } docker variable Start a container in the background and destroy it when the block exits

In Manage Jenkins → System → Declarative Pipeline (Docker) you can set a default Docker Label (docker): stages with agent { docker } will go to an agent with that label even if they do not specify it. Do it: TecnoShop does not want a stage that needs Docker to land on an agent without Docker.

The plugin uses the agent's docker command, with the agent's environment: at TecnoShop, the DOCKER_HOST pointing to docker-dind.

agent { docker }: A Stage Inside a Container

Create a practice Pipeline job, lab-docker, with this script (you will not see it in the job list of Diego's roles: it does not start with orders-):

pipeline {
    agent {
        label 'docker'
    }
    stages {
        stage('Code') {
            steps {
                git url: 'https://github.com/tecnoshop/orders-api.git', branch: 'main',
                    credentialsId: 'github-tecnoshop'
                sh 'java -version 2>&1 | head -n 1; docker version --format "Docker server: {{.Server.Version}}"'
            }
        }
        stage('Build in a Maven container') {
            agent {
                docker {
                    image 'maven:3.9-eclipse-temurin-21'
                    reuseNode true
                    args '-v /home/jenkins/agent/.m2:/home/jenkins/agent/.m2 ' +
                         '-e MAVEN_USER_HOME=/home/jenkins/agent/.m2 --network host'
                }
            }
            steps {
                sh 'id; java -version 2>&1 | head -n 1'
                sh './mvnw -B -ntp clean verify'
            }
        }
    }
    post {
        cleanup {
            cleanWs()
        }
    }
}

What happens in the second stage:

  1. The plugin pulls the image if the daemon does not have it (docker pull), the first time.
  2. It runs docker run -d -t -u 1000:1000 -w <workspace> -v <workspace>:<workspace> -v <workspace>@tmp:<workspace>@tmp <args> maven:3.9-eclipse-temurin-21 cat. The container is left "waiting" with cat.
  3. Each sh runs inside it with docker exec, with the build's variables.
  4. When the stage ends, docker stop and docker rm: the container disappears; the files it wrote to the workspace stay.

The options:

  • image 'maven:3.9-eclipse-temurin-21': Maven 3.9 on Temurin 21. orders-api uses its own ./mvnw, so it only takes the JDK from the image; an eclipse-temurin:21-jdk image would work just as well. Choosing the Maven one makes it clear what the stage does and allows using mvn in projects without a wrapper.
  • reuseNode true: does not request a new agent. The container runs on the same agent and on the same workspace as the pipeline, so it sees the code cloned by the previous stage. Without reuseNode, the stage would get another (empty) workspace and do its own checkout.
  • -u 1000:1000 is added by the plugin on its own: the agent user (jenkins). This keeps the workspace files from being owned by root. In the Maven image that UID has no user or home directory, which is why it is given MAVEN_USER_HOME, where the wrapper stores the Maven distribution.
  • -v /home/jenkins/agent/.m2:...: the Maven cache. The node variable MAVEN_OPTS=-Dmaven.repo.local=/home/jenkins/agent/.m2/repository from 05-01 reaches the container (it is a build variable), and the mount makes that path exist inside with the contents of the agent's volume. Remember that the path is resolved on docker-dind, which has the same volume at the same path.
  • --network host: the container uses the network of the daemon (docker-dind), which is on the Compose network. This way it resolves nexus (the Maven mirror in the managed settings) just as the agent does. On the default network of a nested daemon, containers do not see the Compose names.

Other useful options of docker { }: label (on which agents), alwaysPull true (always check for a new version of the tag), registryUrl and registryCredentialsId (images from a private registry), customWorkspace.

Stage or Whole Pipeline?

Form Example When
At pipeline level agent { docker { image 'node:22-bookworm-slim' } } at the top Every stage needs the same image and none needs tools from the agent
Per stage with reuseNode true The example above Some stages use agent tools (gitleaks, Trivy, docker, ssh) and others a specific image, on the same workspace
Per stage without reuseNode The cells of a matrix Each stage is independent and can go to any agent with Docker

For orders-api, TecnoShop does not move the Maven stages to containers yet: the agent already has a pinned JDK 21, and in the next lesson the whole build will run in a pod with a maven container. Moving them now would be work undone a few days later.

agent { dockerfile }: The Build Image, Versioned with the Code

When no public image brings what you need, the repository can include the Dockerfile of its build environment:

stage('Architecture report') {
    agent {
        dockerfile {
            filename 'Dockerfile.tools'
            dir 'ci'
            label 'docker'
            additionalBuildArgs '--build-arg GRAPHVIZ_VERSION=2.42'
            reuseNode true
        }
    }
    steps {
        sh 'dot -V'
    }
}
  • The plugin builds ci/Dockerfile.tools (with ci/ as the context) and runs the stage in the resulting image. The image tag is a hash of the contents, so it is only rebuilt when the file changes.
  • Advantage: the tool and its version are reviewed in the same PR as the code that uses it.
  • Drawback: each repository maintains its own image and builds it on its agents. If several applications need the same thing, a common image published in registry.tecnoshop.local is better.

Do not confuse this Dockerfile (the environment the build runs in) with the application Dockerfile (what gets deployed), which you will see shortly.

The docker Variable in script: inside, build and withRun

Inside a script block (or in a library), the global docker variable gives the same power with more control:

script {
    def node22 = docker.image('node:22-bookworm-slim')
    node22.pull()
    node22.inside('--network host') {
        sh 'node --version'
    }
}
  • docker.image(name): an object that represents the image (it does not pull it yet).
  • inside(args) { ... }: the same as agent { docker } with reuseNode true, but at any point within a step.

withRun starts a container in the background and destroys it when the block exits, even if there is an error. It is the way to have auxiliary services during a test run. The day orders-api has a database (the Flyway migrations from 07-04), its integration tests could do this:

script {
    docker.image('postgres:17').withRun('-e POSTGRES_PASSWORD=test-only-fake -e POSTGRES_DB=orders -P') { db ->
        def port = sh(script: "docker port ${db.id} 5432/tcp | head -n 1 | sed 's/.*://'",
                      returnStdout: true).trim()
        withEnv(["SPRING_DATASOURCE_URL=jdbc:postgresql://docker-dind:${port}/orders"]) {
            sh './mvnw -B -ntp failsafe:integration-test failsafe:verify'
        }
    }
}
  • -P: publishes the container's ports on free ports of the daemon; that way two simultaneous builds do not collide.
  • db.id: the container ID; docker port tells you which port 5432 ended up on.
  • docker-dind:${port}: from the agent, published ports are on the daemon's host, which in the lab is called docker-dind.
  • The password is disposable, only for a container that lives a few minutes.

Today orders-api has no database, but you will use withRun to check that its own image starts.

The orders-api Image: Dockerfile and .dockerignore

In the root of orders-api, Diego adds the application Dockerfile. It is built from the jar already tested in the build, not by compiling again: build once, deploy many times (07-01).

# Runtime image for orders-api. The jar is produced by the Package stage of the same build.
FROM eclipse-temurin:21-jre

ARG VERSION
ARG COMMIT=unknown
ARG BUILD_DATE=unknown

LABEL org.opencontainers.image.title="orders-api" \
      org.opencontainers.image.description="TecnoShop order management REST API" \
      org.opencontainers.image.version="${VERSION}" \
      org.opencontainers.image.revision="${COMMIT}" \
      org.opencontainers.image.created="${BUILD_DATE}" \
      org.opencontainers.image.source="https://github.com/tecnoshop/orders-api" \
      org.opencontainers.image.vendor="TecnoShop"

RUN set -eu; \
    apt-get update; \
    apt-get install -y --no-install-recommends curl; \
    rm -rf /var/lib/apt/lists/*; \
    groupadd --system --gid 10001 orders; \
    useradd --system --uid 10001 --gid orders --no-create-home --shell /usr/sbin/nologin orders

WORKDIR /app
COPY --chown=10001:10001 target/orders-api-${VERSION}.jar /app/orders-api.jar

USER 10001:10001
EXPOSE 8081

HEALTHCHECK --interval=30s --timeout=3s --start-period=60s --retries=3 \
  CMD curl -fsS http://localhost:8081/actuator/health/readiness || exit 1

ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "/app/orders-api.jar"]

Line by line:

  • FROM eclipse-temurin:21-jre: only the Java 21 runtime environment, without a compiler: a smaller image with fewer packages to scan. More minimal variants (distroless, Alpine) reduce Trivy's findings even further, at the cost of having no shell or curl for troubleshooting.
  • ARG VERSION, COMMIT, BUILD_DATE: values passed in by the build (--build-arg). VERSION is mandatory because it forms the jar name.
  • LABEL org.opencontainers.image.*: the standard OCI labels. Anyone who has the image can find out which version and which commit it comes from (docker inspect), without depending on Jenkins.
  • apt-get install curl: for the HEALTHCHECK. It is installed explicitly so as not to depend on what the base image happens to include today.
  • groupadd/useradd with UID 10001 and USER 10001:10001: the application does not run as root. If someone exploited a vulnerability in the application, they would have no privileges inside the container. Using the number, not the name, lets Kubernetes check runAsNonRoot in the next lesson.
  • COPY --chown=10001:10001 target/orders-api-${VERSION}.jar: only the jar, owned by the application user.
  • EXPOSE 8081: documents the port (server.port=8081 since 01-04).
  • HEALTHCHECK: Docker periodically checks the Actuator readiness health group and marks the container as healthy or unhealthy. Kubernetes ignores this instruction and uses its own probes (08-02), but it is useful when running the image with Docker.
  • ENTRYPOINT [...] in list form: Java is the main process (PID 1) and receives the stop signal directly. -XX:MaxRAMPercentage=75 sizes the heap based on the container's memory.

Spring Boot enables the /actuator/health/readiness and /actuator/health/liveness groups automatically on Kubernetes; to have them with Docker and on the virtual machines as well, add this to src/main/resources/application.properties:

management.endpoint.health.probes.enabled=true

And the .dockerignore, which decides what is sent to the daemon as the build context:

# Only the application jar goes into the image context
*
!target/orders-api-*.jar
  • * excludes everything; ! includes the given path again. Without this file, docker build . would send the whole repository (including .git) to the daemon: slower, and with the risk of putting something into the image that should not be there.

Try it on your machine, after a ./mvnw -B package:

docker build --build-arg VERSION=1.2.0-SNAPSHOT -t orders-api:local .
docker run --rm -d -p 18081:8081 --name orders-local orders-api:local
curl -s localhost:18081/actuator/health/readiness; echo
docker inspect --format '{{.State.Health.Status}} {{index .Config.Labels "org.opencontainers.image.version"}}' orders-local
docker stop orders-local

buildImage and publishImage in tecnoshop-lib v1.6.0

Building, scanning and publishing images will be the same for every TecnoShop service: it goes into the library, as two steps, because they run at different points in the build. Building and scanning happen in every build, PRs included (a broken Dockerfile or a vulnerable base image is caught before merging); publishing, only where the jar is published today.

vars/buildImage.groovy:

/**
 * Builds the project image, scans it with Trivy and checks that it starts and responds.
 *
 *   buildImage image: env.IMAGE, tag: env.IMAGE_TAG, version: env.APP_VERSION
 *   buildImage image: ..., tag: ..., version: ..., healthPath: false   // no smoke test
 *
 * Requires an agent with the Docker client (DOCKER_HOST) and Trivy: tecnoshop/linux-agent:2.
 * Leaves image-bom.json (the image SBOM) archived.
 */
def call(Map config = [:]) {
    for (String required : ['image', 'tag', 'version']) {
        if (!config[required]) {
            error "buildImage: missing parameter \"${required}\""
        }
    }
    String reference = "${config.image}:${config.tag}"
    String date = sh(script: 'date -u +%Y-%m-%dT%H:%M:%SZ', returnStdout: true, label: 'Image date').trim()

    def image = docker.build(reference,
        "--pull --build-arg VERSION=${config.version} --build-arg COMMIT=${env.GIT_COMMIT ?: 'unknown'} " +
        "--build-arg BUILD_DATE=${date} ${config.context ?: '.'}")

    String ignoreOpt = fileExists('.trivyignore') ? '--ignorefile .trivyignore' : ''
    withEnv(["REFERENCE=${reference}", "IGNORE_OPT=${ignoreOpt}"]) {
        sh label: 'Image vulnerabilities (Trivy)', script: '''
            docker save -o image.tar "$REFERENCE"
            trivy image --input image.tar --severity HIGH,CRITICAL --format table --exit-code 0 $IGNORE_OPT
            trivy image --input image.tar --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 --quiet $IGNORE_OPT
            trivy image --input image.tar --format cyclonedx --output image-bom.json --quiet
            rm -f image.tar
        '''
    }
    archiveArtifacts artifacts: 'image-bom.json'

    if (config.healthPath != false) {
        String host = (env.DOCKER_HOST ?: 'tcp://localhost:2375').replaceFirst(/^tcp:\/\//, '').replaceFirst(/:\d+$/, '')
        image.withRun('-P') { c ->
            withEnv(["CONTAINER=${c.id}", "DOCKER_HOST_NAME=${host}",
                     "PORT=${config.port ?: 8081}", "HEALTH_PATH=${config.healthPath ?: '/actuator/health/readiness'}"]) {
                sh label: 'Image smoke test', script: '''
                    MAPPING=$(docker port "$CONTAINER" "$PORT/tcp" | head -n 1)
                    URL="http://$DOCKER_HOST_NAME:${MAPPING##*:}$HEALTH_PATH"
                    for i in $(seq 1 30); do
                        if curl -fsS "$URL"; then echo; echo "==> The image starts and responds at $URL"; exit 0; fi
                        sleep 2
                    done
                    echo "ERROR: the image does not respond at $URL"; docker logs --tail 50 "$CONTAINER"; exit 1
                '''
            }
        }
    }
    return reference
}

The key points:

  • docker.build(reference, arguments): runs docker build -t <reference> <arguments>. When arguments are passed, the last one must be the context (.).
  • --pull: always checks for a new version of eclipse-temurin:21-jre. Base images receive security patches frequently; with --pull, each build picks up the latest ones (07-05). The price is that two builds of the same commit may have different bases; traceability comes from the digest recorded at publish time. For strict reproducibility, the base is pinned by digest (FROM eclipse-temurin:21-jre@sha256:...) and a tool such as Renovate or Dependabot proposes each update in a PR.
  • docker save -o image.tar + trivy image --input: Trivy scans the exported file. That way it does not depend on how it reaches the daemon, and the same scan will work with Kaniko in the next lesson.
  • The three Trivy calls follow the policy from 07-05: show high and critical findings; fail on high or critical findings that have a fix (--ignore-unfixed, a TecnoShop security decision for images); generate the image SBOM (image-bom.json), which complements the jar's.
  • withRun('-P') + docker port: starts the freshly built image and checks the readiness group. It catches what a green Trivy run cannot see: a mistyped ENTRYPOINT, a jar with a different name, a user without permissions.
  • withEnv instead of interpolation: the values reach the shell as variables, as in smokeSpringBoot.

vars/publishImage.groovy:

/**
 * Pushes an image built with buildImage to the registry and records its digest.
 *
 *   publishImage image: env.IMAGE, tag: env.IMAGE_TAG                          // SNAPSHOT from main
 *   publishImage image: env.IMAGE, tag: env.IMAGE_TAG, extraTags: ['1.2.0']    // release
 *
 * Leaves the digest reference in env.IMAGE_DIGEST, in image-digest.txt and in build-info.txt.
 */
def call(Map config = [:]) {
    String reference = "${config.image}:${config.tag}"
    def image = docker.image(reference)

    docker.withRegistry(config.registry ?: 'https://registry.tecnoshop.local', config.credential ?: 'registry-tecnoshop') {
        image.push()
        for (String extraTag : (config.extraTags ?: [])) {
            image.push(extraTag)
        }
    }

    String digest = sh(script: "docker inspect --format '{{index .RepoDigests 0}}' ${reference}",
                       returnStdout: true, label: 'Digest of the published image').trim()
    writeFile file: 'image-digest.txt', text: "${digest}\n"
    if (fileExists('build-info.txt')) {
        writeFile file: 'build-info.txt', text: readFile('build-info.txt') + "image.digest=${digest}\n"
    }
    archiveArtifacts artifacts: 'image-digest.txt,build-info.txt', fingerprint: true, allowEmptyArchive: true

    env.IMAGE_DIGEST = digest
    currentBuild.description = "${currentBuild.description ?: ''} · image ${config.tag}"
    echo "publishImage: ${digest}"
    return digest
}
  • docker.withRegistry(url, credential): runs docker login with the Username with password credential for the duration of the block. Current versions of the plugin store the session in a temporary configuration for the build, not in the agent's home directory. In the lab, the https://... URL works because the daemon treats the registry as insecure and falls back to HTTP.
  • image.push(): pushes the build tag (1.2.0-SNAPSHOT-57); image.push('1.2.0') adds the version tag for releases, following the policy from 06-05. Never latest.
  • RepoDigests: after the push, Docker knows the digest the registry gave it: registry.tecnoshop.local/orders-api@sha256:.... It is the immutable reference that deployments will use.
  • build-info.txt gains the image.digest=... line and is archived again; the archived copy is replaced by the new one.
  • Disable redeploy on docker-tecnoshop prevents pushing a tag that already exists: 1.2.0 is immutable, and a Restart from Stage of a build that already published will fail at the push. That is the intended behavior.

With its help .txt files and the JenkinsPipelineUnit tests (mocking docker and sh), it is released as v1.6.0: new, backward-compatible functionality.

The Changes to the orders-api Jenkinsfile

Three changes to the Jenkinsfile from the end of module 7:

@Library('[email protected]') _

A new stage, between Smoke and Quality analysis (cheap and with a medium probability of failure, following the ordering criterion from 07-02):

        stage('Image') {
            options {
                timeout(time: 15, unit: 'MINUTES')
            }
            steps {
                buildImage image: env.IMAGE, tag: env.IMAGE_TAG, version: env.APP_VERSION
            }
        }

And publishing the image at the end of Publish, after the jar and under the same conditions (SNAPSHOTs from main, releases from vX.Y.Z tags):

                mavenTecnoShop goals: '-DskipTests -Dmaven.install.skip=true deploy',
                               settings: 'maven-settings-tecnoshop-publish',
                               label: 'Publish to Nexus (jar and SBOM)'
                publishImage image: env.IMAGE, tag: env.IMAGE_TAG,
                             extraTags: env.TAG_NAME ? [env.APP_VERSION] : []
  • The pipeline keeps agent { label 'linux' }: linux-agent-01 now has the docker label and the client, so the Image stage works without changing agents.
  • env.TAG_NAME ? [env.APP_VERSION] : []: in the build of a tag (v1.2.0), the image also gets the 1.2.0 tag. The check that the Git tag matches the pom.xml version was already done a few lines earlier, in the same stage.
  • The Publish milestone protects the image too: a build that overtakes another does not publish an older image after a newer one.
  • infoBuild still writes image=registry.tecnoshop.local/orders-api:<IMAGE_TAG> in Package; publishImage adds the digest.

Deployments to dev-01, staging and production do not change: they still install the jar over SSH on virtual machines, as in module 7. The image will get its first destination in the Kubernetes pilot in 08-02. The complete Jenkinsfile, with this module's changes, is at the end of that lesson.

catalog-web in Node Containers

catalog-web used the NodeJS plugin with the node-20 and node-22 installations from Tools, which are downloaded onto the agent. With Docker, the Node version becomes the image:

@Library('[email protected]') _

pipeline {
    agent none

    options {
        timestamps()
        timeout(time: 30, unit: 'MINUTES')
        buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5'))
        disableConcurrentBuilds(abortPrevious: env.CHANGE_ID != null)
    }

    environment {
        NODE_ARGS = '-v /home/jenkins/agent/.npm:/home/jenkins/agent/.npm --network host'
    }

    stages {
        stage('Tests per Node version') {
            matrix {
                axes {
                    axis {
                        name 'NODE_VERSION'
                        values '20', '22'
                    }
                }
                agent {
                    docker {
                        image "node:${NODE_VERSION}-bookworm-slim"
                        label 'docker'
                        args '-v /home/jenkins/agent/.npm:/home/jenkins/agent/.npm --network host'
                    }
                }
                stages {
                    stage('Test') {
                        steps {
                            configFileProvider([configFile(fileId: 'npmrc-tecnoshop', variable: 'NPM_CONFIG_USERCONFIG')]) {
                                sh 'node --version && npm --version'
                                sh 'npm ci --prefer-offline'
                                sh 'npm test'
                            }
                        }
                        post {
                            always {
                                junit testResults: 'reports/junit.xml', allowEmptyResults: false
                            }
                        }
                    }
                    stage('Coverage') {
                        when {
                            environment name: 'NODE_VERSION', value: '22'
                        }
                        steps {
                            recordCoverage(
                                tools: [[parser: 'COBERTURA', pattern: 'coverage/cobertura-coverage.xml']],
                                id: 'jest',
                                name: 'Coverage (Jest)',
                                qualityGates: [
                                    [metric: 'LINE', baseline: 'PROJECT', threshold: 80.0, criticality: 'UNSTABLE']
                                ]
                            )
                            stash name: 'jest-coverage', includes: 'coverage/lcov.info'
                        }
                    }
                }
                post {
                    cleanup {
                        cleanWs()
                    }
                }
            }
        }

        stage('Build') {
            agent {
                docker {
                    image 'node:22-bookworm-slim'
                    label 'docker'
                    args '-v /home/jenkins/agent/.npm:/home/jenkins/agent/.npm --network host'
                }
            }
            steps {
                configFileProvider([configFile(fileId: 'npmrc-tecnoshop', variable: 'NPM_CONFIG_USERCONFIG')]) {
                    sh 'npm ci --prefer-offline'
                    sh 'npm run build'
                }
                script {
                    def version = sh(script: 'node -p "require(\'./package.json\').version"',
                                     returnStdout: true, label: 'Read the version from package.json').trim()
                    infoBuild application: 'catalog-web', version: version
                }
                archiveArtifacts artifacts: 'dist/**,build-info.txt', fingerprint: true
            }
            post {
                cleanup {
                    cleanWs()
                }
            }
        }

        stage('Security') {
            agent {
                label 'linux'
            }
            options {
                timeout(time: 10, unit: 'MINUTES')
            }
            steps {
                scanSecrets()
                script {
                    docker.image('node:22-bookworm-slim').inside(env.NODE_ARGS) {
                        configFileProvider([configFile(fileId: 'npmrc-tecnoshop', variable: 'NPM_CONFIG_USERCONFIG')]) {
                            sh label: 'Dependency vulnerabilities (npm audit)',
                               script: 'npm audit --audit-level=high --omit=dev'
                        }
                    }
                }
            }
            post {
                cleanup {
                    cleanWs()
                }
            }
        }

        stage('Quality analysis') {
            when {
                branch 'main'
            }
            agent {
                label 'linux'
            }
            options {
                timeout(time: 10, unit: 'MINUTES')
            }
            environment {
                SCANNER_HOME = tool 'sonar-scanner'
            }
            steps {
                unstash 'jest-coverage'
                nodejs(nodeJSInstallationName: 'node-22', configId: 'npmrc-tecnoshop') {
                    withSonarQubeEnv('sonar-tecnoshop') {
                        sh '"$SCANNER_HOME/bin/sonar-scanner"'
                    }
                }
            }
            post {
                cleanup {
                    cleanWs()
                }
            }
        }

        stage('Quality Gate') {
            when {
                branch 'main'
            }
            options {
                timeout(time: 10, unit: 'MINUTES')
            }
            steps {
                waitForQualityGate abortPipeline: true
            }
        }
    }

    post {
        always {
            notifyTeam channel: '#ci-catalog', email: '[email protected]'
        }
    }
}

What has changed and why:

  • Matrix axis: '20', '22' instead of node-20 and node-22, because they now form the image tag (node:22-bookworm-slim). The bookworm-slim variant is a slimmed-down Debian: smaller than the full one and with glibc, which avoids the surprises that the Alpine variants cause with native dependencies.
  • Reproducibility: node:22-bookworm-slim moves with every minor version of Node 22, whereas the Tools installations pointed to an exact version. For PR tests, TecnoShop accepts this; if a project needs it fully pinned, it uses the full tag (22.x.y-bookworm-slim) or the digest, and lets Renovate or Dependabot propose the changes.
  • configFileProvider replaces the configId of the nodejs step: it writes npmrc-tecnoshop to a temporary file and puts its path in NPM_CONFIG_USERCONFIG, which npm reads as its .npmrc. It is the same managed file from 06-02, with the Nexus npm-public registry.
  • npm cache: the node variable npm_config_cache=/home/jenkins/agent/.npm reaches the container, and the mount makes that path the agent volume's.
  • The user: the plugin runs with -u 1000:1000, which in the Node images is the node user, with its home directory. Nothing else is needed.
  • Security stays on the agent because gitleaks is in tecnoshop/linux-agent, and it runs npm audit inside a container with docker.image(...).inside. NODE_ARGS avoids repeating the arguments in the script code; in the agent { docker } directives of the matrix and of Build they are written out literally, so each one can be read without looking up the variable.
  • Quality analysis keeps the nodejs step: the SonarQube scanner, installed as a tool on the agent, needs Node to analyze JavaScript. Moving it into a container would require an image with both the scanner and Node, which is not worth it for a stage that only runs on main. That is why the NodeJS plugin is kept, with a single installation (node-22); node-20 can be deleted from Tools.

Other Uses: Browsers, Ansible, Windows and macOS

Three promises from earlier lessons get their answer here:

  • E2E tests with a browser (06-03): browser projects publish images with everything installed. For Playwright, for example, Microsoft's official image (mcr.microsoft.com/playwright, with the tag of the Playwright version the project uses) is used with agent { docker { image '...'; args '--ipc=host' } }, and the tests write JUnit XML for junit. The application under test can be started with withRun from its own image.
  • Ansible (06-06): instead of installing it on the agent, a stage with agent { docker { image 'registry.tecnoshop.local/tecnoshop/ansible:<version>'; reuseNode true } } (a custom image with a pinned Ansible version) inside sshagent. The SSH key reaches the container through the SSH_AUTH_SOCK variable, which points to a file in the temporary workspace, which is mounted.
  • Windows and macOS agents (05-01): Windows containers only run on Windows hosts, and macOS cannot run in containers. For iOS or desktop applications, agents remain permanent (or ephemeral virtual machines in the cloud) with labels such as windows or macos, connected over inbound or SSH.

What Is Left for Later

  • Ephemeral agents with the Docker plugin (Docker Cloud): instead of linux-agent-01 launching containers, Jenkins creates a complete agent container (for example, with registry.tecnoshop.local/tecnoshop/linux-agent:2) for each build and destroys it when it finishes. It is configured in Manage Jenkins → Clouds and compared with the other options in Scaling Jenkins.
  • Kubernetes: agents in pods, images built without a daemon using Kaniko, and the first deployment of the orders-api image, in 08-02.
  • A Docker Hub proxy in Nexus: docker-dind pulls base images directly from Docker Hub, which rate-limits anonymous pulls. A Docker proxy repository in Nexus, configured as the daemon's registry-mirrors, caches those pulls just as maven-central caches Maven Central.

Common Mistakes and Tips

  • Mounting /var/run/docker.sock "because it is the quick way": any PR could become root on the host and stop or read the Jenkins and Nexus containers. Use a daemon dedicated to the builds.
  • The stage container does not see the code (./mvnw: not found, empty workspace): the daemon does not have the agent's volume at the same path. Check that docker-dind mounts linux_agent_01 at /home/jenkins/agent. Some versions of the plugin try to detect whether the agent runs in a container in order to use --volumes-from; with an isolated daemon, that container does not exist from its point of view, and what works is mounting at the same path.
  • x509: certificate is valid for ..., not docker-dind: hostname: docker-dind is missing and the certificates were generated with a different name. Delete the certificate volumes (docker_certs_ca, docker_certs_client), set the hostname and recreate docker-dind and the agent.
  • permission denied when reading key.pem from the agent: the client certificates belong to root. Check their permissions with docker compose exec docker-dind ls -l /certs/client; the client key must be readable by the agent's UID 1000.
  • Could not resolve host: nexus inside the container: --network host is missing from the args. The containers of the nested daemon do not see the Compose network names.
  • mkdir: cannot create directory '/.m2': UID 1000 has no home directory in the image. Pass MAVEN_USER_HOME (or HOME) pointing to a mounted, writable path.
  • Images that keep piling up in docker-dind: every build leaves layers and images behind. Schedule a cleanup (docker image prune -af --filter "until=168h" in a weekly job on the agent) and keep an eye on the docker_dind_data volume.
  • Publishing latest or reusable tags: deployments use the digest; tags are for people. With Disable redeploy the registry protects you, but only if you do not use tags that move.
  • Building the image by compiling the code again (RUN mvn package in the application Dockerfile): the image would carry a different jar from the one that was tested. At TecnoShop, the image packages the jar from the build.
  • Tip: run docker history --no-trunc on your image from time to time; it is the fastest way to discover a layer containing something that should not be there.

Exercises

Exercise 1. Set up docker-dind, the tecnoshop/linux-agent:2 agent and the lab registry. Create lab-docker and run it twice. What takes longer in the first build than in the second, and why? Then remove --network host from the args and explain the error you get.

Exercise 2. Add the Dockerfile, the .dockerignore, the probes property and the orders-api Jenkinsfile changes in a PR. Which image-related stages run in the PR build and which do not? After merging, find the image in Nexus and check that its digest matches the one in image-digest.txt.

Exercise 3. catalog-web must also publish an image, registry.tecnoshop.local/catalog-web, that serves dist/ with unprivileged nginx on port 8080. Write its Dockerfile and the changes to the Jenkinsfile, reusing the library.

Solutions

Solution 1. In the first build, docker-dind pulls maven:3.9-eclipse-temurin-21 (several hundred MB) and the wrapper downloads Maven into MAVEN_USER_HOME; in the second, the image is in docker_dind_data and Maven and the dependencies are in the agent's volume, so only the actual compile and test time remains. Without --network host, the container starts on the default network of the nested daemon, whose DNS does not know nexus: Maven fails when downloading through the mirror with a name resolution error (UnknownHostException: nexus). If you ever see it work without the option, it is because the dependencies were already in the local cache.

Solution 2. In the PR, Image runs (build, Trivy, image SBOM and smoke test with withRun), because it has no when; Publish does not run (neither the jar nor the image), since it requires main or a tag. After merging, Browse → docker-tecnoshop → orders-api shows the 1.2.0-SNAPSHOT-<n> tag; its manifest shows a sha256:... digest that must be the same as the one in image-digest.txt and in the image.digest line of build-info.txt. You can also check it with docker buildx imagetools inspect localhost:5000/orders-api:1.2.0-SNAPSHOT-<n>.

Solution 3. Dockerfile in the root of catalog-web:

FROM nginxinc/nginx-unprivileged:<version>-alpine
ARG VERSION
ARG COMMIT=unknown
ARG BUILD_DATE=unknown
LABEL org.opencontainers.image.title="catalog-web" \
      org.opencontainers.image.version="${VERSION}" \
      org.opencontainers.image.revision="${COMMIT}" \
      org.opencontainers.image.created="${BUILD_DATE}" \
      org.opencontainers.image.source="https://github.com/tecnoshop/catalog-web"
COPY dist/ /usr/share/nginx/html/
EXPOSE 8080

With a .dockerignore (* and !dist/**). In the Jenkinsfile, the Build stage saves dist/ with stash name: 'dist', includes: 'dist/**' and leaves the version in env.WEB_VERSION; a new Image stage with agent { label 'docker' } runs unstash 'dist' and buildImage image: 'registry.tecnoshop.local/catalog-web', tag: "${env.WEB_VERSION}-${env.BUILD_NUMBER}", version: env.WEB_VERSION, port: 8080, healthPath: '/'; and, only on main, publishImage with the same image and tag. The nginx-unprivileged image already runs without root and listens on 8080; / returns the catalog's index.html, which serves as the smoke check.

Conclusion

TecnoShop's builds can now use containers without putting the platform at risk: a daemon of their own, docker-dind, with TLS and sharing nothing with Jenkins or Nexus, which linux-agent-01 talks to with the client in the new tecnoshop/linux-agent:2 image, published along with the rest of the images in registry.tecnoshop.local, which in the lab is the Nexus docker-tecnoshop repository behind an nginx, with the jenkins-push user behind the registry-tecnoshop credential. You know why mounting the host's socket amounts to handing out root, what alternatives exist (rootless, Podman, Kaniko, BuildKit, dedicated VMs), how to run stages in containers with agent { docker } and reuseNode, how to version the build environment with agent { dockerfile }, and how to use inside, build, withRegistry and withRun from code. orders-api has a runtime Dockerfile that runs without root, with OCI labels and a HEALTHCHECK, and tecnoshop-lib v1.6.0 builds, scans with Trivy, tests and publishes its image with buildImage and publishImage, which records the digest in build-info.txt. The most interesting part is still missing: getting that image to run somewhere, and having the agents themselves be born and die with each build. Both arrive in Jenkins and Kubernetes.

© Copyright 2026. All rights reserved