[Docker] Using Docker Multi-Stage Build to Make Image Smaller

Easy To Learn Multi-Stage Building Docker Image.

[Docker] Using Docker Multi-Stage Build to Make Image Smaller

In this article, we using nextjs to present how make image smaller

No multi-stage Dockerfile

FROM node:12.16.1-alpine

WORKDIR /app

COPY ./package.json ./

COPY ./package-lock.json ./

COPY ./ ./

RUN npm install

RUN npm run build

EXPOSE 3001

CMD [ "npm", "run", "start" ]

Using multi-stage Dockerfile

FROM node:12.16.1-alpine AS nodeModuleBuilder

WORKDIR /app

COPY ./package.json ./

COPY ./package-lock.json ./

RUN npm install --only=production

# ---------

FROM node:12.16.1-alpine AS codeBuilder

WORKDIR /app

COPY ./package.json ./

COPY ./package-lock.json ./

COPY ./ ./

RUN npm install

RUN npm run build

# ---------

FROM node:12.16.1-alpine AS runtime
# set workspace
WORKDIR /app

# copy binary from builder stage
COPY --from=codeBuilder /app/dist ./

COPY --from=nodeModuleBuilder /app/node_modules ./node_modules

EXPOSE 3001

CMD [ "node", "main.js" ]