2 min read

[docker] make docker build faster

Speed up your container image builds with few changes on your Dockerfile
[docker] make docker build faster

Intro

Building docker images is most of the time an unavoidable fundamental step in our DevOps pipeline.

And a slow docker build due to a missing cache optimization can lead the teams to a lot of wasted time,
consequently, a reduced efficiency and of course a money loss 🤑🤑🤑

Let's see some easy but very useful tips to speed up our docker builds.

Order layers wisely

Consider for example the following Dockerfile to build a sample nodejs application.

FROM node:20
 
WORKDIR /app
COPY . .
RUN npm install
RUN npm build

This is a very inefficient build.

Why?
Since the Docker build
invalidates all layers after the first line that is detected as changed,
even if you change only an asset file (ex. image, css, js) without impacting the package.json, the RUN npm install will be executed again without taking the advantage of docker cache.

For who does not know nodejs, package.json contains dependencies definition and the npm install downloads and installs that dependencies.

The efficient way would be instead

FROM node:20
 
WORKDIR /app
COPY package.json package-lock.json /app/
RUN npm install
COPY . .
RUN npm build

In the above way instead, the RUN npm install will be runned only on package.json/package-lock.json changes, boosting the docker cache usage.

Make the layers as smaller as possible

Copy only the needed files

The fastest way to copy our application source is to do of course

COPY . .

but this will probably foot us the bill during docker build phase in case of a lot of unnecessary files/folders.

Do instead a more fine-grained command

COPY app app

.dockerignore

Sometimes it is not predictable what are the files needed, in that case is preferable to use the .dockerignore file, for example

.git
node_modules
README.md

Install only the needed dependencies

A practical example is for example while using Ubuntu images.

In that case the usage of --no-install-recommends option in apt install command could make a significant impact on layers size.

Ex.

RUN apt-get update && apt-get install --no-install-recommends --yes python3

Suggested reading on this topic --> https://ubuntu.com/blog/we-reduced-our-docker-images-by-60-with-no-install-recommends

Tweets by YBacciarini