1、Nginx负载均衡概述
1.1 应用情况
Nginx做为一个强大的Web服务器软件,具有高性能、高并发性和低内存占用的特点。此外,其也能够提供强大的反向代理功能。俄罗斯大约有超过20%的虚拟主机采用Nginx作为反向代理服务器,在国内也有腾讯、新浪、网易等多家网站在使用Nginx作为反向代理服务器。据Netcraft统计,世界上最繁忙的网站中有11.48%使用Nginx作为其服务器或者代理服务器。基于反向代理的功能,Nginx作为负载均衡主要有以下几点理由:
- 高并发连接
- 内存消耗少
- 配置文件非常简单
- 成本低廉
- 支持Rewrite重写规则
- 内置的健康检查功能
- 节省带宽
- 稳定性高
1.2 性能
Nginx的高并发,官方测试支持5万并发连接。实际生产环境能到2-3万并发连接数。10000个非活跃的HTTP keep-alive 连接仅占用约2.5MB内存。三万并发连接下,10个Nginx进程,消耗内存150M。淘宝tengine团队说测试结果是“24G内存机器上,处理并发请求可达200万”。
2、Nginx负载均衡模块介绍
Nginx实现负载均衡用到了proxy_pass代理模块核心配置, 将客户端请求代理转发至一组upstream虚拟服务池
ngx_http_upstream_module模块
2.1 配置语法
Syntax:upstream name { ... }
Default:—
Context:http
2.2 配置示例
upstream backend {
server backend1.example.com weight=5;
server backend2.example.com:8080;
server unix:/tmp/backend3;
server backup1.example.com:8080 backup;
server backup2.example.com:8080 backup;
}
server {
location / {
proxy_pass http://backend;
}
}
3、负载均衡使用案例
3.1 后端服务器部署
1. 安装nginx服务
[root@Web-Node1 ~]# yum -y install nginx
2. 编辑虚拟主机(由于主机数量限制,此处我使用虚拟主机)
[root@Web-Node1 ~]# cat /etc/nginx/conf.d/LB.conf
server {
listen 8081;
root /soft/code1;
index index.html;
}
server {
listen 8082;
root /soft/code2;
index index.html;
}
server {
listen 8083;
root /soft/code3;
index index.html;
}
3. 准备访问web页面
[root@Web-Node1 ~]# mkdir /soft/{code1,code2,code3} -p
[root@Web-Node1 ~]# echo " <h1> Code1 192.168.1.22:8081 </h1> " >/soft/code1/index.html
[root@Web-Node1 ~]# echo " <h1> Code2 192.168.1.22:8082 </h1> " >/soft/code2/index.html
[root@Web-Node1 ~]# echo " <h1> Code3 192.168.1.22:8083 </h1> " >/soft/code3/index.html
4. 重启nginx服务
[root@Web-Node1 ~]# systemctl start nginx
[root@Web-Node1 ~]# systemctl restart nginx
3.2 前端负载均衡配置
1. 安装nginx服务
[root@LB01-Master ~]# yum -y install nginx
2. 配置nginx反向代理
[root@LB01-Master ~]# cat /etc/nginx/conf.d/proxy.conf
upstream proxy {
server 192.168.1.22:8081;
server 192.168.1.22:8082;
server 192.168.1.22:8083;
}
server {
server_name 192.168.1.20;
listen 80;
location / {
proxy_pass http://proxy;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
3. 重启nginx服务
[root@LB01-Master ~]# systemctl start nginx
[root@LB01-Master ~]# systemctl enable nginx
3.3 客户端测试
[root@Client ~]# curl http://192.168.1.20
<h1> Code1 192.168.1.22:8081 </h1>
[root@Client ~]# curl http://192.168.1.20
<h1> Code2 192.168.1.22:8082 </h1>
[root@Client ~]# curl http://192.168.1.20
<h1> Code3 192.168.1.22:8083 </h1>
此时是轮询状态