How to Setup Nginx as Frontend Server for Node.js

How to Setup Nginx as Frontend Server for Node.js

Nginx is an incredibly powerful web server frequently used as a reverse proxy. By placing Nginx in front of your Node.js application, you can handle security, load balancing, and static file caching more efficiently than using Node.js alone.

In this guide, we will walk through the process of setting up Nginx as a frontend proxy server for a Node.js application running on Ubuntu.

Step 1: Install Node.js

First, ensure your system is updated and install the necessary dependencies. You can add the NodeSource PPA to get the latest stable version of Node.js.

sudo apt-get update
sudo apt-get install python-software-properties python g++ make
sudo apt-get install nodejs

Step 2: Install Nginx

Next, install the Nginx web server using the default package manager:

sudo apt-get install nginx

Step 3: Create a Test Node.js Server

To verify the proxy works, create a simple “Hello World” application. Create a directory and a file named myapp.js.

mkdir ~/MyApp && cd ~/MyApp
nano myapp.js

Add the following code to myapp.js:

var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World via Nginx Reverse Proxy\n');
}).listen(3000, "127.0.0.1");

console.log('Server running at http://127.0.0.1:3000/');

Run your app in the background:

node myapp.js &

Step 4: Configure Nginx as a Reverse Proxy

Now, configure Nginx to route traffic from port 80 (HTTP) to your Node.js app running on port 3000. Create a new configuration file for your domain:

sudo nano /etc/nginx/conf.d/example.com.conf

Add the following configuration:

upstream myapp {
    server 127.0.0.1:3000;
    keepalive 8;
}

server {
    listen 80;
    server_name example.com www.example.com;

    access_log /var/log/nginx/example.com.log;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;

        proxy_pass http://myapp/;
        proxy_redirect off;
    }
}

Step 5: Restart Nginx and Verify

Test your Nginx configuration for syntax errors and restart the service:

sudo nginx -t
sudo systemctl restart nginx

Now, visit your domain or server IP in a browser. You should see the “Hello World” message served through Nginx!


Discover more from TCMHACK

Subscribe to get the latest posts sent to your email.

Tags:

Leave a Reply

Discover more from TCMHACK

Subscribe now to keep reading and get access to the full archive.

Continue reading