
In-Class Exercise - Multi-Stage Dockerfile¶
- Create a
multi-stagedocker file that will build 2 images - The first image will be based on
alpineand will create a file namedalpine.txtwith the content:This is alpine image - The second image will be based on
nodeand will create a file namednode.txtwith the content:This is node image - The final image should be based on
alpineand should copy the files which you created from the previous stages and display their content when the container will run. - Hint: Use the
COPY --from=command to copy files from previous stages
Solution
Dockerfile Solution¶
Create a file named Dockerfile-exercise:
# First stage: Alpine image
FROM alpine AS alpine-stage
RUN echo "This is alpine image" > alpine.txt
# Second stage: Node image
FROM node AS node-stage
RUN echo "This is node image" > node.txt
# Final stage: Alpine with files from previous stages
FROM alpine
COPY --from=alpine-stage alpine.txt .
COPY --from=node-stage node.txt .
# Run the command to display contents
CMD cat alpine.txt && cat node.txt
Build and Test¶
Build the image:
Run the container:
Expected output:
Explanation¶
- First Stage (alpine-stage): Based on
alpine, createsalpine.txtwith the required content - Second Stage (node-stage): Based on
node, createsnode.txtwith the required content - Final Stage: Based on
alpine(lightweight), copies both files from previous stages usingCOPY --from=<stage-name>and displays their content when run