Search code examples
reactjsdockercontainersdevops

Why do we need nginx to dockerize React apps?


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?


Solution

  • 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.