0
0
Dockerdevops~30 mins

Multi-stage builds concept in Docker - Mini Project: Build & Apply

Choose your learning style9 modes available
Docker Multi-Stage Build for a Simple Web App
📖 Scenario: You want to create a small web application using Docker. To keep your final Docker image small and efficient, you will use a multi-stage build. This means you will first build your app in one stage, then copy only the necessary files to a smaller image in the final stage.
🎯 Goal: Build a Dockerfile using multi-stage builds that compiles a simple static website in the first stage and then copies the built files to a lightweight web server image in the second stage.
📋 What You'll Learn
Create a first build stage named builder using the node:18-alpine image
In the builder stage, create a directory /app and add a file index.html with the exact content <h1>Hello from Builder</h1>
Create a second stage using the nginx:alpine image
Copy the index.html file from the builder stage to /usr/share/nginx/html/index.html in the final image
Set the default command to run nginx in the foreground
💡 Why This Matters
🌍 Real World
Multi-stage builds are used to create small, secure, and efficient Docker images by separating build and runtime environments.
💼 Career
Understanding multi-stage builds is essential for DevOps roles to optimize container images and improve deployment speed.
Progress0 / 4 steps
1
Create the builder stage with Node Alpine image
Write a Dockerfile that starts with a FROM node:18-alpine AS builder line. Then create a directory /app inside the container and add a file index.html with the exact content <h1>Hello from Builder</h1> inside /app.
Docker
Need a hint?

Use RUN mkdir /app to create the directory and RUN echo "<h1>Hello from Builder</h1>" > /app/index.html to create the file.

2
Add the final stage with Nginx Alpine image
Add a new stage starting with FROM nginx:alpine. This will be the final stage that serves the website.
Docker
Need a hint?

Start the final stage with FROM nginx:alpine.

3
Copy the built file from builder stage to final image
In the final stage, copy the file /app/index.html from the builder stage to /usr/share/nginx/html/index.html using the COPY --from=builder command.
Docker
Need a hint?

Use COPY --from=builder /app/index.html /usr/share/nginx/html/index.html to copy the file.

4
Set the default command to run nginx in foreground
Add a CMD instruction in the final stage to run nginx in the foreground using nginx -g 'daemon off;'. Then build the Docker image and run a container to verify the output by accessing http://localhost.
Docker
Need a hint?

Use CMD ["nginx", "-g", "daemon off;"] to keep nginx running in the foreground.