SkillSprout
Chapter 2 · Lesson 4
Advanced
2 min read

Multi-stage Builds and Advanced Operations

Overview

Build tools are usually larger and more privileged than runtime code. Multi-stage builds use several build phases in one Dockerfile, copy the finished artifact into a small runtime stage, and leave build tools behind.

Detailed Notes

Multi-stage Node.js build

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

FROM nginx:alpine AS runtime
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80
  • AS build: names the first stage.
  • AS runtime: names the final stage.
  • COPY --from=build: copies only built files into Nginx.
  • Build tools and source dependencies are not copied into the runtime image.

Enable BuildKit if required:

bash
DOCKER_BUILDKIT=1 docker build -t my-app .

Modern Docker often enables BuildKit by default.

Health checks

dockerfile
HEALTHCHECK --interval=30s --timeout=3s --retries=3   CMD wget -q --spider http://localhost:3000/health || exit 1

The health check runs inside the container. Docker reports healthy or unhealthy, but orchestration must decide whether to restart or replace the container.

Debugging sequence

bash
docker ps -a
docker logs --tail 100 my-app
docker inspect my-app
docker stats my-app
docker top my-app
docker exec -it my-app sh
docker events --since 10m

Also set limits:

bash
docker update --memory 512m --cpus 1 my-app

When a container exits immediately, start by reading docker ps -a and docker logs; then inspect the command, environment and exit code.

Multi-stage build
Architecture
Build stagecompiler …Runtime stagesmall serverRegistryoptimized imageCOPY artifact
Key point. Build stage creates the application artifact.

Only the final stage becomes the deployed runtime image.

Common Interview Questions

Finished this lesson?

0 of 27 lessons done · 0% of the course