From e64e20246907199bc06504fb3d7f29124080f4fd Mon Sep 17 00:00:00 2001 From: Kevyn Bruyere Date: Fri, 24 Jul 2020 20:15:19 +0200 Subject: [PATCH] Be more specific about command caching and cache invalidation --- .../docker/Caching-for-shorter-build-time.md | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/sections/docker/Caching-for-shorter-build-time.md b/sections/docker/Caching-for-shorter-build-time.md index 7518274b..c2f5dd40 100644 --- a/sections/docker/Caching-for-shorter-build-time.md +++ b/sections/docker/Caching-for-shorter-build-time.md @@ -2,10 +2,11 @@ ## One paragraph explainer -Docker images are a combination of layers, each instruction in your Dockerfile creates a layer. The docker daemon can reuse those layers between builds if the instructions and files used are identical. +Docker images are a combination of layers, each instruction in your Dockerfile creates a layer. The docker daemon can reuse those layers between builds if the instructions are identicals or in the case of a `COPY` or `ADD` files used are identical. It is important to layout your Dockerfile correctly to reduce the number of moving parts in your build, the less updated instructions should be at the top and the ones constantly changing (like app code) should be at the bottom. Rebuilding a whole docker image from cache can be nearly instantaneous if done correctly. +⚠️ If the cache can't be used for a particular layer, all the subsquent layers will be invalidated too. That's why order is important. ![Docker layers](/assests/images/docker_layers_schema.png) @@ -13,6 +14,20 @@ Rebuilding a whole docker image from cache can be nearly instantaneous if done c ### Rules +#### Avoid LABEL that change all the time + +If you have a label containing the build number at the top of your Dockerfile, the cache will be invalidated at every build + +```Dockerfile +#Beginning of the file +FROM node:10.22.0-alpine3.11 as builder + +# Don't do that here! +LABEL build_number="483" + +#... Rest of the Dockerfile +``` + #### Have a good .dockerignore file [**See: On the importance of docker ignore**](/sections/docker/docker-ignore.md) @@ -100,4 +115,6 @@ RUN npm prune --production CMD ["node", "dist/server.js"] ``` +## Useful links +Docker docks: https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#leverage-build-cache