C.W.K.
Stream
Lesson 04 of 06 · published

Multi-Stage Build — 크게 빌드, 작게 보내

~18 min · dockerfile, size

Level 0Container 호기심
0 XP0/36 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Multi-stage build 가 왜 있냐

보통 빌드 땐 두꺼운 toolchain (컴파일러, 빌드 도구, dev 의존성) 필요한데 보낼 땐 슬림한 runtime 만 필요해. Multi-stage build 는 한 Dockerfile 에서 둘 다 줘.

FROM stage 여러 개 선언. 각각 다른 base image 가능. COPY --from=<stage> 로 이전 stage 에서 파일 가져와. 마지막 stage 만 최종 image 됨.

고전 Node 예시

Stage 1 은 Node + npm + 소스 + node_modules + dist/ 만드는 빌드 도구. Stage 2 는 nginx + dist/ 만. 최종 image: ~25MB. 단일 stage 였으면: ~1.2GB.

Code

Node → static site·dockerfile
# Stage 1: build
FROM node:22-alpine AS builder
WORKDIR /app

COPY package*.json ./
RUN npm ci

COPY . .
RUN npm run build
# /app/dist now contains the production assets

# Stage 2: serve (the only stage that becomes the final image)
FROM nginx:1.27-alpine
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

# Final image: ~25MB. The 1.2GB builder stage is discarded.
컴파일된 의존성 있는 Python·dockerfile
FROM python:3.12 AS builder
WORKDIR /build
RUN apt-get update && apt-get install -y --no-install-recommends gcc libpq-dev
COPY requirements.txt .
RUN pip install --no-cache-dir --user -r requirements.txt

FROM python:3.12-slim AS runtime
WORKDIR /app
COPY --from=builder /root/.local /root/.local
ENV PATH=/root/.local/bin:$PATH
COPY . .
CMD ["python", "main.py"]

# Build tools stay in the builder. Runtime gets only the installed packages.

External links

Exercise

Node 또는 Go 프로젝트 골라. 단일 stage Dockerfile 작성, 최종 크기 적어. Multi-stage 로 변환, 새 크기 적어. 두 Dockerfile 이랑 크기 차이 캡처. (힌트: docker images myapp 가 크기 보여줘.)

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.