下面以 Apache 2(apache2) 为例,介绍如何配置 负载均衡(反向代理 + 负载均衡),通常使用 mod_proxy、mod_proxy_balancer 和 mod_proxy_http。
在 Debian / Ubuntu 上:
sudo a2enmod proxy
sudo a2enmod proxy_http
sudo a2enmod proxy_balancer
sudo a2enmod lbmethod_byrequests
sudo a2enmod headers
sudo systemctl restart apache2
(CentOS/RHEL 使用 httpd 并修改 httpd.conf)
假设后端有两台应用服务器:
sudo vim /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 ip 192.168.1.0/24
</Location>
ErrorLog ${APACHE_LOG_DIR}/lb_error.log
CustomLog ${APACHE_LOG_DIR}/lb_access.log combined
</VirtualHost>
sudo a2ensite loadbalancer.conf
sudo systemctl restart apache2
访问 http://example.com 即可被分发到后端服务器。
ProxySet lbmethod=byrequests # 轮询(默认)
ProxySet lbmethod=bytraffic # 按流量
ProxySet lbmethod=bybusyness # 按连接数
BalancerMember "http://192.168.1.10:8080" loadfactor=3
BalancerMember "http://192.168.1.11:8080" loadfactor=1
→ 10 号机器处理 3/4 请求
BalancerMember "http://192.168.1.10:8080" status=+H
或:
ProxySet ping=5
ProxySet stickysession=JSESSIONID
<VirtualHost *:443>
SSLEngine on
SSLCertificateFile /path/to/cert.pem
SSLCertificateKeyFile /path/to/key.pem
ProxyPass "/" "balancer://mycluster/"
ProxyPassReverse "/" "balancer://mycluster/"
</VirtualHost>
apachectl -t
curl http://example.com
如果你有 具体场景(如:Tomcat / Node.js / Docker / HTTPS / WebSocket),我可以给你更针对性的配置。