Optimize docker image size for a Nodejs app

📅2023-08-01🧐144

To optimize docker container image size for a Nodejs application, we could use multi-stage builds. Depends on different application we could apply different strategies.

Here are two example for backend and frontend applications in respectively.

Example 1: Using multi-stage builds for typescript app
FROM node:18.14.2-alpine3.17 AS builder

RUN apk add --no-cache libc6-compat

RUN corepack enable && corepack prepare pnpm@8.6.9 --activate

RUN mkdir /app
WORKDIR /app
COPY . .

RUN pnpm install -s
RUN pnpm run build
RUN pnpm prune --prod --no-optional

FROM node:18.14.2-alpine3.17 AS runner

RUN mkdir /app
WORKDIR /app
ENV NODE_ENV=production

COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist

EXPOSE 9000
ENV PORT 9000
CMD ["node", "dist/server/start.js"]
Example 2: Using multi-stage builds to build a Next.js app

Next.js allows us to build a standalone package, so we just need to copy the built standalone package to the stage of runner

FROM node:18.14.2-alpine3.17 AS builder

RUN apk add --no-cache libc6-compat

# get latest version of pnpm from https://www.npmjs.com/package/pnpm

RUN corepack enable && corepack prepare pnpm@8.6.0 --activate

RUN mkdir /workcode
WORKDIR /workcode
COPY . .

RUN pnpm install -s && NODE_ENV=production pnpm build

FROM node:18.14.2-alpine3.17 AS runner

ENV NODE_ENV=production

RUN mkdir /app
WORKDIR /app

COPY --from=builder /workcode/public ./public
COPY --from=builder /workcode/.next/standalone ./
COPY --from=builder /workcode/.next/static ./.next/static

EXPOSE 3000
ENV PORT 3000
CMD ["node", "server.js"]