Docker › Image

Speeding up Gradle Docker builds with BuildKit cache mounts

Cut Spring Boot Docker build times from over 3 minutes to 22 seconds using BuildKit cache mounts and the GitHub Actions cache backend.

Speeding up Gradle Docker builds with BuildKit cache mounts

Changing a single line of Java code shouldn’t force Docker to re-download hundreds of megabytes of Gradle dependencies. Here is how I used BuildKit cache mounts (--mount=type=cache) and the GitHub Actions cache backend to drop a 3-minute-42-second Spring Boot image build down to 22 seconds.


Why one-line code edits trigger full Gradle downloads

When you build Spring Boot Docker images locally or in CI, you quickly run into a frustrating pattern. You fix a typo in a controller, run docker build, and watch Gradle download the world all over again:

1
2
3
4
5
6
# ...
> [builder 6/7] RUN ./gradlew bootJar --no-daemon -x test:
0.842 Downloading https://services.gradle.org/distributions/gradle-8.12-bin.zip
14.21 Downloading https://repo1.maven.org/maven2/org/springframework/boot/spring-boot-starter-web/...
28.53 Downloading https://repo1.maven.org/maven2/org/hibernate/orm/hibernate-core/...
# ... hundreds of JARs downloaded over 3-4 minutes ...

Even on a fast connection, waiting three to four minutes after every tiny edit breaks your flow.

How Docker layer invalidation wipes /root/.gradle

Docker caches each Dockerfile instruction as a layer keyed by the previous layer’s hash plus the current instruction’s inputs. In a typical multi-stage Dockerfile, the build step looks like this:

1
2
3
4
5
6
7
8
9
10
FROM eclipse-temurin:25-jdk-alpine AS builder
WORKDIR /workspace

COPY gradlew .
COPY gradle gradle
COPY build.gradle.kts settings.gradle.kts ./
COPY src src

# Any change under src/ invalidates COPY and busts this RUN layer
RUN ./gradlew bootJar --no-daemon -x test

Touch one file under src/, and the COPY src src layer hash changes. Because Docker invalidates every instruction after a changed layer, RUN ./gradlew bootJar executes in a fresh container with an empty /root/.gradle directory—forcing Gradle to pull its wrapper distribution and every dependency from Maven Central or Nexus again.

flowchart TD
    A["COPY gradlew, gradle, build.gradle.kts"] -->|"Cache hit (CACHED)"| B["Build definition layer"]
    B --> C["COPY src src (1-line edit)"]
    C -->|"Hash changed: cache busted"| D["RUN ./gradlew bootJar"]
    D --> E["Empty /root/.gradle directory"]
    E --> F["Re-download 400+ MB of JARs (3-4 min)"]
    style C fill:#ffebee,stroke:#c62828,color:#b71c1c
    style D fill:#ffebee,stroke:#c62828,color:#b71c1c
    style F fill:#ffcdd2,stroke:#b71c1c,color:#b71c1c

Why the COPY build.gradle trick falls short

A common workaround is copying build scripts first and pre-warming the cache with ./gradlew dependencies:

1
2
3
4
5
6
7
8
# Common layer-splitting workaround
COPY gradlew .
COPY gradle gradle
COPY build.gradle.kts settings.gradle.kts ./
RUN ./gradlew dependencies --no-daemon

COPY src src
RUN ./gradlew bootJar --no-daemon -x test

That helps slightly on tiny single-module apps, but it breaks down fast on real projects:

  1. Incomplete resolution: ./gradlew dependencies doesn’t fetch every configuration (compileClasspath, runtimeClasspath, annotationProcessor) or every plugin artifact, so bootJar still downloads missing JARs afterward.
  2. Multi-module maintenance pain: If your repository has 15 subprojects, you have to mirror and copy every single build.gradle.kts file by hand before copying src/. Every new module breaks the Dockerfile.
  3. Bloated build layers: The RUN ./gradlew dependencies step bakes hundreds of megabytes of cached JARs into an intermediate image layer.

What we actually want is simple: even when src/ changes and Gradle recompiles, /root/.gradle should persist across builds just like ~/.gradle does on your laptop. That’s what BuildKit cache mounts do.


How BuildKit cache mounts preserve dependencies

BuildKit has been Docker’s default builder since Docker 20.10 (and mandatory in Docker Engine 23+). Built around a low-level DAG representation (LLB), it supports parallel stage execution, dead-stage pruning, secret mounts (--mount=type=secret), and persistent cache mounts (--mount=type=cache).

A cache mount attaches a persistent BuildKit-managed directory to a specific RUN instruction while that command executes—completely outside the container’s immutable image layers.

flowchart TD
    CM[("BuildKit persistent cache (/var/lib/docker/buildkit/cache)")]
    CMD["RUN --mount=type=cache,target=/root/.gradle ./gradlew bootJar"]
    DIR["/root/.gradle (mounted during RUN)"]
    OUT["Final image layer (zero cache bloat)"]
    CM <===>|"Read/write during build"| DIR
    CMD --> DIR
    DIR -.->|"Unmounted after RUN"| OUT
    style CM fill:#e8f5e9,stroke:#2e7d32,color:#1b5e20
    style DIR fill:#e3f2fd,stroke:#1565c0,color:#0d47a1

While ./gradlew bootJar runs, /root/.gradle already contains the Gradle wrapper and every previously downloaded JAR. Gradle reads dependencies straight from local disk and writes any new dependencies back to the cache. Once the RUN step finishes, BuildKit unmounts the cache so none of those files end up in your final image.

Optimized multi-stage Spring Boot Dockerfile

Here is the production multi-stage Dockerfile I use:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# syntax=docker/dockerfile:1.7
# Stage 1: Build stage (Gradle + JDK 25)
FROM eclipse-temurin:25-jdk-alpine AS builder
WORKDIR /workspace

# 1. Copy source code and build files together (no fragile build.gradle split)
COPY . .

# 2. Build with a persistent BuildKit cache mount for /root/.gradle
#    - target: Gradle cache path inside the build container
#    - id: unique cache identifier
#    - sharing=locked: serialize concurrent builds sharing the same cache
RUN --mount=type=cache,id=gradle-cache,target=/root/.gradle,sharing=locked \
    chmod +x gradlew && \
    ./gradlew bootJar --no-daemon -x test

# Stage 2: Minimal runtime stage (JRE 25)
FROM eclipse-temurin:25-jre-alpine AS runner
WORKDIR /app

# Create a non-root system user
RUN addgroup -S springgroup && adduser -S springuser -G springgroup
USER springuser

# Copy only the fat JAR from the builder stage
COPY --from=builder /workspace/build/libs/*.jar app.jar

EXPOSE 8080
ENTRYPOINT ["java", "-jar", "-Djava.security.egd=file:/dev/./urandom", "app.jar"]

The # syntax=docker/dockerfile:1.7 directive at the top ensures BuildKit parses the latest mount syntax consistently across local machines and CI runners.

Using Maven instead of Gradle? Swap the target path to /root/.m2:

1
2
RUN --mount=type=cache,id=maven-cache,target=/root/.m2,sharing=locked \
    ./mvnw clean package -DskipTests

Persisting BuildKit cache in GitHub Actions

Cache mounts work automatically on your laptop because the local Docker daemon keeps its BuildKit storage pool across builds.

Cloud CI runners like GitHub Actions’ ubuntu-latest are ephemeral—every job starts on a fresh VM and throws away its disk when the job ends. Without remote cache export/import, your cache mount starts empty on every commit.

Connecting the GitHub Actions cache backend (type=gha)

docker/setup-buildx-action and docker/build-push-action support type=gha, which stores and restores BuildKit cache layers directly in GitHub Actions Cache:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
name: Production Docker Build & Push

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Source Code
        uses: actions/checkout@v4

      # 1. Provision a Buildx builder (required for cache export)
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      # 2. Authenticate with GitHub Container Registry
      - name: Log in to GitHub Container Registry
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      # 3. Build and push with GitHub Actions cache backend
      - name: Build and Push Docker Image
        uses: docker/build-push-action@v6
        with:
          context: .
          file: ./Dockerfile
          push: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }}
          tags: ghcr.io/${{ github.repository }}/backend:latest
          cache-from: type=gha
          cache-to: type=gha,mode=max

Pay close attention to cache-to: type=gha,mode=max. With the default mode=min, Buildx only exports layers that belong to the final runtime image—skipping the builder stage and its intermediate cache entirely. You need mode=max to persist multi-stage build caches.

When not to use type=gha: GitHub Actions Cache caps each repository at 10 GB. If you run a large monorepo or build many branches in parallel, cache eviction will churn constantly. Switch to a registry-backed cache (cache-from: type=registry,ref=ghcr.io/my-org/backend:buildcache and cache-to: type=registry,ref=...,mode=max) instead.


Benchmark results and cache hygiene

I benchmarked a Spring Boot 3.4 backend project with 78 dependencies after changing one line in a controller class:

Build strategyDependency behaviorBuild timeNetwork downloaded
Plain build (no cache)Full re-download every time3m 42s~420 MB
COPY build.gradle splitPartial re-download + extra work1m 58s~110 MB
BuildKit cache mount100% local cache hit22s0 MB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
{
  "type": "bar",
  "data": {
    "labels": [
      "Plain build (no cache)",
      "COPY build.gradle split",
      "BuildKit cache mount"
    ],
    "datasets": [
      {
        "label": "Build time (seconds)",
        "data": [222, 118, 22]
      },
      {
        "label": "Dependencies downloaded (MB)",
        "data": [420, 110, 0]
      }
    ]
  },
  "options": {
    "indexAxis": "y",
    "plugins": {
      "title": {
        "display": true,
        "text": "Gradle Docker build time (s) and network traffic (MB)"
      }
    },
    "scales": {
      "x": {
        "beginAtZero": true
      }
    }
  }
}

With the cache mount active, Gradle skips the network completely and spends those 22 seconds only on incremental compilation and bootJar packaging.

Four pitfalls to avoid in production

  1. Always pass --no-daemon: Gradle’s background daemon expects to stay alive between runs. When a Docker build step exits and kills the daemon mid-cleanup, it can leave stale lock files behind and corrupt the shared cache mount.
  2. Set sharing=locked on shared builders: If two CI jobs run on the same BuildKit daemon with the same id=gradle-cache, concurrent writes to /root/.gradle will break the build. sharing=locked serializes access to that mount cleanly.
  3. Match the mount path and UID to your build user: If your builder stage switches to a non-root user (USER gradle), point the mount at /home/gradle/.gradle and set matching ownership:
    1
    2
    
    RUN --mount=type=cache,id=gradle-cache,target=/home/gradle/.gradle,uid=1000,gid=1000,sharing=locked \
        ./gradlew bootJar --no-daemon -x test
    
  4. Prune stale cache mounts on schedule: Over months of Spring Boot upgrades, old dependency versions pile up on persistent CI runners. Clear only cache mounts on a schedule without wiping regular image layers:
    1
    2
    
    # Remove BuildKit cache mounts only (keep normal image layers)
    docker builder prune --filter type=exec.cachemount --force
    

Avoid running docker system prune -a on shared build hosts—it wipes every image layer and cache mount at once, resetting your next build back to cold-start speed. Filter with --filter type=exec.cachemount when reclaiming cache space.


Takeaways for faster build loops

Cutting a Docker build from nearly four minutes down to 22 seconds does more than save CI minutes. At four minutes, you push a commit and switch to Slack or another task; at 22 seconds, you stay in flow and iterate without losing context.

Before wrapping up your Dockerfile refactor, verify these items:

  • Add # syntax=docker/dockerfile:1.7 at line 1 and replace COPY build.gradle workarounds with --mount=type=cache,id=gradle-cache,target=/root/.gradle,sharing=locked.
  • Keep --no-daemon on every ./gradlew command inside Docker.
  • Export mode=max in CI (type=gha for smaller repos, type=registry if you approach GitHub’s 10 GB cache limit).
  • Schedule docker builder prune --filter type=exec.cachemount --force on long-lived runners.
This post is licensed under CC BY 4.0 by the author.