在LNMP中配置负载均衡器主要通过Nginx实现,步骤如下:
安装Nginx:
sudo apt update && sudo apt install nginx
sudo yum install epel-release && sudo yum install nginx
配置Nginx负载均衡:
编辑配置文件(通常位于/etc/nginx/nginx.conf
或/etc/nginx/conf.d/
):
http {
upstream backend {
server 192.168.1.1:8080; # 后端服务器1(可添加多个)
server 192.168.1.2:8080;
least_conn; # 负载均衡算法(可选:轮询round-robin、IP哈希ip_hash等)
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend; # 转发请求到后端服务器组
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
}
least_conn
:最少连接数(适合长连接场景)。ip_hash
:基于客户端IP的哈希(适合会话保持)。round-robin
(轮询)。重启Nginx:
sudo systemctl restart nginx
验证配置:
curl
测试:curl -I http://example.com
,检查响应头中的X-Real-IP
是否来自不同后端服务器。可选优化:
proxy_next_upstream
指令配置故障转移。ip_hash
算法确保同一用户请求固定到同一服务器。说明:
pm.max_children
等参数)。参考来源: