nginx高性能WEB服务器系列之六--nginx负载均衡配置
注:原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。
nginx的强大之处不必要我细说,当初第一次接触nginx的时候就发现了它的强大之处,并且自我觉得非常有必要出一篇记录nginx的各个功能及坑点。
欢迎大家对nginx感兴趣的朋友们来一起学习与及时提出错误及误点。有问题的可以在评论区@我。
一:nginx负载均衡配置
其实负载均衡的意思很简单明了,网上很多原理一大堆的解释,可能看的似懂非懂。这里本人画了一个简单粗暴的原理图,仅供参考:
解释:其实nginx 作为一个轻量级、高性能的 web server 主要可以干的就两件事情,
第一件事就是直接作为http server(代替apache,对PHP需要FastCGI处理器支持);
第二件事就是作为反向代理服务器实现负载均衡
因为nginx在处理并发方面的优势,现在这个应用非常常见。
当然了Apache的 mod_proxy和mod_cache结合使用也可以实现对多台app server的反向代理和负载均衡,但是在并发处理方面apache还是没有 nginx擅长。
这里介绍一种实践负载均衡+健康检查的方法。
直接vim /usr/local/nginx/conf/nginx.conf 修改upstream 段配置文件:
http { include mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; sendfile on; keepalive_timeout 65; upstream worldcup { server 10.124.25.28:8001; server 10.124.25.29:8001; }
nginx配置文件详解的时候也提到了,注意upstream后面接的关键词,如果需要单台,同端口负载不同请求的时候,需要制定不同upstream,以下提供一个实践实例。
实践示例,仅供参考,不做解释:
worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' sendfile on; keepalive_timeout 65; upstream keep_one { server 192.168.1.1:8080 weight=1 max_fails=2 fail_timeout=30s; server 192.168.1.2:8080 weight=1 max_fails=2 fail_timeout=30s; } upstream keep_two { server 192.168.1.3:8081 weight=1 max_fails=2 fail_timeout=30s; server 192.168.1.4:8081 weight=1 max_fails=2 fail_timeout=30s; } server { listen 80; server_name localhost; location / { root html; index index.html index.htm; } location /one { root html; index index.html index.htm; proxy_pass http://keep_one/; proxy_set_header Host $http_host; proxy_set_header Cookie $http_cookie; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; client_max_body_size 300m; } location /two { root html; index index.html index.htm; proxy_pass http://keep_two/; proxy_set_header Host $http_host; proxy_set_header Cookie $http_cookie; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; client_max_body_size 300m; } } }
提供两个负载接口,同台服务器,同个IP,同个端口。
至此关于nginx最常用的负载均衡已经配置完成,后系列中还会介绍到相对常用的nginx的反向代理与nginx负载均衡的健康检查。