Multi-stage build trong Docker dùng khi nào?

Multi-stage build tách stage build và stage runtime. Stage build chứa compiler, dev dependencies và artifacts tạm; stage runtime chỉ copy output cần chạy. Kết quả là image nhỏ hơn, ít surface security hơn và deploy nhanh hơn.

Ví dụ:

FROM node:22-alpine AS build
WORKDIR /app
COPY package.json pnpm-lock.yaml ./
RUN corepack enable && pnpm install --frozen-lockfile
COPY . .
RUN pnpm build

FROM node:22-alpine AS runtime
WORKDIR /app
COPY --from=build /app/.next ./.next
COPY --from=build /app/package.json ./package.json
CMD ["node", "server.js"]

Không nên ship cả compiler, source test và cache build nếu runtime không cần.

Xem toàn bộ Docker & Kubernetes cùng filter theo level & chủ đề con.

Mở danh sách Docker & Kubernetes