Reminder App - A Two - Tier Node Application (V-2)

Reminder App - A Two - Tier Node Application (V-2)

Multistage Docker

ยท

2 min read

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:

  1. 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.

  2. 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.

  3. 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.

  4. 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:

  5. Dockerfile : -

  6. 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 the node:14 base image to install dependencies, build the Node.js application, and produce the necessary artifacts.

    • Stage 2 (nginx stage) uses the nginx: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

ย