Дано три сервера:
1. Балансировщик Haproxy - 192.168.0.25
2. Веб сервер nginx1 - 192.168.0.26
3. Веб сервер nginx2 - 192.168.0.27
Задача:
Настроить простую балансировку нагрузки по принципу Round Robin
Решение:
СЕРВЕР 1 - 192.168.0.25
Настраиваем сервер Балансировщик нагрузки с Haproxy, логинимся под root'ом на хосте 192.168.0.25:
Редактируем файл /etc/hosts и добавляем в него записи о наших веб серверах:
# vi /etc/hosts
192.168.0.26 nginx1.loadbalancer.me nginx1192.168.0.27 nginx2.loadbalancer.me nginx2
Обновляем систему:
# yum -y update
Устанавливаем haproxy:
# yum -y install haproxy
Сохраняем оригинальный конфиг файл:
# cd /etc/haproxy/
# mv haproxy.cfg haproxy.cfg.orig
Создаем и редактируем новый:
# vi haproxy.cfg
#---------------------------------------------------------------------
# Global settings
#---------------------------------------------------------------------
global
log 127.0.0.1 local2 #Log configuration
chroot /var/lib/haproxy
pidfile /var/run/haproxy.pid
maxconn 4000
user haproxy #Haproxy running under user and group "haproxy"
group haproxy
daemon
# turn on stats unix socket
stats socket /var/lib/haproxy/stats
#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------
defaults
mode http
log global
option httplog
option dontlognull
option http-server-close
option forwardfor except 127.0.0.0/8
option redispatch
retries 3
timeout http-request 10s
timeout queue 1m
timeout connect 10s
timeout client 1m
timeout server 1m
timeout http-keep-alive 10s
timeout check 10s
maxconn 3000
#---------------------------------------------------------------------
#HAProxy Monitoring Config
#---------------------------------------------------------------------
listen haproxy3-monitoring *:8080 #Haproxy Monitoring run on port 8080
mode http
option forwardfor
option httpclose
stats enable
stats show-legends
stats refresh 5s
stats uri /stats #URL for HAProxy monitoring
stats realm Haproxy\ Statistics
stats auth admin:admin #User and Password for login to the monitoring dashboard
stats admin if TRUE
default_backend app-main #This is optionally for monitoring backend
#---------------------------------------------------------------------
# FrontEnd Configuration
#---------------------------------------------------------------------
frontend main
bind *:80
option http-server-close
option forwardfor
default_backend app-main
#---------------------------------------------------------------------
# BackEnd roundrobin as balance algorithm
#---------------------------------------------------------------------
backend app-main
balance roundrobin #Balance algorithm
option httpchk HEAD / HTTP/1.1\r\nHost:\ localhost #Check the server application is up and healty - 200 status code
server nginx1 192.168.0.26:80 check #Nginx1
server nginx2 192.168.0.27:80 check #Nginx2
Здесь главное поменять две IP адреса выделенные жирным шрифтом.
Настраиваем syslog сервер (rsyslog):
# vi /etc/rsyslog.conf
Рас коментируем строчки:
$ModLoad imudp$UDPServerRun 514
Далее создаем файл haproxy.conf
# cd /etc/rsyslog.d/
local2.=info /var/log/haproxy-access.log #For Access Loglocal2.notice /var/log/haproxy-info.log #For Service Info - Backend, loadbalancer
Перезапускаем службы:
# systemctl restart rsyslog
# systemctl start haproxy
# systemctl enable haproxy
СЕРВЕР 2/192.168.0.26 и СЕРВЕР 3/192.168.0.27
Здесь действия повторяются двух серверах:
# yum -y install epel-release
# yum -y install nginx
# cd /usr/share/nginx/html/
На втором сервере вводим команду:
# echo "<h1>nginx1.loadbalance.me</h1>" > index.html #For nginx1 server
На третьем сервере вводим команду:
# echo "<h1>nginx2.loadbalance.me</h1>" > index.html #For nginx2 server
Стартуем ngnix:
# systemctl enable nginx
# systemctl start nginx
ПРОВЕРКА
Вводим в браузере адрес балансировщика - 192.168.0.25
И обновляем страницу:
При нажатии F5 (обновить страницу) нас перекидывает с одного веб сервера на другой (round robin)
Также можно посмотреть статистику:
Логин/Пароль - admin/admin
В будущем усложню настройку.
Ссылки:
https://www.howtoforge.com/tutorial/how-to-setup-haproxy-as-load-balancer-for-nginx-on-centos-7/