This is a very simple example of the use of multi stage docker build that improves the docker's image size
🏠 Homepage
According to the official documentation, the use of multi stage docker build will help us as the following description.
One of the most challenging things about building images is keeping the image size down. Each instruction in the Dockerfile adds a layer to the image, and you need to remember to clean up any artifacts you don’t need before moving on to the next layer. To write a really efficient Dockerfile, you have traditionally needed to employ shell tricks and other logic to keep the layers as small as possible and to ensure that each layer has the artifacts it needs from the previous layer and nothing else.
It was actually very common to have one Dockerfile to use for development (which contained everything needed to build your application), and a slimmed-down one to use for production, which only contained your application and exactly what was needed to run it. This has been referred to as the “builder pattern”. Maintaining two Dockerfiles is not ideal.
Source: https://docs.docker.com/develop/develop-images/multistage-build/
As described before, I can resume the use of multi docker build in the following use cases.
- Reduce the final docker build image;
- Split the build, Run and etc... to stages phases;
- Cache the build Stages;
This is a piece of multi stage dockerfile split up in two stages. The first one will create a docker to build the code and the second one will get the output of first one
using the code COPY --from=buildStage /app/dist/ /app/
due to improve the final docker image size.
# Stage 1: Build the base code.
FROM node:14.17.0-alpine as buildStage
LABEL stage="builder"
...
# Stage 2. Run build container code using the code from buildStage phase.
FROM node:14.17.0-alpine
LABEL author="Thiago lopes da Silva<thiagoolsilva@gmail.com>"
...
COPY --from=buildStage /app/dist/ /app/
...
Please give it a try and go to the post that I've created about this topic in the medium
The post was written in the Portuguese language.
yarn install
yarn docker:build-clean
yarn docker:run
$output:
The method main() was called.
calling the uuid.v4()
Result: 032e4c47-0635-4e84-87b1-724d6e4be3f1
Done in 0.69s.
👤 Thiago lopes da silva thiagoolsilva@gmail.com
- Website: https://medium.com/@thiagolopessilva
- Twitter: @thiagoolsilva
- Github: @thiagoolsilva
- LinkedIn: @https://www.linkedin.com/in/thiago-lopes-silva-2b943a25/
Contributions, issues and feature requests are welcome!
Feel free to check issues page.
Give a ⭐️ if this project helped you!
Copyright © 2021 Thiago lopes da silva thiagoolsilva@gmail.com.
This project is Apache V2 licensed.
This README was generated with ❤️ by readme-md-generator