How do you write an efficient Dockerfile for a Node.js API?

IntermediateConceptNode.js builds (npm, package.json)
Answer

Short answer

Use a small base (node:22-alpine or -slim), copy package.json + package-lock.json first and run npm ci so dependencies are cached in their own layer, install only production dependencies in the final image, add a .dockerignore, set NODE_ENV=production, and run as the non-root node user.

Example

FROM node:22-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build && npm prune --omit=dev     # drop devDependencies after building

FROM node:22-alpine
WORKDIR /app
ENV NODE_ENV=production
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
COPY package.json .
USER node
EXPOSE 3000
CMD ["node", "dist/server.js"]
# .dockerignore
node_modules
.git
.env
coverage

Why each choice

Choice Reason
Lockfile copied before source Code edits don't trigger a full reinstall
npm prune --omit=dev Smaller image, fewer CVEs
.dockerignore Local node_modules and secrets never enter the image
CMD ["node", ...] not npm start Node receives SIGTERM directly for graceful shutdown
USER node Not running as root

What to say in the interview

"Multi-stage with dependency layer caching, production-only node_modules, a .dockerignore, non-root user, and starting node directly so signals reach the process for graceful shutdown."

All Build Tools (Java, Node.js, Python, .NET) questions Roadmap: Node.js apps: npm & package.json

More on Node.js builds (npm, package.json)