The Symptom
Symptom
Root Cause Analysis
Root Cause
The Dockerfile was poorly structured. It copied the entire directory (including `node_modules` and `.git`), ran `npm install`, and then ran `npm run build`. Every single file change invalidated the Docker layer cache, forcing a complete re-download of all dependencies. Furthermore, the base image was the bloated `node:18` (which is almost 1GB) instead of Alpine, and the `.dockerignore` file was completely missing.
FROM node:18
# The fatal flaw: Copying everything before installing invalidates cache!
COPY . .
RUN npm install
RUN npm run build
CMD ["npm", "start"]
Resolution
Resolution
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:18-alpine AS production
WORKDIR /app
COPY --from=builder /app/dist ./dist
CMD ["node", "dist/main.js"]
Discussions 0