Nginx负载均衡配置场景

负载均衡配置命令
环境准备

PS:需要关闭selinux和防火墙
Web01服务器上配置nginx
[root@web01 ~]# cd /etc/nginx/conf.d/
[root@web01 conf.d]# vim node.conf
server {
listen 80;
server_name node.test.com;
location / {
root /code/node;
index index.html;
}
}
[root@web01 conf.d]# mkdir -p /code/node
[root@web01 conf.d]# echo "web01 ..." > /code/node/index.html
[root@web01 conf.d]# systemctl restart nginx
Web02服务器上配置nginx
[root@web02 ~]# cd /etc/nginx/conf.d/
[root@web02 conf.d]# vim node.conf
server {
listen 80;
server_name node.test.com;
location / {
root /code/node;
index index.html;
}
}
[root@web02 conf.d]# mkdir -p /code/node
[root@web02 conf.d]# echo "web02 ..." > /code/node/index.html
[root@web02 conf.d]# systemctl restart nginx
配置Nginx负载均衡
[root@lb01 ~]# cd /etc/nginx/conf.d/
[root@lb01 conf.d]# vim /etc/nginx/proxy_params
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;
proxy_connect_timeout 30;
proxy_send_timeout 60;
proxy_read_timeout 60;
proxy_buffering on;
proxy_buffer_size 32k;
proxy_buffers 4 128k;
[root@lb01 conf.d]# vim node_proxy.conf
upstream node {
server 192.168.106.20:80;
server 192.168.106.30:80;
}
server {
listen 80;
server_name node.test.com;
location / {
proxy_pass http://node;
include proxy_params;
}
}
[root@lb01 conf.d]# nginx -t
[root@lb01 conf.d]# systemctl restart nginx
打开浏览器访问:http://node.test.com,反复刷新,检测连接的服务器
负载均衡常见典型故障
如果后台服务连接超时,Nginx是本身是有机制的,如果出现一个节点down掉的时候,Nginx会更据
你具体负载均衡的设置,将请求转移到其他的节点上,但是,如果后台服务连接没有down掉,但是返回
错误异常码了如:504、502、500,这个时候你需要加一个负载均衡的设置,如下:
proxy_next_upstream http_500 | http_502 | http_503 | http_504 |http_404;意思是,当其中一台返
回错误码404,500...等错误时,可以分配到下一台服务器程序继续处理,提高平台访问成功率。
[root@lb01 conf.d]# vim node_proxy.conf
server {
listen 80;
server_name node.test.com;
location / {
proxy_pass http://node;
proxy_next_upstream error timeout http_500 http_502 http_503 http_504 http_404;#添加此行
}
}
Nginx负载均衡调度算法

Nginx负载均衡[rr]轮询具体配置
[root@lb01 conf.d]# vim node_proxy.conf
upstream node {
server 192.168.106.20:80;
server 192.168.106.30:80;
}
Nginx负载均衡[wrr]权重轮询具体配置
[root@lb01 conf.d]# vim node_proxy.conf
upstream node {
server 192.168.106.20:80 weight=5;#修改此处
server 192.168.106.30:80;
}
Nginx负载均衡ip_hash
具体配置不能和weight一起使用
[root@lb01 conf.d]# vim node_proxy.conf
upstream node {
ip_hash;#添加此行
server 192.168.106.20:80;
server 192.168.106.30:80;
}
Comments | NOTHING