{"componentChunkName":"component---src-blog-post-template-js","path":"/blog/docker-layers-optimizing","result":{"pageContext":{"page":{"fileAbsolutePath":"/opt/build/repo/gatsby-site/scraped-data/posts/2020-10-11-dockerfile-optimize.md","html":"<p>One small problem I recently came across was a project that had a slow build time to run, ~7 mins approx. Config changes required a rebuild, so 7 mins per change. Something i noticed was npm packages being installed for config changes and even HTML changes - why do I need to download 1000+ npm packages if i'm only changing HTML? Madness!</p>\n<p>Docker <em>can</em> cache commands but only if the Dockerfile is written in a certain way. Take the following scenario:</p>\n<pre><code>FROM node:9\nCOPY /src /src\nRUN npm install\nRUN npm run build\n</code></pre>\n<p>Docker <em>can</em> cache each command and create a <a href=\"https://docs.docker.com/storage/storagedriver/#images-and-layers\">Layer</a>. Layers are cached if Docker detects that no files have been changed for that command. </p>\n<p>By splitting the COPY into 2 commands, we can utilize caching and speed up the build time for builds that haven't modified npm packages:</p>\n<pre><code>FROM node:9\nCOPY /src/package*.json /src\n# Docker will cache these 2 layers if package.json and package.lock.json are unmodified\nRUN npm install\n\n# copy the rest of our code and run a fresh build\nCOPY /src /src\nRUN npm run build\n</code></pre>\n<p>Just by adding 1 line, we can speed up most of our builds - in my scenario it was local builds and CI server builds (npm packages rarely change in a mature project)</p>\n<p>This 1 line <code>Dockerfile</code> change has saved our team a few minutes per build (we had some large / slow npm dependencies for things like integration testing such as cypress).</p>\n<p>This is because Docker only reuses a cached layer if every file involved in that layer is unchanged. When you <code>COPY . .</code> before npm install, any HTML, JS, or config change invalidates the whole dependency layer.</p>\n<p>That's all folks!</p>","frontmatter":{"title":"Speed up your Docker builds using layer caching (avoid reinstalling dependencies)","description":"Docker layers and optimizing your Dockerfile","permalink":"/docker-layers-optimizing","tags":"docker,dockerfile,performance","date":"2020-10-11 20:32:14 +0100"}},"date":"2020-10-11 20:32:14 +0100"}}}