Docker Layers for faster build times

Docker Layers for faster build times

ยท

2 min read

The order of instruction on the docker file matters a lot. Each instruction in the docker file is a layer.

With the docker, when you are building an image, layers that are cached and not changed will be reused again. So, it is essential to keep the instruction order right so that most layers are reused again.

Let's dive into an example

FROM golang # layer 1

COPY . . # layer 2
RUN go build -o myapp # layer 3

Now, here every time there are code changes, go modules will be downloaded and build will be slow. The only unchanged layer is layer1 so the build will start from layer2 and layer1 will be used again.

It can be easily changed to this for faster build time.

FROM golang # layer 1

COPY go.mod go.sum . # layer 2
RUN go mod download # layer 3

COPY . . # layer 4
RUN go build -o myapp # layer 5

Here, if go modules are not changed then docker will start building from layer 4 as other layers are unchanged and can be used from cache.

Another example could be always downloading stuff in the beginning so that they are used from cache like dependencies or packages. We make sure here that one layer is just our packages and it will reused again for all future builds.

FROM golang # layer 1

RUN apt-get -y install x11 pulse # layer2

COPY . . # layer 3

Did you find this article valuable?

Support Dhairya's Blog by becoming a sponsor. Any amount is appreciated!