Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readDev ToolNode

Ship a Node image without devDependencies

Use a two-stage Dockerfile to compile in a build stage and copy only dist into a runner stage that installs production dependencies.

Your image builds and runs, and it carries more than it needs. The Dockerfile installs dependencies, copies the source and runs the build in one stage. The image you ship still holds TypeScript, src/ and npm's download cache.

FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
CMD ["node", "dist/index.js"]

The final image includes the layers from this stage, including the source and dependencies used to build it.

Build in one stage, ship from another

A multi-stage build uses more than one FROM. Each FROM starts a fresh stage, the last stage becomes the image, and COPY --from=<stage> pulls files out of an earlier one.

FROM node:22-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM node:22-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY package*.json ./
RUN npm ci --omit=dev && npm cache clean --force
COPY --from=build /app/dist ./dist
USER node
CMD ["node", "dist/index.js"]

The build stage is the old Dockerfile with a name. The runner stage starts from a clean node:22-alpine, installs production dependencies, clears the npm cache in the same layer and copies the compiled output. I name both stages with AS, so the copy line reads as from build.

diagram

What crosses from the build stage to the runner

The build stage keeps devDependencies, source and cache; only dist/ crosses into the runner.

What crosses and what stays

Only /app/dist crosses. The runner stage does not copy node_modules from build, because that folder holds the dev dependencies you are trying to leave out. It installs its own with --omit=dev, which is why runner copies package*.json again.

Use a committed npm lockfile for npm ci. Add a .dockerignore with node_modules and dist in it. Without one, COPY . . in the build stage copies your laptop's node_modules over the ones npm ci installed.

I ran the same npm steps by hand in two folders, build and runner, for a small TypeScript project with one dependency and three devDependencies.

$ npm ci
added 5 packages
$ npm run build
$ ls dist
index.js
$ npm ci --omit=dev
added 1 package
$ node dist/index.js
uptime limit: 2h

The first npm ci ran in build and the second in runner. The runner folder has the compiled output and one package, and it starts. If an install script requires your source or a dev dependency, adjust the runner install before using this Dockerfile.