How to serve NodeJS app using Nginx

JavaScript
2 min read

Reverse proxy a NodeJS-based app using Nginx. This prevents us from directly exposing our NodeJS app and provides multiple options to enhance app performance via Nginx configs.

This post tries to capture the steps that we need to do a basic server block setup in Nginx for a NodeJS-based application.

Prerequisites:

8 easy steps to serve NodeJS app using Nginx:

Remove the default page of welcome to nginx

sudo unlink /etc/nginx/sites-enabled/default

Create a new file for your domain

/etc/nginx/sites-available$ sudo vi domain.name

Create a new server block

server {
   server_name domain.name www.domain.name;

   location / {
       proxy_set_header   X-Forwarded-For $remote_addr;
       proxy_set_header   Host $http_host;
       proxy_pass         "http://127.0.0.1:3000”;
       proxy_http_version 1.1;
       proxy_set_header   Upgrade $http_upgrade;
       proxy_set_header   Connection "upgrade";
   }
}

Save and exit the vi editor

press escape -> :wq -> hit enter

Check the contents of the file created above

cat file.name.used.above

Create a symlink between sites-available and sites-enabled

sudo ln -s /etc/nginx/sites-available/domain.name /etc/nginx/sites-enabled/

Test nginx configuration for any errors

sudo nginx -t

Reload nginx for changes to take effect

sudo systemctl reload nginx

Open your browser and visit your site at the configured domain name. You should see your app if nginx test did not throw any error and your node app is in running state.