0
0
Dockerdevops~30 mins

Named build stages in Docker - Mini Project: Build & Apply

Choose your learning style9 modes available
Named Build Stages in Docker
📖 Scenario: You are creating a Docker image for a simple web application. To keep the image size small and organized, you will use named build stages.
🎯 Goal: Build a multi-stage Dockerfile using named build stages to separate the build environment from the final runtime environment.
📋 What You'll Learn
Create a Dockerfile with two named build stages: builder and final
In the builder stage, use the node:18 image and create a file /app/build.txt with the text Build complete
In the final stage, use the alpine:latest image and copy the /app/build.txt file from the builder stage
Print the contents of /app/build.txt when running the container
💡 Why This Matters
🌍 Real World
Using named build stages helps create smaller, cleaner Docker images by separating build tools from runtime environments.
💼 Career
Many DevOps and software engineering roles require writing efficient Dockerfiles with multi-stage builds to optimize deployment pipelines.
Progress0 / 4 steps
1
Create the builder stage
Create a Dockerfile with a named build stage called builder that uses the node:18 image. Inside this stage, create a directory /app and add a file /app/build.txt containing the text Build complete using a single RUN command.
Docker
Need a hint?

Use FROM node:18 AS builder to name the build stage. Use RUN mkdir /app && echo "Build complete" > /app/build.txt to create the file.

2
Add the final stage
Add a second named build stage called final that uses the alpine:latest image. In this stage, copy the file /app/build.txt from the builder stage to the same path /app/build.txt.
Docker
Need a hint?

Use FROM alpine:latest AS final to start the final stage. Use COPY --from=builder /app/build.txt /app/build.txt to copy the file.

3
Add a command to display the file
In the final stage, add a command to run when the container starts that prints the contents of /app/build.txt using cat.
Docker
Need a hint?

Use CMD ["cat", "/app/build.txt"] to print the file when the container runs.

4
Build and run the Docker image
Build the Docker image with the tag buildstage-demo and run a container from it. The output should be the text Build complete.
Docker
Need a hint?

Use docker build -t buildstage-demo . to build and docker run --rm buildstage-demo to run the container.