Create an nginx load balancer

I wanted to play with a simple load balancer with powerful implications. A load balancer using nginx as the front end and two apache servers on the backend.

server1 - apache - 192.168.1.89 (CentOS 6)

yum -y install httpd
echo server1 /var/www/html/index.html
lokkit -s http -s https
chkconfig httpd on && service httpd restart

server2 - apache -192.168.1.90 (CentOS 6)

yum -y install httpd
echo server2 /var/www/html/index.html
lokkit -s http -s https
chkconfig httpd on && service httpd restart

load balancer - nginx - 192.168.1.88 (CentOS 6/7)

Add the nginx repository and install nginx (CentOS 6/7)

echo '[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1' > /etc/yum.repos.d/nginx.repo

yum install -y nginx

Apply Firewall Rules (CentOS 6/7)

# CentOS 6
lokkit -s http -s https

# CentOS 7
firewall-cmd --permanent --add-service={http,https} 
firewall-cmd --reload

Backup the default.conf file. (CentOS 6/7)

cp /etc/nginx/conf.d/default.conf{,.original}

Modify the default.conf file.

vi /etc/nginx/conf.d/default.conf

Add to the top the upstream section and under location below the two proxy* lines.

upstream web_backend {
#       ip_hash;
        server 192.168.1.89;
        server 192.168.1.90;
        }

server {
    listen       80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://web_backend;
    }

Or a more automated approach. Not pretty but works.

sed -i.original'/\ \ \ \ \ \ \index/a\ \ \ \ \ \ \ \ \proxy_pass http://web_backend;' /etc/nginx/conf.d/default.conf
sed -i '/\ \ \ \ \ \ \index/a\ \ \ \ \ \ \ \ \proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;' /etc/nginx/conf.d/default.conf

cat > /tmp/default /dev/stdin /etc/nginx/conf.d/default.conf << EOF
upstream web_backend {
        server 192.168.1.89;
        server 192.168.1.90;
        }
		
EOF
/bin/cp /tmp/default /etc/nginx/conf.d/default.conf

Restart nginx.

# CentOS 6
chkconfig nginx on && service nginx start

# CentOS 7
systemctl enable --now nginx

nginx-load-balancer

Using your favorite web-browser, type in http://192.168.1.88 and refresh the page a few times to see the text change from server1 to server2.

Source(s)

  • https://www.nginx.com/resources/admin-guide/reverse-proxy/
  • https://www.nginx.com/resources/wiki/start/topics/tutorials/install/
  • http://think-devops.blogspot.com/2013/03/nginx-crumbs.html
  • https://unix.stackexchange.com/questions/99350/how-to-insert-text-before-the-first-line-of-a-file