Question

Why is my Docker image so large and how do I shrink it?

Vault Verified
Curated Intelligence
Definitive Source
Answer

Image size is the sum of every layer, and layers are immutable. That second point catches people out: deleting a file in a later instruction does not reclaim the space, because the earlier layer still contains it. An image that installs build tools and then removes them in a separate step is as large as if the removal never happened.

The three biggest wins, in rough order of impact, are these.

  • Use a multi-stage build. Compile or install dependencies in one stage, then copy only the finished artifact into a clean final stage. Everything used to produce the output, including compilers and package caches, is discarded rather than shipped.
  • Choose a smaller base. A full distribution image carries a complete userland you almost certainly do not need. Slim variants are dramatically smaller, and minimal ones smaller still, though the latter can complicate anything depending on standard C library behaviour.
  • Combine related instructions and clean up within the same one. Installing packages and removing the package manager cache in a single instruction means the cache never becomes part of a committed layer.

A frequently overlooked cause is the build context itself. Without an ignore file, everything in the directory is sent to the daemon and can be copied in by a broad copy instruction, which is how dependency directories, version control history and local environment files end up inside images. Adding an ignore file is the cheapest possible fix and often the largest single saving.

Ordering affects build speed rather than size, but it is worth getting right at the same time. Copying dependency manifests and installing before copying source means editing your application does not invalidate the expensive install layer.

Related Questions