fix: optimize Dockerfile to use Yarn PnP instead of node-modules

- Use Yarn Plug'n'Play (PnP) for faster installs and smaller image size
- Keep .yarnrc.yml configuration instead of overriding it
- Copy PnP files (.pnp.cjs, .pnp.loader.mjs, .yarn cache) to production stage
- Use yarn workspaces focus --production for production dependencies
- Corepack manages Yarn version while PnP handles dependency resolution
This commit is contained in:
Damir Mukimov 2025-11-27 06:54:20 +01:00
parent 3ad0f9b538
commit 40be6866b0

View File

@ -1,5 +1,5 @@
# Multi-stage build for Node.js frontend application # Multi-stage build for Node.js frontend application
FROM node:22.21.1-alpine3.20 AS builder FROM node:iron-alpine3.22 AS builder
# Enable Corepack for Yarn 4.x # Enable Corepack for Yarn 4.x
RUN corepack enable RUN corepack enable
@ -7,10 +7,10 @@ RUN corepack enable
# Set working directory # Set working directory
WORKDIR /app WORKDIR /app
# Copy package files # Copy Yarn configuration and package files
COPY package.json yarn.lock ./ COPY .yarnrc.yml package.json yarn.lock ./
# Install dependencies # Install dependencies (uses PnP by default from .yarnrc.yml)
RUN yarn install --immutable RUN yarn install --immutable
# Copy source code # Copy source code
@ -20,25 +20,27 @@ COPY . .
RUN yarn build RUN yarn build
# Production stage # Production stage
FROM node:22.21.1-alpine3.20 AS production FROM node:iron-alpine3.22 AS production
# Enable Corepack for Yarn 4.x # Enable Corepack for Yarn 4.x
RUN corepack enable RUN corepack enable
# Create app user # Create app user
RUN addgroup -g 1001 -S nodejs RUN addgroup -g 1001 -S nodejs && \
RUN adduser -S nextjs -u 1001 adduser -S nextjs -u 1001
# Set working directory # Set working directory
WORKDIR /app WORKDIR /app
# Copy package files # Copy Yarn configuration and package files
COPY package.json yarn.lock ./ COPY .yarnrc.yml package.json yarn.lock ./
# Install all dependencies first, then clean up dev dependencies # Install production dependencies (uses PnP)
RUN yarn install --immutable && yarn autoclean --force RUN yarn workspaces focus --production
# Copy built application from builder stage # Copy PnP files and built application from builder stage
COPY --from=builder --chown=nextjs:nodejs /app/.pnp.cjs /app/.pnp.loader.mjs ./
COPY --from=builder --chown=nextjs:nodejs /app/.yarn ./.yarn
COPY --from=builder --chown=nextjs:nodejs /app/dist ./dist COPY --from=builder --chown=nextjs:nodejs /app/dist ./dist
# Switch to non-root user # Switch to non-root user