Should I be using Nginx to serve React in production?

4/12/2020

I'm building an SPA using with React and Node.js on Kubernetes. I have separate services and ingresses for the front-end and back-end services. I've seen people also use Nginx to serve the React build, but I found that doing below works well.

# Dockerfile.production
FROM node:8.7.0-alpine
RUN mkdir -p /usr/app/client
WORKDIR /usr/app/client
COPY package*.json /usr/app/client/
RUN npm install
RUN npm install -g serve
COPY . /usr/app/client
EXPOSE 3000
RUN npm run build
CMD ["serve", "-s", "build", "-l", "3000" ]

Alternatively, I could serve the build with Nginx like the following. This seems like "the right way" to do it, but I'm unsure what the advantage is over using the serve npm package, though it does feel very hacky to me. It seems like everything that could be configured with Nginx to serve the app could also be done in the Ingress, right?

server {
    server_name example.com;
    ...

    location ~ / {
        root /var/www/example.com/static;
        try_files $uri /index.html;
    }
}
-- Diego Balvin
dockerfile
kubernetes
nginx
node.js
reactjs

1 Answer

4/12/2020

Serve is fine. Nginx might use a few bytes less RAM for serving, but that will be cancelled out by carrying around all the extra features you aren't using. We use a similar Serve setup for a lot of our K8s SPAs and it uses between 60 and 100MB of RAM per pod at full load. For a few other apps we have a cut down version of Caddy and it maxes out around 70MB instead so slightly less but there are probably better ways to worry about 30MB of RAM :)

-- coderanger
Source: StackOverflow