Subscribe

Faster Docker builds with layer caching and BuildKit cache mounts

Every one-line change to shorty took about 10 seconds to rebuild in Docker. Ordering COPY, a BuildKit cache mount for the Go build cache and a proper .dockerignore got it under 2 seconds. Then a registry cache for CI, and the cache mount trap I hit on a fresh builder.

Faster Docker builds with layer caching and BuildKit cache mounts

I change one line in shorty, run docker build, and wait ten seconds. Then I do it again. Ten seconds doesn't sound like much, but it's long enough to switch to another tab and lose the thread. And in CI the same build runs on a fresh machine every time, so it's always the slow version.

In this blog we will make the shorty image build faster: order the Dockerfile so the cache actually hits, use BuildKit cache mounts for the Go build cache, fix the .dockerignore, and carry the cache to CI through a registry. Level is intermediate. You should have read Docker from zero or know what a layer is, and the starting point is the Dockerfile from hardening a Go container image.

I used Docker 29.8.2 with buildx 0.37.2 on OrbStack 2.2.5 (Apple M5), golang:1.27.4-alpine to build and distroless to run. All the times below are from my laptop, measured with time and the step timings that --progress=plain prints. Your numbers will be different. The ratios should not be.

How the build cache decides

BuildKit walks the Dockerfile top to bottom. For each step it builds a cache key from the step itself and its inputs. For RUN the input is the command text and the layer below it. For COPY it's a checksum of the files being copied. If the key matches something it built before, the step is CACHED. The moment one step misses, every step after it runs again.

That second rule is basically the whole game. Put the things that rarely change at the top and the things that change all the time at the bottom.

The slow version

This is the Dockerfile most of us write first:

FROM golang:1.27.4-alpine AS build
WORKDIR /src
COPY . .
RUN go mod download
ARG VERSION=dev
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w -X main.version=${VERSION}" -o /out/shorty ./cmd/shorty

COPY . . copies every file, so any edit changes its checksum. Then go mod download runs again even though go.mod didn't change, and then go build compiles everything from zero. I added one comment line to internal/httpapi/handlers.go and rebuilt:

#11 [build 3/5] COPY . .
#12 [build 4/5] RUN go mod download
#12 DONE 1.4s
#13 [build 5/5] RUN CGO_ENABLED=0 go build ...
#13 DONE 6.9s

About 10 seconds in total. shorty only has a handful of modules and my connection to the Go proxy is quick, so the download is just 1.4 seconds here. On a project with a hundred modules it's a lot more.

Copy go.mod first

The hardening post already does the classic fix:

COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build ...

Now go mod download only depends on go.mod and go.sum. Same one-line edit:

#11 [build 3/6] COPY go.mod go.sum ./
#11 CACHED
#12 [build 4/6] RUN go mod download
#12 CACHED
#14 [build 6/6] RUN CGO_ENABLED=0 go build ...
#14 DONE 8.5s

The download is cached. And the total was still 10.7 seconds. Honestly this surprised me a bit. I had always thought of the go.mod trick as "the" Docker speed-up for Go, but for shorty the expensive part is the compile, and go build inside a fresh layer has no build cache. It recompiles pgx, goose, go-redis and the standard library packages every single time.

On my Mac, go build after a small edit takes well under a second because ~/.cache/go-build remembers everything. The container needs the same thing.

Cache mounts

BuildKit has RUN --mount=type=cache. It mounts a directory that lives in the builder, outside of any layer, and survives from one build to the next. It's never part of the image. Here is the build stage with a cache mount for the Go build cache:

# syntax=docker/dockerfile:1

FROM golang:1.27.4-alpine AS build
WORKDIR /src

COPY go.mod go.sum ./
RUN go mod download

ARG VERSION=dev
RUN --mount=type=cache,target=/root/.cache/go-build \
    --mount=type=bind,target=. \
    CGO_ENABLED=0 go build -trimpath -ldflags="-s -w -X main.version=${VERSION}" -o /out/shorty ./cmd/shorty

FROM gcr.io/distroless/static-debian13:nonroot
COPY --from=build /out/shorty /shorty
USER 65532:65532
EXPOSE 8080
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 CMD ["/shorty", "healthcheck"]
CMD ["/shorty", "serve"]

Two mounts on the build step. /root/.cache/go-build is where Go keeps compiled packages in the golang image (the build runs as root there). --mount=type=bind,target=. puts the build context into /src for this one step, so I don't need COPY . . at all and the source never becomes a layer of its own.

The # syntax=docker/dockerfile:1 line at the top makes sure you get a Dockerfile frontend that knows about --mount. Recent Docker versions understand it anyway, but I keep the line.

To compare fairly I ran both versions on the same builder and made the same kind of change before each one: I added one more field to the access log in middleware.go.

copy go.mod first, then COPY . .     go build 8.1s    total 9.7s
cache mount for go-build             go build 0.6s    total 1.9s

That is the number I wanted. Go only recompiles the httpapi package and the main package, then links.

Should modules go in a cache mount too

A lot of guides also put /go/pkg/mod in a cache mount, on both the download and the build step. I did that first. It's a little nicer locally, because when go.mod changes you download less modules, only the new one.

Then I tested it on fresh builder with a registry cache (next section) and got this in the log:

#12 [build 3/4] RUN --mount=type=cache,target=/go/pkg/mod ... go mod download
#12 CACHED
#13 [build 4/4] RUN --mount=type=cache,target=/go/pkg/mod ... go build ...
#13 0.059 go: downloading github.com/jackc/pgx/v5 v5.13.0
#13 0.060 go: downloading github.com/pressly/goose/v3 v3.30.1
...
#13 DONE 10.0s

The download step was cached, but it was empty. The modules were never in that layer, they were in the cache mount, and a new builder has empty cache mounts. So go build downloaded all fourteen modules again, the cached layer was useless. See, cache mounts are not exported with --cache-to. That's the part that's easy to miss.

So my Dockerfile keeps modules in a normal layer (COPY go.mod go.sum plus RUN go mod download, which a registry cache can carry) and uses a cache mount only for the build cache, which is a local speed-up anyway.

.dockerignore

The build context is everything in the folder you pass to docker build, minus what .dockerignore excludes. It matters for two reasons: size, and cache keys.

I ran go build -o bin/shorty ./cmd/shorty on my Mac to try something, then built the image without changing any source:

#9 transferring context: 20.26MB 0.1s done
#13 [build 5/6] COPY . .
#14 [build 6/6] RUN CGO_ENABLED=0 go build ...
#14 DONE 6.8s

A 20 MB macOS binary went into the context, and because COPY . . copies it, the checksum changed and the compile ran again. For a binary the image never uses. The same thing happens with .git (every commit changes it), coverage files, a node_modules from some tool, and worst of all a .env with real secrets in it.

This is the .dockerignore I use for shorty now:

# Version control and editor junk
.git
.idea
.vscode
*.swp

# Local build output and test artefacts
bin/
dist/
coverage.out
*.test

# Things the image never needs
*.md
compose.yaml
seed/
.github/

# Secrets must never reach the build context
.env
.env.*

One more small thing that actually confused me for a minute. The first build after I edited .dockerignore was not cached either. That's because .dockerignore is itself in the context, so it changed what COPY . . copied. The build after that, with a rebuilt bin/shorty and an edited README.md, was fully cached in 1.7 seconds.

Carrying the cache to CI

All of this lives in the builder on my laptop. A GitHub-hosted runner starts empty every time. BuildKit can export its cache somewhere and import it on the next run. The post on pushing images from GitHub Actions to ECR and GHCR uses type=gha, the GitHub Actions cache. The other option is type=registry: the cache is stored as an image in your own registry.

I tested the registry cache locally itself, before writing any YAML. I started a throwaway registry:3 container and a docker-container builder on the same Docker network, pushed a cache, then deleted the builder and created a new one, which is as close to a fresh CI runner as I can get on one machine:

docker buildx build --builder shorty-builder \
  --cache-to type=registry,ref=cache-registry:5000/shorty:buildcache,mode=max,image-manifest=true,oci-mediatypes=true .

docker buildx rm shorty-builder
docker buildx create --name shorty-builder --driver docker-container \
  --driver-opt network=buildnet --buildkitd-config buildkitd.toml --bootstrap

docker buildx build --builder shorty-builder \
  --cache-from type=registry,ref=cache-registry:5000/shorty:buildcache .

(buildkitd.toml only tells BuildKit that this test registry speaks plain HTTP. You won't need it for ECR.)

With no source change, every step came back CACHED on the new builder. The run still took 8.8 seconds, but nearly all of that was resolving the base image tags from Docker Hub and gcr.io. After a code change, the module layer (67.78 MB) came from the registry, no module was downloaded, and the compile took 7.1 seconds because the build cache mount was empty. That's the honest picture for CI: the registry cache saves the download and every unchanged step, and the compile still runs.

mode=max exports the layers of the build stage too. Without it you only get the final image's layers, and for a multi-stage build that's the useless half. image-manifest=true,oci-mediatypes=true stores the cache as a normal OCI image manifest. ECR needs that, it rejects the default cache manifest format.

In GitHub Actions

Here is the build step from that post with the registry cache in ECR instead of the GHA cache:

      - name: Build and push
        uses: docker/build-push-action@v7
        with:
          push: ${{ github.event_name != 'pull_request' }}
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          build-args: |
            VERSION=${{ steps.meta.outputs.version }}
          # Read the cache on every run. Pull requests have no ECR login, so this is a warning there, not an error.
          cache-from: type=registry,ref=${{ env.ECR_IMAGE }}:buildcache
          # Only main writes the cache, so pull requests can't fill it with half-finished branches.
          cache-to: ${{ github.ref == 'refs/heads/main' && format('type=registry,ref={0}:buildcache,mode=max,image-manifest=true,oci-mediatypes=true', env.ECR_IMAGE) || '' }}

The full workflow passes actionlint 1.7.12. I checked the "warning, not an error" part locally too: a --cache-from pointing at a cache that doesn't exist prints an ERROR: failed to configure registry cache importer line, and the build still exits 0.

There is one catch if you followed that post. The ECR repository there has immutable tags with only main excluded. buildcache is a tag that gets overwritten on every build to main, so the second push would be refused. Add it to the exclusions:

  image_tag_mutability = "IMMUTABLE_WITH_EXCLUSION"
  image_tag_mutability_exclusion_filter {
    filter      = "main"
    filter_type = "WILDCARD"
  }
  image_tag_mutability_exclusion_filter {
    filter      = "buildcache"
    filter_type = "WILDCARD"
  }

terraform validate is happy with this on Terraform 1.17.1 and AWS provider 6.73.0. I didn't apply it to a real account for this post.

Which one to pick? type=gha needs no registry and no IAM, but it shares the repo's Actions cache limit and old entries get evicted. The registry cache costs a bit of ECR storage, and any machine that can pull from ECR can use it, including a self-hosted runner or your laptop. For one small repo I would stay on type=gha. I'd switch when several workflows or runners build the same image.

If you really want the Go build cache in CI too, there is an action called reproducible-containers/buildkit-cache-dance that saves cache mounts into the Actions cache and injects them back. I haven't needed it for shorty. The compile itself is 7 seconds.

Checking it yourself

--progress=plain is the only tool you need here. Look for CACHED next to each step, and for the transferring context line to see how much you're sending. If a step you expected to be cached runs again, the step right above it is usually the one that changed.

There we have it: one-line changes in about 2 seconds locally, and in CI the modules come from the registry instead of the internet.