Skip to main content

๐Ÿ‘ฉโ€๐Ÿ’ป Multi-stage Build

็‚บไฝ•่ฆไฝฟ็”จ Multi-stage Buildโ€‹

ๅœจ็›ดๆŽฅๅปบ็ซ‹ nest ็š„ docker image ๆ™‚๏ผŒ

image ่‡ณๅฐ‘ๆœƒ 400 ๅคš mb๏ผŒๅฆ‚ๆžœ่ฆ้€ฒ่กŒ็˜ฆ่บซๆ‰“ๅŒ…้‚ฃๅ‹ขๅฟ…้œ€่ฆๅŸท่กŒๆญคๅ‹•ไฝœ

่ฉฆๅš nest Multi-stage Buildโ€‹

dockerfileโ€‹

ๆญคๆญฅ้ฉŸๆ˜ฏๅ…ˆไฝฟ็”จ้–‹็™ผ็’ฐๅขƒ้€ฒ่กŒๆ‰“ๅŒ…๏ผŒๆŽฅไธ‹ไพ†ไพ้  pnpm ไพ†ๅฎ‰่ฃ็”Ÿ็”ข็’ฐๅขƒๆ‰€้œ€่ฆ็”จๅˆฐ็š„ไพ่ณด

# development image
FROM node:alpine AS development

# ๅปบ็ซ‹app็›ฎ้Œ„
WORKDIR /usr/src/app

# ่ค‡่ฃฝไพ่ณดๆช”
COPY package*.json ./

COPY tsconfig*.json ./

# ไธ‹่ผ‰ pnpm
RUN npm i -g pnpm

# ่ค‡่ฃฝ็จ‹ๅผ็ขผ
COPY . . /usr/src/app/

# ไธ‹่ผ‰ไพ่ณด
RUN pnpm install -r

# ้ƒจๅฑฌๅฐˆๆกˆ
RUN pnpm run build

# production image
FROM node:alpine AS production

# ๅปบ็ซ‹app็›ฎ้Œ„
WORKDIR /usr/src/app

# ่ค‡่ฃฝไพ่ณดๆช”
COPY package.json ./

COPY pnpm-lock.yaml ./

# ไธ‹่ผ‰ pnpm
RUN npm i -g pnpm

# ไธ‹่ผ‰ไพ่ณด(ๅชไธ‹่ผ‰้œ€ไฝฟ็”จ็š„ไพ่ณด)
RUN pnpm install --prod

# ่ค‡่ฃฝๅ‰›ๅ‰›ๆ‰“ๅŒ…็š„ๆช”ๆกˆ
COPY --from=development /usr/src/app/dist ./dist

# ๅ•Ÿๅ‹•ๆœๅ‹™
CMD [ "node", "dist/main.js" ]

ref:

Multi-stage Build, Miles

ๆขๅคงๅ“ฅ github