在 Ubuntu 上用 Apache 配置负载均衡,通常是通过 Apache 的 mod_proxy + mod_proxy_balancer 模块来实现的。下面我给你一个从零开始的完整示例。
sudo apt update
sudo apt install apache2 -y
sudo a2enmod proxy
sudo a2enmod proxy_http
sudo a2enmod proxy_balancer
sudo a2enmod lbmethod_byrequests
sudo a2enmod headers
常用调度算法模块:
lbmethod_byrequests:轮询(默认)lbmethod_bybusyness:按繁忙度lbmethod_bytraffic:按流量
重启 Apache:
sudo systemctl restart apache2
sudo nano /etc/apache2/sites-available/loadbalancer.conf
<VirtualHost *:80>
ServerName example.com
# 负载均衡集群
<Proxy "balancer://mycluster">
BalancerMember "http://192.168.1.101:8080"
BalancerMember "http://192.168.1.102:8080"
# 负载均衡算法
ProxySet lbmethod=byrequests
</Proxy>
# 反向代理
ProxyPreserveHost On
ProxyPass "/" "balancer://mycluster/"
ProxyPassReverse "/" "balancer://mycluster/"
# 可选:状态页面
<Location "/balancer-manager">
SetHandler balancer-manager
Require local
</Location>
</VirtualHost>
sudo a2ensite loadbalancer.conf
sudo a2dissite 000-default.conf # 可选
sudo systemctl reload apache2
curl http://localhost
多次访问,应在两台后端之间切换。
访问状态页(仅本地):
http://服务器IP/balancer-manager
BalancerMember "http://192.168.1.101:8080" loadfactor=3
BalancerMember "http://192.168.1.102:8080" loadfactor=1
→ 101 接收 3 倍流量
ProxySet stickysession=JSESSIONID
或:
Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; path=/"
<Proxy "balancer://mycluster">
BalancerMember "http://192.168.1.101:8080" route=node1
BalancerMember "http://192.168.1.102:8080" route=node2
</Proxy>
BalancerMember "https://192.168.1.101:8443"
sudo apache2ctl configtest
sudo journalctl -u apache2
如果你愿意,我可以帮你:
你现在是哪种后端服务?