在 CentOS 上配置 Nginx 实现高效负载均衡需要遵循以下步骤:
- 安装 Nginx 和 keepalived 软件包
首先,确保您的 CentOS 系统已更新。然后,安装 Nginx 和 keepalived 软件包:
sudo yum update sudo yum install epel-release sudo yum install nginx keepalived
- 配置 Nginx 负载均衡
编辑 Nginx 配置文件(通常位于 /etc/nginx/nginx.conf 或 /etc/nginx/conf.d/default.conf),并添加以下内容:
http { upstream backend { server backend1.example.com; server backend2.example.com; server backend3.example.com; } server { listen 80; location / { proxy_pass http://backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } }
在此示例中,我们定义了一个名为 “backend” 的服务器组,其中包含三个后端服务器。然后,我们将所有传入的请求代理到该组中的服务器。
- 配置 keepalived
创建一个名为 /etc/keepalived/keepalived.conf 的文件,并添加以下内容:
vrrp_instance VI_1 { state MASTER interface eth0 virtual_router_id 51 priority 100 authentication { auth_type PASS auth_pass 1234 } virtual_ipaddress { 192.168.1.100 } }
在此示例中,我们将 VRRP 实例的状态设置为 MASTER,并将其绑定到 eth0 网络接口。我们还定义了一个虚拟路由器 ID 和优先级。最后,我们配置了简单的密码身份验证和虚拟 IP 地址。
- 启动并启用 Nginx 和 keepalived 服务
启动 Nginx 和 keepalived 服务,并将它们设置为开机启动:
sudo systemctl start nginx sudo systemctl enable nginx sudo systemctl start keepalived sudo systemctl enable keepalived
现在,您已经在 CentOS 上配置了 Nginx 和 keepalived,以实现高效负载均衡。请注意,您需要根据实际情况替换示例配置文件中的服务器名称、IP地址和端口。