In this lesson, you will learn how to automate frontend asset compilation by integrating build tools directly into your multi-stage Docker pipeline to ensure your production images contain only the lean, ready-to-serve files.
The Problem: Bloat vs. Functionality
Modern frontend frameworks (like React, Vue, or SASS) require heavy build tools—compilers, minifiers, and package managers—to turn source code into static files (HTML, CSS, JS). If you install these in your final image, you end up with hundreds of megabytes of unnecessary "node_modules" and build artifacts. Furthermore, you increase your attack surface by including dev-dependencies in production.
The Solution: Multi-Stage Compilation
We use a two-stage approach. In the first stage, we use a "heavy" image (like node) to install all dependencies and run the build command. In the second stage, we copy only the resulting, minified assets into a lightweight web server image (like nginx).
Here is how that looks in your Dockerfile:
# Stage 1: Build the assets
FROM node:18 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build # This generates a 'dist' or 'build' folder
# Stage 2: Serve the assets
FROM nginx:alpine
# Copy only the compiled output from the builder stage
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
Why This Matters
By separating concerns, the nginx image never sees the source code or the build tools. It only receives the final, optimized output. This drastically reduces your image size, improves security, and ensures that your production environment remains strictly for serving content. Because we use the COPY --from=builder instruction, the intermediate build environment is discarded after the image is built, leaving behind a slim, efficient container ready for deployment to Kubernetes.
Key Takeaway: Always compile your static assets in a dedicated build stage and copy only the final, minified artifacts to your runtime image to keep your production deployments lean and secure.