Apache 是互联网上最受欢迎的 Web 服务器之一。除了基本的网页服务,它还能通过模块扩展出丰富的功能。其中一个重要用途就是将 Apache 配置成负载均衡器,用于在多个后端服务器之间分配流量,提升网站的性能和稳定性。

apache

什么是负载均衡?

负载均衡是一种将系统或服务器接收到的请求均匀分配到多个节点上的技术。它的目标是优化资源使用、最大化吞吐量、减少响应时间,并防止任意一个服务器过载。在高流量场景下,比如节假日的电商网站,这种技术尤为关键。

通过负载均衡,系统能把来自客户端的请求智能地分发给最空闲或最健康的服务器节点,从而避免单点故障,提高应用的可用性和稳定性。

Apache 负载均衡的优势

  • 支持 L4(传输层)和 L7(应用层)负载均衡
  • 提高系统可扩展性
  • 支持会话保持(Session Persistence)
  • 可在单个实例中进行端口到端口的路由
  • 节省带宽资源
  • 提升用户访问体验
  • 快速部署,节省运维时间
  • 支持拒绝异常请求,提高安全性
  • 多服务器容灾能力强

配置环境说明

在这个配置示例中,我们将使用三台运行 Ubuntu 系统的服务器:

  • web1.example.com:后端服务器1
  • web2.example.com:后端服务器2
  • balancer.example.com:负载均衡器

步骤 1:更新系统并安装 Apache

在三台服务器上执行以下命令,更新系统并安装 Apache:

apt update -y
apt upgrade -y
apt install apache2 -y
systemctl start apache2
systemctl enable apache2

步骤 2:配置两个后端服务器

web1(后端服务器1)

创建示例网页:

nano /var/www/html/web1.html

内容如下:

<title>Apache Web Server1</title>
<h2>This is Apache Web Server 1 Page!</h2>

配置虚拟主机:

nano /etc/apache2/sites-enabled/web1.conf
<VirtualHost *:80>
    ServerName web1.example.com
    DocumentRoot /var/www/html
    DirectoryIndex web1.html
</VirtualHost>

重启 Apache:

systemctl restart apache2

web2(后端服务器2)

创建示例网页:

nano /var/www/html/web2.html

内容如下:

<title>Apache Web Server2</title>
<h2>This is Apache Web Server 2 Page!</h2>

配置虚拟主机:

nano /etc/apache2/sites-enabled/web2.conf
<VirtualHost *:80>
    ServerName web2.example.com
    DocumentRoot /var/www/html
    DirectoryIndex web2.html
</VirtualHost>

重启服务:

systemctl restart apache2

步骤 3:配置负载均衡服务器

balancer.example.com 上启用相关模块:

a2enmod proxy
a2enmod proxy_http
a2enmod proxy_balancer
a2enmod lbmethod_byrequests
systemctl restart apache2

确认模块是否启用:

apachectl -M | grep proxy

配置负载均衡虚拟主机:

nano /etc/apache2/sites-enabled/loadbalancer.conf

内容如下:

<VirtualHost *:80>
    ServerName balancer.example.com
    <Proxy balancer://webserver>
        BalancerMember http://web1.example.com
        BalancerMember http://web2.example.com
        ProxySet stickysession=ROUTEID
    </Proxy>
    ProxyPreserveHost On
    ProxyPass / balancer://webserver/
    ProxyPassReverse / balancer://webserver/
</VirtualHost>

保存后重启 Apache:

systemctl restart apache2

测试负载均衡效果

打开浏览器访问:http://balancer.example.com
第一次刷新页面时,应该会看到来自 web1 的页面。再次刷新几次后,应该能看到 web2 的页面,说明请求已在两个服务器之间轮换分发。

补充说明:负载均衡类型

常见的三种负载均衡方式包括:

  1. DNS 轮询:通过 DNS 将请求轮流指向不同服务器
  2. L3/L4 负载均衡:基于 IP 或 TCP 层进行转发
  3. L7 负载均衡:基于应用层协议(如 HTTP)进行智能分发