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.
1. Install Node.js
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
2. Install Nginx
Now install Nginx web server using apt-get. Nginx is available under default repositories.
$ sudo apt-get install nginx
4. Create Test Node Server
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.
4. Configure NGINX
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
5. Verify Setup
Now access your server using domain name, you will see the same page shows on http://127.0.0.1:3000/ .