✦ For everyone, free.

Practical knowledge for real and everyday life

Home

12.2.2 Node Docker Workflow

A focused guide to Node Docker Workflow, connecting core concepts with practical Docker and container operations.

The Node.js Docker workflow centers on efficient dependency installation through proper layer caching, careful handling of the node_modules directory, and a clear distinction between development dependencies and the leaner set actually needed in a production runtime image.

The Basic Node.js Dockerfile Structure

Dependencies are installed in their own layer, separate from copying the full application source.

FROM node:20-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --production
COPY . .
CMD ["node", "server.js"]

Copying only the package files before running the install step allows Docker to cache this layer separately, avoiding unnecessary reinstalls when only application code changes.

Why a Multi-Stage Build Often Improves a Node.js Image Further

For applications with a build step (TypeScript compilation, bundling), a multi-stage build separates that build-time tooling from the leaner runtime image.

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

FROM node:20-alpine
WORKDIR /app
COPY --from=build /app/dist ./dist
COPY package*.json ./
RUN npm ci --production
CMD ["node", "dist/server.js"]
Why Using npm ci Rather Than npm install Matters in This Context

npm ci installs exactly what's specified in the lockfile, providing a more reliable, reproducible install than npm install, which can in certain cases modify the lockfile itself.

npm ci --production
Running as a Non-Root User

Many official Node.js images include a pre-created node user, making it straightforward to adopt non-root execution.

USER node
Why the Node Docker Workflow Matters

These established conventions — careful dependency layer caching, multi-stage builds for applications with a build step, reliable installs through npm ci — together produce efficient, reliable Node.js container images appropriate for this ecosystem's particular tooling and conventions.

Content in this section