Interview Prep/Real-World Interview/Write-a-Dockerfile tasks

Write a production Dockerfile for a Node.js API using a multi-stage build.

IntermediateHands-onWrite-a-Dockerfile tasks
Answer
# syntax=docker/dockerfile:1
FROM node:22-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev

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

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

Key trick → Copy only the lockfiles before npm ci so the dependency layer stays cached until dependencies change. The final stage ships prod dependencies only and runs as the built-in node user.

All Real-World Interview questions Roadmap: Interview readiness

More on Write-a-Dockerfile tasks