Mexson Fernandes
17 April 202353% decrease in docker image size - Multi stage docker (Nuxt.js)
First we had a docker layer with following `Dockerfile`.
FROM node:12-alpine
# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
# Install system requirements
RUN apk update && apk add --no-cache --virtual .build-deps make gcc g++ python \
&& rm -rf node_modules \
&& apk add git \
&& apk del .build-deps
# ENV
ENV NODE_ENV=production
# Install app dependencies
COPY package.json /usr/src/app/
COPY yarn.lock /usr/src/app/
RUN yarn install
# Bundle app source
COPY . /usr/src/app
RUN yarn generate
# Clear the cache
RUN yarn cache clean
ENV HOST 0.0.0.0
EXPOSE 3000
CMD ["yarn", "start" ]
This setup had a size of 853 MB.
My WiFi was over and I was allowed to hit 512 KB max.
So I had to reduce the size as I needed to constantly push this image for an on premise solution.
After some minor research I found that multi-stage builds do help.
So here my updated Dockerfile.
FROM node:12-alpine AS build
# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
# Install system requirements
RUN apk update && apk add --no-cache --virtual .build-deps make gcc g++ python \
&& rm -rf node_modules \
&& apk add git \
&& apk del .build-deps
# ENV
ENV NODE_ENV=production
# Install app dependencies
COPY package.json /usr/src/app/
COPY yarn.lock /usr/src/app/
RUN yarn install
# Bundle app source
COPY . /usr/src/app
RUN yarn generate
# Clear the cache
RUN yarn cache clean
FROM gcr.io/distroless/nodejs
COPY --from=build /usr/src/app /usr/src/app
WORKDIR /usr/src/app
ENV HOST 0.0.0.0
EXPOSE 3000
CMD ["standalone.js" ]
The distroless idea I got from the referred article (link below).
Now my docker image has final size of 409 MB. A massive decrease in size at first go.
I will look into reducing it more when I get time. 😉
Bonus: Content of standalone.js
for all Nuxt.js developers.
require('child_process').fork('node_modules/nuxt/bin/nuxt.js', ['start'])
Ref: Why You Should Use Multi-Stage Docker Builds in Production | by Bryant Hagadorn | ITNEXT