December 4, 2026

Dockerfile Layer Caching: The Line Order That Turned a 4.9-Second Rebuild Into 0.8

A stack of offset translucent glass plates like image layers on a workbench

Two Dockerfiles built the same image from the same files, and both took about five seconds the first time. Then one line of application code changed. The first Dockerfile took 4.9 seconds to rebuild; the second took 0.8. The only difference was where one COPY sat. The same set of tests then showed a 50 MB file deleted in a Dockerfile that still shipped in the image, and a build context that shrank from 21 MB to about a kilobyte with one line in .dockerignore. Every number here came from real builds with Docker’s BuildKit builder, on a small local base image made for the purpose.

Video: Net Ninja on YouTube

How the build cache works

One instruction, one layer

Docker’s documentation on the build cache explains the model in two sentences worth memorizing. Each instruction in a Dockerfile translates to a layer in your final image, and layers stack, each adding to what came before. When a layer changes, it has to be rebuilt, and the page continues: if a layer changes, all other layers that come after it are also affected.

That second rule is the whole game. Docker checks each instruction in order. As long as nothing about an instruction or its inputs has changed, the cached result is reused. The first instruction whose inputs differ is rebuilt, and so is every instruction after it, whether or not anything about them changed.

What counts as a change

Docker’s page on cache invalidation gives the details. For COPY and ADD, the cache is invalidated if the file metadata has changed for any of the files involved, but the modification time of a file (mtime) is not taken into account. Editing a source file invalidates a COPY that includes it; merely touching it does not. Outside of ADD and COPY, the same page says, cache checking does not look at the files in the container, so a RUN step is matched on its command string. Editing one source file therefore invalidates the COPY that includes it, and everything below that COPY runs again.

The tests confirmed the first point directly. Running touch on both files, which changes only their timestamps, and rebuilding took 0.2 seconds, with every step cached.

Silver and white round analog watch

The test

Two orderings of the same steps

The test application had a dependency list, deps.txt, and a script, main.sh. The dependency install was simulated by a RUN step that took four seconds, standing in for pip install, npm ci or a package manager.

The first Dockerfile copied everything, then installed:

FROM localbase:1
WORKDIR /app
COPY app/ .
RUN sleep 4 && echo "installed $(cat deps.txt)" > /installed.txt
CMD ["sh","main.sh"]

The second copied only the dependency list, installed, then copied the rest:

FROM localbase:1
WORKDIR /app
COPY app/deps.txt .
RUN sleep 4 && echo "installed $(cat deps.txt)" > /installed.txt
COPY app/ .
CMD ["sh","main.sh"]

The timings

Build Copy-everything first Dependencies first
First build 5.1 s 4.9 s
After editing main.sh 4.9 s 0.8 s
After editing deps.txt not tested 5.0 s

In the first Dockerfile, editing main.sh changed the content of the COPY app/ . layer, which invalidated the install step beneath it, so the four-second install ran again for a one-line code change. In the second, the COPY app/deps.txt layer was unchanged, the install step was reused, and only the final COPY ran. The build log marked the reused steps CACHED.

Changing deps.txt itself rebuilt the install in both cases, which is correct: new dependencies need installing. The point of the ordering is that only a dependency change pays that cost.

The general rule

Put the things that change least at the top and the things that change most at the bottom. Base image, system packages, dependency manifests and their install, then application code. A real install step takes minutes, not four seconds, so the difference in a real project is between a build that waits on a package manager every time and one that does not.

Build arguments and forced rebuilds

ARG changes invalidate what follows

The invalidation page also states that build arguments do result in cache invalidation. The test put ARG BUILD_ID=1 near the top of a Dockerfile, above a four-second step:

Build Time
First build, BUILD_ID=1 4.6 s
Same value again 0.2 s
New value, BUILD_ID=2 4.6 s

A build argument that changes on every build, such as a commit hash or a timestamp, placed near the top of a Dockerfile, quietly turns off caching for everything below it. If the value is only needed for a label at the end, declaring the ARG at the end keeps the expensive steps cached.

–no-cache

docker build --no-cache ignores the cache for every step. In the test it brought the dependencies-first build back to 5.0 seconds, the full cost. It is the right tool when a cached RUN apt-get update has gone stale, since a command string that never changes will never be re-run on its own.

Shipping container

Deleting a file does not shrink the image

The 50 MB that stayed

A common pattern downloads something, uses it, and deletes it in a later step. The test built three images on the same 3.29 MB base:

# Separate steps
RUN dd if=/dev/zero of=/tmp/build.tmp bs=1M count=50
RUN rm /tmp/build.tmp

# One step
RUN dd if=/dev/zero of=/tmp/build.tmp bs=1M count=50 && rm /tmp/build.tmp
Version Image size
Base image 3.29 MB
Create and delete in separate RUN steps 55.8 MB
Create and delete in one RUN step 3.31 MB
Multi-stage (below) 3.30 MB

docker history on the first version showed why:

8.19kB   RUN /bin/sh -c rm /tmp/build.tmp
52.4MB   RUN /bin/sh -c dd if=/dev/zero of=/tmp/build...

The rm layer records that the file is gone, but the layer underneath still contains the 52.4 MB that the earlier step wrote. Layers only add. A file is only absent from the image if it never existed at the end of any layer, which is why cleanup has to happen in the same RUN that created the mess.

Multi-stage builds

Leaving the toolchain behind

The cleaner answer is to never put build tools in the final image at all. The Docker documentation describes multi-stage builds as using multiple FROM statements in one Dockerfile, each beginning a new stage, so that artifacts can be copied from one stage to another, leaving behind everything not wanted in the final image.

The test’s version wrote a 50 MB stand-in for a toolchain in a build stage, produced a small output file, and copied only that file forward:

FROM localbase:1 AS build
RUN dd if=/dev/zero of=/tmp/toolchain.bin bs=1M count=50 && echo "binary" > /out.txt
FROM localbase:1
COPY --from=build /out.txt /out.txt

The final image came out at 3.30 MB. The 50 MB existed only in the build stage, which is not part of what gets pushed or run. Compilers, headers, test frameworks and package caches all belong in a stage like that.

Fine mesh filter

The build context and .dockerignore

What gets sent before the first line runs

Before a build starts, Docker sends the build context, normally the directory given at the end of docker build, to the builder. The test directory held a 20 MB file that the image never needed. With the builder cache cleared, the log reported:

transferring context: 20.98MB

Adding one line to .dockerignore:

app/bigtest.bin

brought the same step down to transferring context: 1.13kB. The Docker documentation describes the file’s purpose as excluding files or directories from the build context, which avoids sending unwanted files to the builder and improves build speed, especially with a remote builder.

The cache side effect

.dockerignore also protects the cache. A COPY . . includes everything in the context, so a changing log file, a local database or a .git directory can invalidate that layer on every build even when no source code changed. Excluding them keeps the layer stable. The same habit applies to secrets: a .env file that is never in the context can never be copied into an image by accident.

A checklist that follows from the tests

In order of payoff

  • Copy dependency manifests and install dependencies before copying application code.
  • Clean up in the same RUN that created the files, or better, in a separate build stage that never reaches the final image.
  • Exclude anything the image does not need with .dockerignore, starting with version-control directories, local environments and large test data.
  • Check docker history <image> when an image is bigger than expected. The layer that carries the weight is usually obvious.
  • Watch for CACHED in the build output. A step expected to be cached that is not points at an input that changed, often one nobody meant to include.

Sources

  • Docker build cache, Docker Docs: https://docs.docker.com/build/cache/
  • Build cache invalidation, Docker Docs: https://docs.docker.com/build/cache/invalidation/
  • Multi-stage builds, Docker Docs: https://docs.docker.com/build/building/multi-stage/
  • Build context, Docker Docs: https://docs.docker.com/build/concepts/context/

719 Posts

Peter Kalafatis writes and edits X9M8. He holds a bachelor's degree from LIU Post and a master's in Media Studies from The New School, with academic work in the philosophy of science, human behavior, AI, and memetics.

View All Posts

Leave a Reply

Your email address will not be published. Required fields are marked *