1. Use a multi-stage build
Keep compilers and build dependencies in a builder stage, then copy only the runtime artifacts into the final image.
FROM node:22 AS build WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . RUN npm run build FROM node:22-alpine WORKDIR /app COPY --from=build /app/dist ./dist CMD ["node","dist/server.js"]
2. Use a suitable base image
A smaller runtime base can reduce image size, but compatibility and security still matter. Test the application thoroughly instead of choosing a base image only because it is small.
3. Use .dockerignore
Exclude Git history, local dependencies, build output and other files that do not belong in the image build context.
node_modules .git coverage *.log .env
4. Combine this with Kubernetes practices
Smaller images pull faster when a new node starts, which can improve scaling and rollout time. Keep image tags immutable and regularly scan the final runtime image.
Interview tip: Mention multi-stage builds, .dockerignore, minimal runtime dependencies, layer caching and immutable image tags.