Nginx is an event-based web server, while Apache is a process-based server. Nginx is probably the two best-known asynchronous servers and Apache is undoubtedly the best known process-based server. The main advantage of the asynchronous approach is scalability. In a process-based server, each simultaneous connection requires a thread which incurs significant overhead. An asynchronous server, on the other hand, is event-driven and handles requests in a single (or at least, very few) threads due to which under heavier loads apache usually consume far too much RAM which significantly degrades performance. On the other hand nginx is faster at serving static files and consumes much less memory for concurrent requests because it is event-based and it doesn’t need to spawn new processes or threads for each request, so its memory usage is very low.
Features of nginx
- Static file serving.
- SSL/TLS support.
- Virtual hosts.
- Reverse proxying.
- Load balancing.
- Access controls.
- URL rewriting.
We can use nginx as HTTP server and load balancer in front of tomcat. Below is the detail steps how we can use nginx with tomcat for load balancing using sticky session and serving static content.
Step 1: Install depending libraries.
apt-get install libpcre3 libpcre3-dev zlibc zlib1g zlib1g-dev
apt-get install libssl-dev
Step 2: Download source release for nginx package.
Step 3: By default nginx provide IP base load balancing but some time we require session based load balancing instead of IP based load balancing. For session based load balancing we need to install nginx sticky session plugin. For this, download source release for sticky session package. If you don’t want to use nginx load balancing through sticky session you can ignore this step.
Step 4: Extract nginx-1.4.1.tar.gz and nginx-sticky-module-1.1.tar.gz.
tar -xvhf nginx-sticky-module-1.1.tar.gz
tar -xvhf nginx-1.4.1.tar.gz
Step 5: Move nginx-sticky-module-1.1 directory inside nginx-1.4.1 directory and execute below command.
./configure –add-module=nginx-sticky-module-1.1 –with-http_ssl_module
Step 6: Now go to nginx-1.4.1 directory and make build with below command.
2. Configure nginx
Now nginx is installed on your machine on path /usr/local/nginx/. Now we will configure nginx. We will call /usr/local/nginx/ as nginx home directory. nginx.conf is the main configuration file of nginx. We will create our own configuration file and include in nginx.conf
Step 1: Make directory conf.d in nginx home directory . Now we have to include this folder in nginx.conf. Edit nginx.conf and add below line:
Your nginx.conf file should look like this: