Multi Stage Docker Builds
Updated: 03 September 2023
A multi stage build is pretty much what it sounds like - It is a docker build which can have multiple stages capable of inheriting material from one another. Using this method an image, while being built, has access to a shared file system from the other image
In the below image on the first line we can see that we create the initial image using FROM node:8
and call it install-packages
. Therefter we install the application dependencies. Next in the production stage we start to build the second image, FROM node:8
once again, however note that in the COPY
lines we make use of a --from=install-packages
flag which indicates that we should copy the files from the install-packages
image instead of the local machine as we normally would do. The resulting image is the Production image. The Installation phase layers are discarded hence resulting in a smaller overall image without the unecessary build dependencies
1# Install Node Modules2FROM node:8 as install-packages3
4COPY app/package.json ./app/package.json5COPY server/package.json ./server/package.json6
7WORKDIR /app8RUN yarn9
10WORKDIR /server11RUN yarn12
13WORKDIR /14COPY app ./app15
16WORKDIR /app17RUN yarn build18
19# Build Production Image20FROM node:821
22WORKDIR /23COPY --from=install-packages app/build ./app/build24COPY --from=install-packages server ./server25COPY server server26
27WORKDIR /server28EXPOSE 300129CMD ["node", "index.js"]