Configure node.js application server with nginx

Generally we want to integrate any web application to run as fast as possible.

To make this case viable as much as possible, our solution approach should be in web front end and back end.

For front end there are multiple optimization elements like –

A> Load Balancing

B> Caching

C> Serving Static Resources from server which is different than the application server which is/are serving dynamic requests.

and other optimization parameters

Now this article scope is to show a way to integrate nginx and node.js server to accomplish most the above.

Here is a diagram which is representing nginx with one of its function.

Nginx on top of Application Server

We have integrated our previous node express.js based application with nginx to proxy the request through nginx server.

So, to install nginx in ubuntu, we need simply 2 commands –

 
sudo apt-get update

sudo apt-get -f install nginx

To

start the service – sudo service nginx start

stop the service – sudo service nginx stop

restart the service – sudo service nginx restart

Now when we are having nginx up and running in browser by typing – http://127.0.0.1,

we will have the following configuration code in gist, which we updated in nginx.conf and then reloaded the server.The nginx.conf can be found in /etc/nginx/ folder for default nginx installation in ubuntu 14.04LTS.

Here is the Github gist –


To integrate the node.js application the important parts are discussed below. In the configuration file, here are the important parts –

 
upstream sample {
              // the node.js server is running here 
	      server 127.0.0.1:8080; // The server for which upstream/proxy to be done
	      ...
	    }

Now in the server section, some important line of snippets –

 
server {
	        listen 80; //nginx server should listen to which port
	        listen 443 ssl; // for secured socket layer

	        server_name 127.0.0.1; // name of the server, the dns name can be provided here

                // static files such as images are to be served from the physical file path
                // and not from main application server 
		 location ~ ^/(images/|img) {
          			root /nodeapps/nodeexpress4mongoangular;
				  access_log off;
				  expires max;
			}

		location / {
			  ...
			  proxy_pass         http://sample;
                          // here the proxy is set up with our previous supstream section
			}
	}

After setting this up, we need to reload the nginx server and to be sure about our node server up and running.

In our next articles, we will discuss about nginx load balancing, haproxy load balancing and nginx cache server configuration.

If you find this article helpful, you can connect us in Google+ and Twitter

1 thought on “Configure node.js application server with nginx

Leave a Reply

Your email address will not be published. Required fields are marked *