Multi-stage docker with nodejs

Multi-stage builds are mostly popular when using compiled languages, with heavy toolchains. For a node app, you would expect to need just the js files, and any dependencies.

I was therefore surprised to find that our images were weighing in at over 500MB, when the base node:18-alpine image is a mere 174MB. After some judicious commenting out, it seemed like the culprit was npm (shocker).

Moving the npm(/yarn) install to a discarded layer could save > 50%:

FROM node:18-alpine AS builder
WORKDIR /build
RUN --mount=type=ssh yarn install

FROM node:18-alpine
WORKDIR /app
COPY --from=builder /build/node_modules ./node_modules
...

Leave a comment