0
0
Dockerdevops~20 mins

Copying from build stage to final stage in Docker - Mini Project: Build & Apply

Choose your learning style9 modes available
Copying from build stage to final stage
📖 Scenario: You are creating a Docker image for a simple web application. To keep the final image small, you want to use a multi-stage build. The first stage will build the application, and the second stage will copy only the necessary files from the build stage.
🎯 Goal: Build a multi-stage Dockerfile where the final stage copies the built application files from the build stage.
📋 What You'll Learn
Create a build stage named builder using the node:18 image
In the build stage, create a directory /app and add a file index.js with the content console.log('Hello from build stage');
Create a final stage using the node:18-slim image
Copy the index.js file from the builder stage to the final stage's /app directory
Set the working directory to /app in the final stage
Set the default command to run node index.js
💡 Why This Matters
🌍 Real World
Multi-stage builds are used in real projects to separate building and running environments. This keeps the final Docker image small and secure by excluding build tools.
💼 Career
Understanding multi-stage Docker builds is important for DevOps roles, as it improves deployment efficiency and image management.
Progress0 / 4 steps
1
Create the build stage
Create a build stage named builder using the node:18 image. Inside it, create a directory /app and add a file index.js with the content console.log('Hello from build stage'); using a RUN command.
Docker
Need a hint?

Use FROM node:18 AS builder to name the build stage. Use RUN mkdir /app to create the directory. Use echo to create the index.js file with the exact content.

2
Create the final stage
Create the final stage using the node:18-slim image. This stage will be the last FROM instruction in the Dockerfile.
Docker
Need a hint?

Use FROM node:18-slim to start the final stage.

3
Copy files from build stage to final stage
In the final stage, copy the index.js file from the builder stage's /app directory to the final stage's /app directory using the COPY --from=builder command. Then set the working directory to /app.
Docker
Need a hint?

Use COPY --from=builder /app/index.js /app/index.js to copy the file. Use WORKDIR /app to set the working directory.

4
Set the default command
In the final stage, add a CMD instruction to run node index.js when the container starts.
Docker
Need a hint?

Use CMD ["node", "index.js"] to set the default command.