Skip to content

How to serve Node js app with NGINX reverse Proxy

Last updated on November 21, 2022

In this post, I will show you How we can use the NGINX web server as a Reverse Proxy server. NGINX is very powerful. It can handle at least 10,000 simultaneous client connections on a single server with its event-driven architecture.

In simple words NGINX is

– Open source and it’s free to use.
– High-Performance HTTP Server.
– Can be used as Reverse Proxy
– Can be used as IMAP/POP3 Proxy Server.
– Simple and easy to configure.
– High Performance, stable, and low resource consumption.
– Event-Driven Asynchronous architecture.

To start off, we need to install and configure Nginx which will serve the front end of our site.

Installing Nginx on Ubuntu 16.04

$ sudo apt-get update && sudo apt-get upgrade -y
$ sudo apt-get install nginx -y

Once it has been installed, you can check the status of Nginx and start it using the following commands:-

$ sudo systemctl status nginx    # To check the status of nginx
$ sudo systemctl start nginx    # To start nginx

Make sure that Nginx will run on system startup by using the command below:-

sudo systemctl enable nginx

Nginx should be up and running, now we need to configure NGINX as a Proxy for the Node JS application.

$ sudo vi /etc/nginx/sites-available/default

Now update your server block the same as below shown. It should look something like this:-

server {
    listen 80;

    server_name your_domain.com;

    location / {
        proxy_pass http://private_ip_address:8080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

Replace your_domain.com with your ec2 domain name and private_ip_address with the private ip address associated ( which you obtained previously)

Save and quit the file using wq vim command.

Test the configuration of Nginx using the command below:-

$ sudo nginx -t

Then reload Nginx if OK is displayed.

$ sudo /etc/init.d/nginx reload

Create your first Nodejs application using Expressjs
Create your project directory and install Expressjs

$ mkdir myapp
$ cd myapp
$ npm install express

Create a simple express application

$ vi app.js

and make it listen at port 8080 and private_ip_address. It should look something like this:-

var express = require('express');
var app = express();

app.get('/', function(req, res){
  res.send("Hello World!");
});

app.listen(8080, 'private_ip_address');

Replace private_ip_address with your private IP address.

Run your app by using the command below:-

$ node app.js

Now open your browser and browse your domain. It should display Hello World!

Nginx is now set up as a reverse proxy for your application.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments