With the help of EC2 Instance we will create a Load Balancer using the Nginx Web Server. we will use three instances for checking the traffic if the Load Balancer is working correctly or not. For data output we are using the ip of each instance in html page and different background colour of html page By which, we are able to find each instance with different colour.
ssh -i "your key" ubuntu@(your publicip).compute-1.amazonaws.com
sudo apt update
It will download and installs the most recent packages, replacing any earlier versions that were already on your system.
Now we have to install nginx webserver to create a Load balancer.to install nginx webserver type-
sudo apt install nginx -y
To check if the nginx server is working correctly copy paste the instance public ip and paste it on your browser.. if its working correctly you can see the default nginx page..
Now we have to delete or remove a file named as default
to configure nginx..
which is available at /etc/nginx/sites-enabled/
..to remove that file type-
rm -rf /etc/nginx/sites-enabled/default
Now we have to create a file using .conf
...You can name it like anything you want. i am using here kitty.conf
as my file name.
sudo vim /etc/nginx/conf.d/kitty.conf
Now we have to paste the script which is given below
upstream backend {
server 13.233.40.230; # type the public IP of the first instance you created
server 13.127.42.35; # type the public IP of the second instance you created
}
server {
listen 80;
server_name 13.127.90.230; # type the public IP of your Nginx instance
location / {
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_pass http://backend;
}
}
Create 2 instances using ubuntu AMI.
Now scroll down and you will see an Advanced details
option click on it and scroll down , you will see a userdata
with box. type these commands inside the box -
#!/bin/bash
apt update
apt install apache2 -y
systemctl start apache2
Launch the instance.
SSH both instances and type-
echo "<h1>heya its $(hostname)"<h1/> > /var/www/html/index.html
Now go back to the instance where you installed nginx and go to that file kitty.conf
..
First, we have to change the Nginx server ip address which is named as servername
in the script with our public ip address.
Now we have to copy paste the public ip of two instances which we are going to use and check it for our customised load balancer.
Copy paste the public ip of two instances named after server
in the script..
Restart ngnix
sudo systemctl restart ngnix
Now again copy the nginx instance public-ip and paste it on your browser, you can see whenever you refresh the page you will get the diffrent ip which means our custom load balancer is working Perfectly!!!!