Docker image layers

Docker images are layer based – layer based architecture.

Each step (instruction) from a Dockerfile creates a layer. These layers are cached and reused next time the image is built.

Lets see one Docker file for a node.js app:

FROM node:12

WORKDIR /app

COPY . /app

RUN npm install

EXPOSE 80

CMD [ "node", "server.js" ]

Now, imagine we change the content of the app folder and then we rebuild the image. Docker will reuse layer from step 1, then reuse layer from step 2, but from then on, it will have to rebuild the rest as it would not know if npm install step would be different or not.

For that reason, we could hack around and rewrite the Dockerfile in a smarter way (Thanks Max). Check it out:

FROM node:12

WORKDIR /app

COPY package.json /app

RUN npm install

COPY . /app

EXPOSE 80

CMD ["node", "server.js"]

Is this not something to think about?