Nginx负载均衡策略
一 环境情况:
LB 10.240.35.55
web1 10.240.35.56
web2 10.240.35.57
web3 10.240.35.58
二.负载均衡
LB 配置:
server{ listen 80; server_name www.ceshi.com; location /{ proxy_pass http://ceshi; } } server{ listen 80; server_name bbs.ceshi.com; location /{ proxy_pass http://ceshi; } } server{ listen 80; server_name aaa.ceshi.com; location /{ proxy_pass http://ceshi; } } upstream ceshi { server 10.240.37.56:80; server 10.240.37.57:80; server 10.240.37.58:80; }
web配置:轮训机制
server{ listen 80; server_name www.ceshi.com; location / { root /data/www; index index.html; } } server{ listen 80; server_name bbs.ceshi.com; location / { root /data/bbs; index index.html; } } server{ listen 80; server_name aaa.ceshi.com; location / { root /data/aaa; index index.html; } }
每个目录下有个子的index配置文件
已经实行轮训机制
权重轮训
upstream ceshi { server 10.240.37.56:80 weight=3; server 10.240.37.57:80 weight=2; server 10.240.37.58:80 weight=1; }
发现权重低的分配的次数低
backup 只要前面2个节点没有坏就不会调度到第三台上。
健康检查
定义最大失败数 max_fails=5 定义失败后的重发的间隔时间 fail_timeout=10
ip_hash 当用户A访问到web1的时候,请求完毕后,如果在连接根据用户的IP重新调度到web1.
nginx_http_proxy_module -- proxy_pass
01.根据不同的网站访问不同的地址:
案例:我明显访问的是3个域名,但是返回的东西还是一样的这是为什么呢,因为默认nginx有多个80端口,程序不知道访问哪个80,就选择第一符合80端口的域名。导致成以下这样,怎么解决呢。需要添加一个请求头信息 ,把负载均衡的请求Host改成用户访问HOST
proxy_set_header Host $host:$server_port;
server{ listen 80; server_name www.ceshi.com; location /{ proxy_pass http://ceshi; proxy_set_header Host $host:$server_port; } } server{ listen 80; server_name bbs.ceshi.com; location /{ proxy_pass http://ceshi; proxy_set_header Host $host:$server_port; } } server{ listen 80; server_name aaa.ceshi.com; location /{ proxy_pass http://ceshi; proxy_set_header Host $host:$server_port; } }
02.获取用户真实IP,不用反向代理IP
server{ listen 80; server_name bbs.ceshi.com; location /{ proxy_pass http://ceshi; proxy_set_header Host $host:$server_port; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }
03. 通过负载均衡访问页面会出现错误页面,加上有好配置以后就不会显示错误页面
server{ listen 80; server_name www.ceshi.com; location /{ proxy_pass http://ceshi; proxy_set_header Host $host:$server_port; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_next_upstream http_502 http_503 http_504 http_404 error timeout invalid_header; } }