How To Install and Configure Nginx on Amazon ec2 RHEL and Ubuntu Instances

Nginx is a web server like apache. Not only as web server, it can act as a load balancer, reverse proxy etc. Performance wise, Nginx is considered to be better than apache. Processing request in Nginx is even based as opposed to the spawning new thread model in apache.

In this tutorial, I will explain how to install and configure Nginx on ec2 RHEL and ubuntu instances.

The process for installing & configuring Nginx on RHEL , Centos and Amazon Linux is the same.

Instance Setup

Launch an RHEL/Centos/Ubuntu instance using the management console. While launching the instance , configure the security group to allow traffic from HTTP 80 port & HTTPS 443.

Load balancing using Nginx

You can use Nginx as a load balancer to balance the load between server fleets. Nginx proxies the incoming requests and sends it to the backend servers. To configure Nginx as a load balancer, you have to add two blocks of code to the nginx configuration file.

Step 1: Open nginx.conf file

1

sudo vi/etc/nginx/nginx.conf

Step 2: Add the upstream group under the HTTP section. The upstream group is the group of servers which comes under the load balancer. You can give any user defined name for the group. Here am going to give the name as “web_fleet”.

Note: this configuration should be present in the HTTP section of nginx.conf file.

1

2

3

4

5

upstreamweb_fleet{

server54.136.14.10:80;

server64.156.14.11:80;

server94.176.14.12:80;

}

Step 3: Now you have to set the vhost configuration to receive traffic from a particular domain name and route it to the upstream servers. Add the following lines followed by the upstream block and save the file.

1

2

3

4

5

6

7

server{

listen80;

server_name example-one.com www.example-one.com;

location/{

proxy_pass http://web_fleet;

}

}

Step 4: Restart the Nginx server

1

sudo systemctl restart nginx

Step 5: Now, if you access your nginx server using the DNS, the request will be routed to the backend server fleet present in the upstream block.

Make sure some service is running on the backend servers you mention in the upstream block.

There are many other parameters and setting associated with the load balancing configuration. You can check the official Nginx documentation for more clarification.