在 Ubuntu 上使用 Apache2 做负载均衡,通常是通过 Apache 的 mod_proxy + mod_proxy_balancer 模块来实现反向代理和负载均衡。下面我给你一个从零开始、可直接用的方案。
Apache 作为 负载均衡器(前端)
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
重启 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"
BalancerMember "http://192.168.1.103:8080"
# 负载均衡策略
ProxySet lbmethod=byrequests
</Proxy>
# 反向代理
ProxyPass "/" "balancer://mycluster/"
ProxyPassReverse "/" "balancer://mycluster/"
# 可选:会话保持(如需要)
# ProxyPass "/" "balancer://mycluster/" stickysession=JSESSIONID
# 状态页面(可选)
<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 restart apache2
| 策略 | 说明 |
|---|---|
byrequests |
轮询(默认) |
bytraffic |
按流量 |
bybusyness |
按连接数 |
修改方式:
ProxySet lbmethod=bytraffic
BalancerMember "http://192.168.1.101:8080" status=+H
或自动检测:
BalancerMember "http://192.168.1.101:8080" ping=5
如果你需要 HTTPS:
sudo apt install certbot python3-certbot-apache
sudo certbot --apache
Certbot 会自动帮你改 VirtualHost。
curl http://localhost
多次访问,观察请求被分发到不同后端。
✅ 适合:
❌ 不适合:
如果你愿意,我可以:
你现在是 什么业务场景?