Build cache invalidation


目录

When building an image, Docker steps through the instructions in your Dockerfile, executing each in the order specified. For each instruction, the builder checks whether it can reuse the instruction from the build cache.

General rules

The basic rules of build cache invalidation are as follows:

Once the cache is invalidated, all subsequent Dockerfile commands generate new images and the cache isn't used.

If your build contains several layers and you want to ensure the build cache is reusable, order the instructions from less frequently changed to more frequently changed where possible.

WORKDIR and SOURCE_DATE_EPOCH

The WORKDIR instruction respects the SOURCE_DATE_EPOCH build argument when determining cache validity. Changing SOURCE_DATE_EPOCH between builds invalidates the cache for WORKDIR and all subsequent instructions.

SOURCE_DATE_EPOCH sets timestamps for files created during the build. If you set this to a dynamic value like a Git commit timestamp, the cache breaks with each commit. This is expected behavior when tracking build provenance.

For reproducible builds without frequent cache invalidation, use a fixed timestamp:

$ docker build --build-arg SOURCE_DATE_EPOCH=0 .

RUN instructions

The cache for RUN instructions isn't invalidated automatically between builds. Suppose you have a step in your Dockerfile to install curl:

FROM alpine:{{% param "example_alpine_version" %}} AS install
RUN apk add curl

This doesn't mean that the version of curl in your image is always up-to-date. Rebuilding the image one week later will still get you the same packages as before. To force a re-execution of the RUN instruction, you can:

The --no-cache-filter option lets you specify a specific build stage to invalidate the cache for:

$ docker build --no-cache-filter install .

Build secrets

The contents of build secrets are not part of the build cache. Changing the value of a secret doesn't result in cache invalidation.

If you want to force cache invalidation after changing a secret value, you can pass a build argument with an arbitrary value that you also change when changing the secret. Build arguments do result in cache invalidation.

FROM alpine
ARG CACHEBUST
RUN --mount=type=secret,id=TOKEN,env=TOKEN \
    some-command ...
$ TOKEN="tkn_pat123456" docker build --secret id=TOKEN --build-arg CACHEBUST=1 .

Properties of secrets such as IDs and mount paths do participate in the cache checksum, and result in cache invalidation if changed.


版本号 #2
由 壳壳虫 创建于 2026-10-31 19:04:52 UTC
由 壳壳虫 更新于 2026-10-31 19:04:53 UTC