在 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表示按请求数轮询(常用)
重启 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.10:8080"
BalancerMember "http://192.168.1.11:8080"
# 负载均衡策略
ProxySet lbmethod=byrequests
</Proxy>
# 反向代理
ProxyPreserveHost On
ProxyPass "/" "balancer://mycluster/"
ProxyPassReverse "/" "balancer://mycluster/"
# 可选:状态页面
<Location "/balancer-manager">
SetHandler balancer-manager
Require local
</Location>
ErrorLog ${APACHE_LOG_DIR}/lb_error.log
CustomLog ${APACHE_LOG_DIR}/lb_access.log combined
</VirtualHost>
sudo a2ensite loadbalancer.conf
sudo a2dissite 000-default.conf # 可选
sudo systemctl reload apache2
curl http://localhost
多次访问,请求会轮流打到不同后端。
在 ProxySet 中修改:
| 算法 | 说明 |
|---|---|
| byrequests | 轮询(默认) |
| bytraffic | 按流量 |
| bybusyness | 按连接数 |
示例:
ProxySet lbmethod=bytraffic
如果后端需要会话一致性:
<Proxy "balancer://mycluster">
BalancerMember "http://192.168.1.10:8080" route=node1
BalancerMember "http://192.168.1.11:8080" route=node2
ProxySet stickysession=JSESSIONID
</Proxy>
BalancerMember "http://192.168.1.10:8080" status=+H
+H:热备-H:下线在 *:443 的 VirtualHost 中:
sslProxyPass 指向 balancer://mycluster✅ Ubuntu + Apache 负载均衡核心步骤:
balancer://ProxyPass 反向代理如果你愿意,我可以:
你现在的后端是什么服务?