Member-only story
How to reduce the size of the docker image with the help of a multistage docker file?
As we all know when the Dockerfile builds an image, creates new layers on the image with each command mentioned in the Dockerfile.
FROM node:12-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
CMD ["npm", "run", "start"]
For Example: If we consider the above Dockerfile and build it.
We can see four layers in your image:
1. The base `node:12-alpine` image
2. A layer that sets the working directory to `/app`
3. A layer that copies the `package*.json` files to the `/app` directory
4. A layer that installs the dependencies and copies the rest of the files to the `/app` directory
Each layer in this method increases the image’s size, which is a problem. The ‘npm install’ command, which can be large, as it will download and install all the dependencies. Because the previous layer added the dependencies, even if you delete the “node_modules” directory in a later layer, the image size will still be large.
This is when we can solve the Docker image size issue with Multistage Dockerfile Method.