Node Multi‑Stage Dockerfile
Efficient Dockerfile for Node projects that caches dependencies and builds only once.
Building Docker images for Node apps can be slow if dependencies are reinstalled on every build. Using multi‑stage builds and layering strategically reduces build times and produces smaller images. This example installs dependencies in a base layer, copies only the package files needed for npm install, builds the app, then copies the build into a slim runtime image.
# ----- build stage -----
FROM node:18-bullseye AS build
WORKDIR /app
# Install dependencies based on package files
COPY package*.json ./
RUN npm ci
# Copy source and build
COPY . .
RUN npm run build
# ----- runtime stage -----
FROM node:18-bullseye-slim AS runtime
WORKDIR /app
# Copy node_modules from build stage
COPY --from=build /app/node_modules ./node_modules
# Copy built assets
COPY --from=build /app/dist ./dist
# Set the runtime command
CMD ["node", "dist/index.js"]
This Dockerfile caches the npm ci
layer unless your package.json
or package-lock.json
change. The final image contains only the compiled code and dependencies, reducing size and attack surface. Adjust the dist
path and CMD
line based on your build output and entry point.