Leverage the Build Cache

Learn to use build cache to optimize image build time.

The build process used by Docker has the concept of a cache, which uses it to speed up the build process. The best way to see the impact of the cache is to build a new image on a clean Docker host. Then, repeat the same build immediately after. The first build will pull images and take time building layers. The second build will complete almost instantaneously. This is because artifacts from the first build, such as layers, are cached and leveraged by later builds.

As we know, the docker image build process iterates through a Dockerfile one line at a time starting from the top. For each instruction, Docker looks to see if it already has an image layer for that instruction in its cache. If it does, this is a cache hit, and it uses that layer. If it doesn’t, this is a cache miss, and it builds a new layer from the instruction. Getting cache hits can hugely speed up the build process.

Let’s look a little closer.

Example for using cache

We’ll use this Dockerfile example to provide a quick walk-through:

Get hands-on with 1000+ tech skills courses.