Multistage builds in Docker are a feature that allows you to create smaller and more efficient Docker images by using multiple build stages within a single Dockerfile. This feature is especially useful when you're building complex applications or when you need to compile code within the Docker image.
Build create with base image and execute with slim or distroless images
Here's how multistage builds work:
Multiple Stages: A Dockerfile can define multiple stages, each with its own base image and set of instructions. Each stage can copy artifacts or files from the previous stage.
Intermediate Images: Each stage in a multistage build produces an intermediate image. Only the final stage's image is saved as the final Docker image.
Reduced Image Size: Multistage builds allow you to include only necessary dependencies and files in the final image, reducing its size. For example, you might use one stage to compile code and another stage to copy the compiled binary into the final image.
Clarity and Maintainability: Multistage builds can improve the clarity and maintainability of your Dockerfiles by separating different build steps into distinct stages.
Here's a simple example of a multistage Dockerfile for a Node.js application:
Dockerfile : -
Stage 1: Build the Node.js application
FROM node:14 AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm install
COPY . .
RUN npm run build
Stage 2: Create the production image
FROM nginx:alpine
COPY --from=build /app/build /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
Utility:
Reduce image size
Less image layer
Container creation fast
Stage 1 (
build
stage) uses thenode:14
base image to install dependencies, build the Node.js application, and produce the necessary artifacts.Stage 2 (
nginx
stage) uses thenginx:alpine
base image and copies the built artifacts from the previous stage into the appropriate location in the final image. This stage sets up Nginx to serve the static files.
When you build an image using this Dockerfile, Docker will execute both stages, but only the artifacts from the second stage (nginx
stage) will be included in the final image. This results in a smaller and more efficient Docker image that only contains the compiled application and necessary runtime dependencies.
Multistage builds are a powerful feature of Docker that can significantly improve the efficiency and maintainability of your Docker images, especially for complex applications with multiple dependencies and build steps.
Checkout the link below :
https://github.com/soumen321/two-tier-node-app/tree/fth-multistage
In this application image size reduce :
From 1.12 GB to 218 MB