skip to content
Burak Berk Keskin
Table of Contents

Overview

Packaging Node.js services into container images often results in bloated runtime layers when developer tooling, TypeScript compilers, test runners, and linters leak from the build stage into production artifacts.

While npm includes a built-in npm prune --production command to purge devDependencies from node_modules after compilation, Yarn Classic (v1) lacks a direct drop-in equivalent. Below is how I strip non-production dependencies in multi-stage Dockerfiles when using Yarn before pushing artifacts via my self-hosted GitHub Actions and Harbor CI/CD pipeline.

The Multi-Stage Strategy

The most effective pattern isolates compilation inside an ephemeral builder image and copies only the minimal runtime output into a stripped execution environment:

Dockerfile
FROM node:18-alpine AS builder
WORKDIR /app
COPY package.json yarn.lock ./
RUN yarn install --frozen-lockfile
COPY . .
RUN yarn run build
# Purge devDependencies in-place using production offline flags
RUN yarn install --production --ignore-scripts --prefer-offline --frozen-lockfile
FROM node:18-alpine AS runner
RUN apk add --no-cache tini
WORKDIR /app
ENV NODE_ENV=production
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/build ./
COPY --from=builder /app/package.json ./
ENTRYPOINT [ "/sbin/tini", "--" ]
CMD [ "node", "build/server.js" ]

Implementation Mechanics

1. Build Cache Optimization

Copying package.json and yarn.lock independently before the rest of the application codebase preserves Docker’s layer cache. Node modules are re-installed only when dependency manifests change, rather than on every source edit.

2. Pruning devDependencies In-Place

Running yarn install --production --ignore-scripts --prefer-offline --frozen-lockfile immediately after the compilation step forces Yarn to remove devDependencies from /app/node_modules while referencing cached tarballs offline, avoiding a costly secondary download over the network.

3. Process Management with Tini

Node.js was not engineered to run as PID 1 inside Linux namespaces: it does not forward POSIX termination signals (SIGINT, SIGTERM) or reap orphaned zombie child processes by default. Wrapping the runtime entrypoint with tini ensures graceful container shutdowns when orchestrators trigger rolling deployments.

Benchmark Results

Comparing the optimized multi-stage build against a single-stage baseline yielded significant operational gains:

  • Security Surface: Scanning with vulnerability scanners reduced Common Vulnerabilities and Exposures (CVEs) from 33 (13 medium, 20 high) down to 10 by shedding unneeded dev dependencies.
Security Scan Comparison
  • Image Footprint: Final container size dropped by more than 50%, accelerating CI/CD registry pushes and cluster pull times.
Docker Image Size Comparison