I saw a dockerfile for building a Node.js app with npm:
FROM diamol/node AS builder,
WORKDIR /src
COPY src/package.json .
RUN npm install <-------------Q2
# app
FROM diamol/node <-------------Q1
EXPOSE 80
CMD ["node", "server.js"]
WORKDIR /app
COPY --from=builder /src/node_modules/ /app/node_modules/
COPY src/ .
I have some questions:
Q1-Why we need FROM diamol/node
twice, we already have it in the beginning, isn't it, what will happen if I remove the second FROM diamol/node
Q2- when the instruction runs npm install
, a lot of packages are downloaded to src folder and we know each instruction represents an image layer, so does those packages stored in "RUN npm install" layer, or they are saved in "WORKDIR /src" layer since src folder is created here?
CodePudding user response:
You can think as if they were 2 different Dockerfiles. So each one requires it's base image (FROM). And each one has its own layers.
The additional benefit from multi-stage is that it allow you to copy from one image to the other (the --from=builder in COPY instruction).
The npm install
in first image creates a new layer with node_modules directory.
The COPY --from=builder
in the second one, just copies that directory from the resulting first image.
This particular example doesn't seem to have any advantage over a single stage build.