实验准备:
准备三台虚拟机
克隆rhel9 名为haproxy vmset.sh eth0 172.25.254.100 haproxy.jingwen.org
克隆rhel9 名为webserver1 vmset.sh eth0 172.25.254.10 webserver1.jingwen.org
克隆rhel9 名为webserver2 vmset.sh eth0 172.25.254.20 webserver2.jingwen.org
#20.10
[root@webserver1 ~]# dnf install nginx -y
[root@webserver1 ~]# echo webserver1 -172.25.254.10 > /usr/share/nginx/html/index.html
[root@webserver1 ~]# systemctl enable --now nginx
[root@webserver2 ~]# dnf install nginx -y
[root@webserver2 ~]# echo webserver2 - 172.25.254.20 > /usr/share/nginx/html/index.html
[root@webserver2 ~]# systemctl enable --now nginx
#测试实验环境能不能通
[root@haproxy ~]# curl 172.25.254.10
webserver1 -172.25.254.10
[root@haproxy ~]# curl 172.25.254.20
webserver2 - 172.25.254.20
[root@haproxy ~]# dnf install haproxy -y
#更改缩进等
[root@haproxy ~]# vi ~/.vimrc
set ts=4 ai sw=4
#使用哪个后端 use_backend
[root@haproxy ~]# vi /etc/haproxy/haproxy.cfg
# main frontend which proxys to the backends
#---------------------------------------------------------------------
frontend webcluster
bind *:80
mode http
use_backend webcluster-host
backend webcluster-host
balance roundrobin
server web1 172.25.254.10:80
server web2 172.25.254.20:80
#第二种写法
listen webcluster-host
bind *:80
mode http
balance roundrobin
server web1 172.25.254.10:80
server web2 172.25.254.20:80
[root@haproxy ~]# systemctl restart haproxy
[root@haproxy ~]# systemctl start haproxy.service
#测试是否能访问
[root@haproxy ~]# curl 172.25.254.100
webserver1 -172.25.254.10
[root@haproxy ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
#有问题看日志
[root@haproxy ~]# > /var/log/messages
[root@haproxy ~]# systemctl restart haproxy.service
[root@haproxy ~]# cat /var/log/messages
#但是当我们停止ngnix后,访问会变为20
[root@haproxy ~]# systemctl stop nginx.service
#修改为100000
[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
# Global settings
#---------------------------------------------------------------------
global
# to have these messages end up in /var/log/haproxy.log you will
# need to:
#
# 1) configure syslog to accept network log events. This is done
# by adding the '-r' option to the SYSLOGD_OPTIONS in
# /etc/sysconfig/syslog
#
# 2) configure local2 events to go to the /var/log/haproxy.log
# file. A line like the following can be added to
# /etc/sysconfig/syslog
#
# local2.* /var/log/haproxy.log
#
log 127.0.0.1 local2
chroot /var/lib/haproxy
pidfile /var/run/haproxy.pid
maxconn 100000
user haproxy
group haproxy
daemon
[root@haproxy ~]# pstree -p | grep haproxy
|-haproxy(1654)---haproxy(1656)-+-{haproxy}(1657)
| |-{haproxy}(1658)
| `-{haproxy}(1659)
#重启后发生了变化
[root@haproxy ~]# systemctl restart haproxy.service
[root@haproxy ~]# pstree -p | grep haproxy
|-haproxy(1694)---haproxy(1696)-+-{haproxy}(1697)
| |-{haproxy}(1698)
| `-{haproxy}(1699)
在/etc/haproxy/haproxy.cfg 中添加了
#必须创建日志
[root@haproxy ~]# cat /etc/rsyslog.conf
# Save boot messages also to boot.log
local7.* /var/log/boot.log
local2.* /var/log/haproxy.log