`

Nginx Configration For node.js

Nginx has become the most important player in web server’s. With very low footprint and easy virtual host configuration, Nginx is becoming more and more popular among Developers and System Admins.

There is a lot of struggle when it comes to configure Nginx with Node.js. A Node.js app can be started on any free port that is not in use and it is a web server in itself. But there are a couple of drawbacks in using Node.js as raw web server. Hence here comes the need for Nginx to act as reverse proxy.

In a typical Nginx + Node.js environment, Nginx is installed to listen to the port 80 to serve http or port 443 to serve https requests and forward the request to the Node.js application on the laters specific port.

Below is a gist for the server block configuration for Nginx that can we use to reverse proxy a Node.js app.

server {
  listen        PUBLIC_IP:80;
  server_name   example.com www.example.com;
   location / {
    proxy_pass      http://PUBLIC_IP:5001;
  root           /home/admin/web/example.com/public_html;
   }
}

Line 2 – 7 in the gist is the main server config block. Line 2 specified the IP address and the port that Nginx should listen to. Line 3 maps your virtual host domain name to the public IP address.

Line 4 – 7 is the most important part. This block configures all the requests coming to Nginx to be forwarded to the Node.js app – which in this case is running on port 5001. The proxy pass is configured on line 5 and line 6 is the path to the folder where the Node.js app resides.

That’s it. Save this config and restart your Nginx and you are ready to roll!

Level: Beginner

Technologies: NodeJS

post by Codincafe