Nginx is pronounced as "Engine x".
Nginx is a open-source HTTP server, reverse proxy and a load balancer.
Download Location: Nginx 1.10.2.zip
Extract the nginx zip file.
Before starting nginx there are sequence of steps to be done.
1. We will consider to work on this with two tomcat's set up. I have launched two tomcat's running on different ports 8081 and 8082. (Make sure to change listen port as well)
2. Let's have a sample war file that is deployed in both tomcats and start them.
Location to download sample war file and nginx configuration: https://github.com/raviteja548/blog-files/tree/master/nginx
3. Nginx config(nginx.conf) file has directives and those which are placed in configuration file are to be in main context.
4. let's create an upstream in http directive as below.
8. Based on nginx configuration we access webapplication using url http://localhost/hello-world/ but nginx internally takes care of routing request to both tomcats i.e sending alternate request to each tomcat since the algorithm used is least connect.
9. Routing to each tomcat can be verfied adding logs.
Below screenshot to show load balancing between configured servers for different requests.
upstream tomcat_servers{ least_conn; server 127.0.0.1:8084; server 127.0.0.1:8085; }You can name upstream as you wish. least_conn is the name of algorithm on which load balancing has to happen. Add servers on which your application is running on. 5. create a server directive as below
server { listen 80; server_name localhost; location / { proxy_pass http://tomcat_servers; proxy_next_upstream error timeout invalid_header http_500; proxy_connect_timeout 2; } }By default listen port is 80. 6. At the end nginx config should look like this.
#user nobody; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events { worker_connections 1024; } http { upstream tomcat_servers{ least_conn; server 127.0.0.1:8084; server 127.0.0.1:8085; } # another virtual host using mix of IP-, name-, and port-based configuration # #server { # listen 8000; # listen somename:8080; # server_name somename alias another.alias; # location / { # root html; # index index.html index.htm; # } #} server { listen 80; server_name localhost; location / { proxy_pass http://tomcat_servers; proxy_next_upstream error timeout invalid_header http_500; proxy_connect_timeout 2; } } }7. Navigate to nginx home directory and start it using command "start nginx"