How to Setup Nginx as Frontend Server for Node.js

NGINX is a powerful and widely used for web server. It also used as frontend proxy server for multiple web application servers runs behind this. This tutorial will help you to setup your Nginx server as fronted proxy server for your Node.js application.

First install the required packages for node.js installation and add PPA of nodejs available on launchpad. Afer that install nodejs with following commands.

$ sudo apt-get install python-software-properties python g++ make $ sudo add-apt-repository ppa:chris-lea/node.js $ sudo apt-get update $ sudo apt-get install nodejs

Now install Nginx web server using apt-get. Nginx is available under default repositories.

$ sudo apt-get install nginx

Now create a test node server app and run it on port 3000 on host 127.0.0.1. To create a node server create file ~/MyApp/myapp.js .

$ cd ~/MyApp/ $ vi myapp.js

and add following content in javascript file.

var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello Worldn'); }).listen(3000, "127.0.0.1"); console.log('Server running at http://127.0.0.1:3000/');

Now use the following command to start nodejs in background

$ node myapp.js &

and access this in browser. You will see result like below screenshot.

After starting a demo server with node.js. Now start configuration with Nginx. Create a virtual host configuration file for your domain under /etc/nginx/conf.d/ directory.

$ sudo vim /etc/nginx/conf.d/example.com.conf

and add the following content.

upstream myapp { server 127.0.0.1:3000; keepalive 8; } # the nginx server instance server { listen 0.0.0.0: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; } }

After making all configuration, let’s restart Nginx web server using following command.

$ sudo /etc/init.d/nginx restart

Now access your server using domain name, you will see the same page shows on http://127.0.0.1:3000/ .


Originally published at tecadmin.net on January 8, 2016.

Like what you read? Give jack.yin a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.