Very Slow ng build --prod in Docker

Naso picture Naso · Apr 19, 2019 · Viewed 10.7k times · Source

When I try to build an angular7 project inside docker it takes around 40 minutes. The line that takes 40 minutes is

ng build --prod

92% chunk asset optimization TerserPlugin

I've ran ng build --prod outside docker on the same laptop it takes 2 minutes.

I've tried adding --build-optimizer false

and --sourceMap=false

Does not make any difference

Here is my Dockerfile

FROM node:carbon
WORKDIR /usr/src/app
COPY package.json package-lock.json ./
RUN npm install
RUN npm install -g @angular/[email protected]
COPY . .
RUN ng build --prod
EXPOSE 4200
CMD [ "npm", "start" ]
HEALTHCHECK --interval=5s --timeout=30s --retries=20 CMD curl --fail http://localhost:4200 || exit 1

Answer

Daniel picture Daniel · Apr 19, 2019

This issue with extremely slow builds is almost always related to the build process lacking memory.

Node will not allocate a lot of memory for a single process (512mb on 32bit systems and 1gb on 64bit systems), but running ng build with production settings uses a lot of memory.

You can use the Node paramteter max_old_space_size to set how much RAM you allow the process to use, but you have to pass the parameter directly to node so replace

ng build --prod

with

node --max_old_space_size=8192 ./node_modules/@angular/cli/bin/ng build --prod

it will allocate up to 8GB of RAM for the process, which will make it run much faster.

You can also add this to your scripts in package.json:

"scripts": {
  ....
  "build:prod": "node --max_old_space_size=4096 ./node_modules/@angular/cli/bin/ng build --prod"
 }

(If increasing the memory limit doesn't work, try running ng build --prod --verbose to see exact timings for different phases of the compilation)