HAProxy

HAProxy

Haproxy提供高可用性、负载均衡以及基于TCP和HTTP应用的代理,支持虚拟主机,它是免费、快速并且可靠的一种解决方案。

搭建HAProxy 负载均衡

实验准备

IP Address Hostname
192.168.25.50 haproxy
192.168.25.51 web1-nginx
192.168.25.52 web2-nginx

#安装 HAProxy 负载均衡器
sudo apt update
sudo apt show haproxy
sudo apt install -y haproxy

#查看版本
haproxy -v

#查看是否运行
sudo systemctl status haproxy

#修改配置文件
sudo vim /etc/haproxy/haproxy.cfg

#在文件末尾添加
frontend test
   bind 192.168.25.50:80
   stats uri /haproxy?stats
   default_backend web-servers

backend web-servers
    balance roundrobin
    server web1 192.168.25.51:80
    server web2 192.168.25.52:80

#可选,能够在浏览器中查看 HAProxy 统计信息
listen stats
   bind *:8080
   stats enable
   stats uri /
   stats refresh 5s
   stats realm Haproxy\ Statistics
   stats auth test:root123 #这个账号密码
   
#保存退出
#重启
sudo systemctl restart haproxy

#编辑/etc/hosts 文件
vim /etc/hosts

#定义 haproxy 主服务器和 web 服务器的主机名和 IP 地址

192.168.25.50 haproxy
192.168.25.51 web1
192.168.25.52 web2

#保存退出
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
#在nginx 服务器操作
sudo apt update
sudo apt install -y nginx

# Nginx服务器1(51)执行:
echo "<h1>Nginx Server 1 (192.168.25.51)</h1>" | sudo tee /var/www/html/index.nginx-debian.html
# Nginx服务器2(52)执行:
echo "<h1>Nginx Server 2 (192.168.25.52)</h1>" | sudo tee /var/www/html/index.nginx-debian.html

# 启动Nginx并设置开机自启 (两台nginx机)
sudo systemctl start nginx
sudo systemctl enable nginx

#在两台nginx服务器上 配置 /etc /hosts 文件。

sudo vim /etc/hosts

192.168.25.50 haproxy

#保存退出

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------

#在客户端验证
curl http://192.168.25.50
或
while true; do curl http://192.168.25.50; sleep 1; done

posted @ 2025-09-26 09:50  落无一  阅读(12)  评论(0)    收藏  举报