Nginx 负载均衡
负载均衡方式说明
1.轮询:所有请求都按照时间顺序分配到不同的服务上,如果服务Down掉,可以自动剔除
upstream webhost {
server localhost:8080 ;
server 192.168.14.133:8080 ;
server 192.168.14.134:8080 ;
}
2.权重:指定每个服务的权重比例,weight和访问比率成正比,通常用于后端服务机器性能不统一,将性能好的分配权重高来发挥服务器最大性能,如下配置后192.168.14.134服务的访问比率会是其他两台服务的二倍。
upstream webhost {
server localhost:8080 weight=1;
server 192.168.14.133:8080 weight=1;
server 192.168.14.134:8080 weight=2;
}
3.iphash:每个请求都根据访问ip的hash结果分配,经过这样的处理,每个访客固定访问一个后端服务,如下配置(ip_hash可以和weight配合使用)
upstream webhost {
ip_hash;
server localhost:8080 weight=1;
server 192.168.14.133:8080 weight=1;
server 192.168.14.134:8080 weight=2;
}
4最少连接:将请求分配到连接数最少的服务上
upstream webhost {
least_conn;
server localhost:8080 weight=1;
server 192.168.14.133:8080 weight=1;
server 192.168.14.134:8080 weight=2;
}
5.根据响应时间分配
upstream webhost {
fair;
server localhost:8080 weight=1;
server 192.168.14.133:8080 weight=1;
server 192.168.14.134:8080 weight=2;
}
nginx 负载均衡各个配置详解
1.在/etc/nginx/conf.d文件下新建default.conf
在default.conf中配置
upstream test_server {
server xxx.xxx.xxx.xx:777 weight=1; //777一次
server xxx.xxx.xxx.xx:9999 weight=2; //9999的两次,
}
server {
listen 888;
server_name xxx.xxx.xxx.xx7;
location / {
proxy_pass http://test_server;
}
}
访问 xxx.xxx.xxx.xx:888的时候,根据权重配置分发的xxx.xxx.xxx.xx:777,xxx.xxx.xxx.xx:9999俩个项目中,
2.在conf.d文件下,新建11.conf,其中配置如下
server {
listen 777; //监听777端口
server_name xxx.xxx.xxx.xx; //服务器ip,或者域名
root "/var/www/11"; //文件根目录
location / {
index index.php index.html error/index.html;
autoindex off;
}
location ~ \.php(.*)$ {
fastcgi_pass unix:/run/php-fpm/www.sock; //根据php-fpm中监听的是否9000或者是/run/php-fpm/www.sock来设置,如果是9000端口,则直接设置9000,否则就是现在这样写法
fastcgi_index index.php;
fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
include fastcgi_params;
}
}
3.在conf.d文件下,新建test2.conf,其中配置如下
server {
listen 9999; //监听99989端口
server_name xxx.xxx.xxx.xx; //服务器ip,或者域名
root "/var/www/test2"; //文件根目录
location / {
index index.php index.html error/index.html;
autoindex off;
}
location ~ \.php(.*)$ {
fastcgi_pass unix:/run/php-fpm/www.sock;//根据php-fpm中监听的是否9000或者是/run/php-fpm/www.sock来设置,如果是9000端口,则直接设置9000,否则就是现在这样写法
fastcgi_index index.php;
fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
include fastcgi_params;
}
}
4.重启nginx
service nginx reload
如果重启不成功,则执行ps -ef|grep nginx 查出来id,kill id,然后service nginx strat;service nginx status;查看nginx是否启动成功
注意点:
1.确保各个端口是否开启,