Serving Node application in production


When we want to serve our Node app in production and with best performance, we need to minimize our static files (javascript, stylesheets, images,…), setup Nginx for serving those static files/proxying requests to our application server and installing process manager that will keep our application alive in case of crashes.

Minimizing our static files is done with help of tools like Grunt, Gulp, Webpack, depending on which we used for developing application. I highly recommend Webpack despite having a huge learning curve. With Webpack it’s easy to reduce bundle size since it can easily remove dead and duplicated code.

Setting up Nginx goes like this: when we have Nginx installed, open /etc/nginx/sites-available/default, add/change root to folder where we are keeping static files (for example /var/www/yoursite/public) and add those directives:

location / {
    try_files $uri $uri/ @proxy;
}

location @proxy {
    proxy_pass http://localhost:3000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}

Nginx will first try to load a file if exists. If not, it will pass a request to our app which is listening on port 3000. Although this is Node-centric post, those Nginx directives can be applied to application servers written in other languages like Python and Go as long as they are listening on specified port.

Keeping application alive forever can be done with packages like forever and pm2 (more popular of the two).