Is it possible to cache multi-stage docker builds?

Matthew Goslett picture Matthew Goslett · Oct 4, 2018 · Viewed 7.5k times · Source

I recently switched to multi-stage docker builds, and it doesn't appear that there's any caching on intermediate builds. I'm not sure if this is a docker limitation, something which just isn't available or whether I'm doing something wrong.

I am pulling down the final build and doing a --cache-from at the start of the new build, but it always runs the full build.

Answer

Matthew Goslett picture Matthew Goslett · Oct 4, 2018

This appears to be a limitation of docker itself and is described under this issue - https://github.com/moby/moby/issues/34715

The workaround is to:

  1. Build the intermediate stages with a --target
  2. Push the intermediate images to the registry
  3. Build the final image with a --target and use multiple --cache-from paths, listing all the intermediate images and the final image
  4. Push the final image to the registry
  5. For subsequent builds, pull the intermediate + final images down from the registry first