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 Modules
2
FROM node:8 as install-packages
3
4
COPY app/package.json ./app/package.json
5
COPY server/package.json ./server/package.json
6
7
WORKDIR /app
8
RUN yarn
9
10
WORKDIR /server
11
RUN yarn
12
13
WORKDIR /
14
COPY app ./app
15
16
WORKDIR /app
17
RUN yarn build
18
19
# Build Production Image
20
FROM node:8
21
22
WORKDIR /
23
COPY --from=install-packages app/build ./app/build
24
COPY --from=install-packages server ./server
25
COPY server server
26
27
WORKDIR /server
28
EXPOSE 3001
29
CMD ["node", "index.js"]