Skip to main content
InterviewHubPRO
Section Overview
Q14

Question 14 of 50

Part 2: Core Architecture & Implementation (Mid-Level)

28%
Docker & Containers (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)

How do Multi-Stage Docker Builds reduce production image size and protect build secrets?

senior LevelMost AskedCode ExampleDocker & ContainersSystem Design

In Simple Words: Traditional Dockerfiles included compilers, SDKs, build tools, package managers, and test runners in the final image, bloating size to gigabytes and increasing the security attack surface. Multi-Stage Builds allow you to define multiple FROM lines in a single Dockerfile. You compile code in temporary builder stages, then copy only the compiled artifacts into a clean, minimal runtime image.

dockerfile
# Stage 1: Build stage (contains Node.js SDK, TypeScript compiler, devDependencies)
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build && npm prune --production

# Stage 2: Minimal Production Runtime
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production

# Security: Create and switch to non-root user
USER node

# Copy ONLY built JS files and pruned production node_modules from builder
COPY --chown=node:node --from=builder /app/package.json ./
COPY --chown=node:node --from=builder /app/node_modules ./node_modules
COPY --chown=node:node --from=builder /app/dist ./dist

EXPOSE 3000
CMD ["node", "dist/main.js"]

Result: Image size drops from ~950MB to ~75MB.