skip to Main Content

I’m no React developer, and I’ve been doing a docker course that uses a multi-stage build Dockerfile with node and nginx to dockerize a React app. Why is nginx needed? And why can’t we simply use npm start in production? Doesn’t it already start a server and exposes the port for React to run?

2

Answers


  1. When you are ready with your react app and publish it (npm run build), you will get a bunch of static html and js files. And somehow you want to serve them, this is where a webserver, for example nginx comes in. (You can use any other webserver, for example serve)

    You can serve with node, if you create a server, which can serve static files too, npm start is for debugging, it will use much more resources (ram, cpu) and the file size will be bigger (it will load much slower)

    Login or Signup to reply.
  2. You are correct, there is really nothing stopping you from just doing npm start even for production. For development purposes using a Nginx server is kind of overkill. However, the story is different for production environments. There are many reasons to use a "proper" webserver. Here some points:

    1. Performance and obfuscation when doing a production build of the React code: In order to improve performance you should do a npm build to obtain minified and optimized code. This will reduce the file size of your application which will reduce storage, memory, processing and networking resources. The result of npm build is a bunch a static files which can be served from any web server.
      1. This will also obfuscate your code, making it harder for other to see what the code does, making it harder to exploit potential bugs and weaknesses
    2. Obfuscation of infrastructure: Having a front-facing webserver can act as a "protective layer" from the internet, hiding your infrastructure from the outside is good for security purposes.
    3. More performance and security; A battle tested production web server such as Nginx is highly performant and has HTTPS capabilities built-in. A dev server usually won’t have the same abilities, it will perform worse, and it won’t have near the same level of security.
    4. Convenience: Handling a production environment can be significantly different from a dev environment. Nginx provides built in logging, you can easily restrict/allow/redirect calls to your server, load balancing, caching, A/B testing and much more. All of which can be very essential in production.

    I guess your course just sets up example cases that are also relevant for people wanting to create production ready systems.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search