Nginx as a web server and a load balancer

Nginx as a web server and a load balancer

Hello, friends today I will be talking about Nginx, this might not be your first time hearing about nginx, or you might have always been confused about its uses because people talk about it a lot. Don't fret I'm here to talk about its two major uses in this article.

Firstly, what is Nginx? Nginx is a tool that serves as either an HTTP server, a reverse proxy, a load balancer, a mail proxy, or a TCP/UDP proxy server. You might be confused with the terms listed above but it's really no big deal. Let me break them down into bits.

A reverse proxy is a server that hides the identity of the main server a client sends a request. It can be used in cases of deployment, increase in security, and reliability.

A load balancer is used to distribute network traffic coming in from one server to other servers, nginx is a good use for load balancing.

A mail proxy is a machine or server that helps provide services such as web-based emails via IMAP and virus scanning for incoming mails before it hits the main mailing server as shown below

nginximage.jpeg

Now that we have gained a little insight into what nginx is it's time to talk about how nginx can be used as a web server and a load balancer. Nginx can be used as a web server by simply running nginx.

Let me walk you through a simple installation process on nginx and running nginx.

sudo install nginx

Run this command in your terminal to install nginx.

systemctl start nginx

This will start nginx on your machine, and if you head on to localhost:8000 you should see a welcome nginx homepage.

That is how you set up a web server using nginx.

Using nginx as a load balancer is very easy and efficient. Take for example we have our website on our localhost running on port 8000 and we want to route all traffic coming into that webserver to other servers so as to reduce the traffic on our site's server, all we have to do is add our other servers to our configuration file. It is located at /etc/nginx, you would see your nginx.conf file in that directory

http { 
     upstream siteloadbalancer {
           server 127.0.0.1:2222;
           server 127.0.0.1:3333;
           server 127.0.0.1:4444;
     }
     server {
             listen 8000;
             location / {
                   proxy_pass http://siteloadbalancer/;
             }      
     }
}

What the code above does basically is re-route all the requests going to your main server's homepage to the server IPs listed in the upstream backend in sequential order.

There you have it. Now you know how to use nginx as a web server and also as a load balancer. Stay tuned for more important and exciting articles.