NestJS minimize dockerfile NestJS minimize dockerfile docker docker

NestJS minimize dockerfile


For reducing docker image size you can use

  1. Multi-stage build
  2. Npm prune

While using multi-stage build you should have 2(or more) FROM directives, as usual, the first stage does build, and the second stage just copies build from the first temporary layer and have instructions for run the app. In our case, we should copy dist & node_modules directories.

The second important moment its correctly split dependencies between 'devDependencies' & 'dependencies' in your package.json file.

After you install deps in the first stage, you should use npm prune --production for remove devDependencies from node modules.

FROM node:12.14.1-alpine AS buildWORKDIR /appCOPY package*.json ./RUN npm ciCOPY . ./RUN npm run build && npm prune --productionFROM node:12.14.1-alpineWORKDIR /appENV NODE_ENV=productionCOPY --from=build /app/dist /app/distCOPY --from=build /app/node_modules /app/node_modulesEXPOSE 3000ENTRYPOINT [ "node" ]CMD [ "dist/main.js" ]

If you have troubles with node-gyp or just want to see - a full example with comments in this gist:

https://gist.github.com/nzvtrk/cba2970b1df9091b520811e521d9bd44

More useful references:

https://docs.docker.com/develop/develop-images/multistage-build/

https://docs.npmjs.com/cli/prune