Optimize node docker file
- Dominant language
- C#
- Stars
- 6.3k
- Forks
- 991
- Avg merge
- 2d 15h
- Merged PRs (30d)
- 196
Description
From Claude 😄
Optimization Opportunities
1. Poor layer caching for dependencies (HIGH IMPACT)
- Currently copies all files first, then runs npm ci
- Any file change invalidates the npm install cache
- Fix: Copy package*.json files first, run npm ci, then copy source code
2. Copying unnecessary files (MEDIUM IMPACT)
- COPY . . includes everything (node_modules, temp files, git files, etc.)
- Fix: Use a .dockerignore file or copy selectively
3. Installing dev dependencies unnecessarily (MEDIUM IMPACT)
- npm ci installs both production and dev dependencies
- These get copied to the runtime stage
- Fix: Use npm ci --omit=dev in build stage
4. Inefficient runtime copy (LOW-MEDIUM IMPACT)
- Copies entire /app directory from build to runtime
- Could copy only node_modules/ and necessary app files
- Fix: Selective copying
5. Missing BuildKit cache mounts (MEDIUM IMPACT on rebuild times)
- Could use --mount=type=cache,target=/root/.npm to cache npm downloads
- Speeds up repeated builds significantly
Optimized Dockerfile Example
```Dockerfile
FROM node:22-alpine AS build
WORKDIR /app
# Copy dependency files first for better caching
COPY package*.json ./
RUN --mount=type=cache,target=/root/.npm \
npm ci --omit=dev
# Copy application source
COPY app.js ./
FROM node:22-alpine AS runtime
WORKDIR /app
# Copy only production dependencies and app
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/app.js ./
ENV NODE_ENV=production
EXPOSE 3000
USER node
ENTRYPOINT ["node","app.js"]
```
Expected improvements:
- Faster rebuilds when only source code changes (dependencies cached)
- Smaller final image (no dev dependencies)
- 30-50% faster builds with cache mounts
- Better Docker layer caching efficiency
Contributor guide
Assessment
This issue has not been assessed yet.