Question

Why is my Docker build so slow?

Vault Verified
Curated Intelligence
Definitive Source
Answer

Most slow builds are slow because the cache is being invalidated unnecessarily, not because the work itself is expensive. Each instruction produces a layer, and once one is invalidated every instruction after it must run again regardless of whether anything relevant changed.

The dominant cause is copying source code before installing dependencies. Editing any file invalidates that copy, so the dependency install runs from scratch on every build even though the dependency list did not change. Copying only the manifest files, installing, and then copying the source means the expensive layer is reused until dependencies actually change. This single reordering is usually the largest improvement available.

The build context is the second common cause and is invisible until you look. Everything in the directory is sent to the daemon before the build starts, so a project containing a dependency directory, version control history or large assets can spend a long time transferring before any instruction runs. An ignore file fixes it, and the build output reports the context size, which makes the problem easy to confirm.

Other contributors are worth knowing. Running package manager updates in a separate instruction from installs means a cached update layer paired with a fresh install, which can fail as well as being slow. Combining them in one instruction is both faster and more correct.

Multi-stage builds help beyond image size, because independent stages can build in parallel with a modern builder.

For repeated builds in continuous integration, the cache usually does not persist between runs, which is why builds are fast locally and slow in the pipeline. Most platforms support exporting and importing a cache, or using a remote cache, and configuring that removes the difference.

Related Questions