Step-by-Step Explanation
🔷 Stage 1 – Build the App
FROM node:18 AS builder
🔹 This is the base image to compile your app.
AS builder gives a name to this stage for later use.
WORKDIR /app
Creates /app directory in the image and sets it as the current
working directory.
COPY . .
Copies everything (source code) from your local folder to /app inside
the image.
dockerfile
CopyEdit
RUN npm install && npm run build
npm install: installs all dependencies.
npm run build: builds the frontend (e.g., React) into static files inside
a /build folder.
✅ After this step, you have:
swift
CopyEdit
/app/build/[Link]
/app/build/static/...
🔷 Stage 2 – Final Image with Nginx (Serving Static Files)
dockerfile
CopyEdit
FROM nginx:alpine
This starts a new, fresh image based on Nginx (Alpine =
lightweight).
No dev tools, no [Link] — just Nginx web server.
dockerfile
CopyEdit
COPY --from=builder /app/build /usr/share/nginx/html
This line copies the compiled files ([Link], JS, CSS) from Stage
1 (called builder) into Nginx’s default public folder
/usr/share/nginx/html.
⏳ Now Nginx will serve your app when the container starts.
⚡ Final Behavior When You Run the Container
bash
CopyEdit
docker build -t my-frontend-app .
docker run -p 80:80 my-frontend-app
➡️Open browser at [Link]
🎉 You will see your React/Vue/Angular frontend running, served by Nginx.
💡 Summary of Benefits
Feature Why It's Good
Multi-stage Keeps image small
No
Dev files are excluded
node_modules
Fast and efficient for serving
Uses Nginx
static files
Only static files and Nginx
Fast startup
needed
# Stage 1: build
FROM node:18 AS builder
WORKDIR /app
COPY . .
RUN npm install && npm run build
# Stage 2: run only built app
FROM nginx:alpine
COPY --from=builder /app/build /usr/share/nginx/html