Creating a REST API with NestJS — Part 04 — Quick Adding a Dockerfile with Reduced Image Size. We will focus on creating a reduced image size for our NestJS REST application! If you are interested only in the Dockerfile part, just skip the quick introduction and move forward. We are building a REST API using NestJS but during my previous weeks of work with NestJS (but using GraphQL)
In this article, we are going to expand our current NestJS project to quick-add a real working example of a Dockerfile to run as a container.
This article will focus basically on a common NestJS issue: A basic image can be extremely big without some handling. We will focus on creating a reduced image size for our NestJS REST application!
If you are interested only in the Dockerfile part, just skip the quick introduction and move forward.
If you are not aware of my article series, you can start with the first article here.
We are building a REST API using NestJS but during my previous weeks of work with NestJS (but using GraphQL), I faced a common issue across several projects: the Dockerfile. If you know the basics of using docker, you probably can go to Google and check how to build a docker image, and for the majority of simple backend scaffolding or similar, you can find something super similar as:
FROM node:14.15.0-alpine3.10 USER 2000 RUN mkdir -p /home/node/app/node_modules && chown -R 2000:2000 /home/node/app WORKDIR /home/node/app COPY --chown=2000:2000 . /home/node/app RUN yarn install RUN yarn build EXPOSE 3000 ENTRYPOINT ["node"] CMD ["/home/node/app/dist/main.js"]
It’s great, it works well. You can do a quick Google to understand why we are setting a user instead of using a root (which you should).
The hidden issue here is that if you run this in a NestJS project, the final image (with just a basic Rest API with Express under the hood, without even a GraphQL module) will have more than 900MB!
To see this by yourself, take this sample repository from my previous article. After having the code in your computer, at the root of the directory add a file called Dockerfile and paste the above code. Then don’t forget to add a .dockerignore file and to add node_modules/ there as well.
The main goal of this blog is to explain the “Architecture of Nodejs” and to know how the Nodejs works behind the scenes. Generally, most of the server-side languages, like PHP, ASP.NET, Ruby, and including Nodejs follows multi-threaded architecture. That means for each client-side request initiates a new thread or even a new process.
Looking to build dynamic, extensively featured, and full-fledged web applications? **[Hire NodeJs Developer](https://hourlydeveloper.io/hire-dedicated-node-js-developer/ "Hire NodeJs Developer")** to create a real-time, faster, and scalable...