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.
More on Write-a-Dockerfile tasks
Write a Dockerfile for a Python Flask app that runs with gunicorn as a non-root user.BeginnerWrite a Dockerfile for a Go service that produces a tiny image (under 20 MB).IntermediateWrite a multi-stage Dockerfile for a Java Spring Boot app built with Maven.IntermediateWrite a Dockerfile for a static React site served by Nginx.BeginnerThis Dockerfile rebuilds dependencies on every code change. Fix it.BeginnerWrite a `.dockerignore` for a typical Node or Python project and explain why it matters.Beginner