Multi-stage builds for static sites in Nginx - Time & Space Complexity
We want to understand how the time it takes to build and serve a static site changes as the site grows.
How does the build process scale when we add more files or steps?
Analyze the time complexity of the following nginx multi-stage build snippet.
# Stage 1: Build static files
FROM node:18 AS builder
WORKDIR /app
COPY package.json .
RUN npm install
COPY . .
RUN npm run build
# Stage 2: Serve with nginx
FROM nginx:stable-alpine
COPY --from=builder /app/dist /usr/share/nginx/html
This snippet builds a static site using Node.js, then copies the built files to an nginx server image to serve them.
Look for repeated steps or loops in the build and serve process.
- Primary operation: npm install and npm run build process that reads and processes all source files.
- How many times: Each source file is processed once during the build stage.
As the number of source files grows, the build step takes longer because it processes each file.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 files | Processes 10 files once |
| 100 files | Processes 100 files once |
| 1000 files | Processes 1000 files once |
Pattern observation: The build time grows roughly in direct proportion to the number of files.
Time Complexity: O(n)
This means the build time grows linearly as you add more files to your static site.
[X] Wrong: "Adding more files won't affect build time much because nginx just serves files quickly."
[OK] Correct: The build step processes every file, so more files mean more work before nginx can serve them.
Understanding how build steps scale helps you explain deployment choices and predict build times in real projects.
What if we added caching to the npm install step? How would the time complexity change?