`
wbj0110
  • 浏览: 1550218 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

Nginx反向代理+负载均衡

阅读更多

1. 环境

1.1 系统环境
[root@nginx-cache-1-1 nginx]# cat /etc/redhat-release 
CentOS release 5.8 (Final)
[root@nginx-cache-1-1 ~]# uname -r
2.6.18-308.el5
[root@nginx-cache-1-1 ~]# uname -m
x86_64
[root@nginx-cache-1-1 ~]# uname -n
nginx-cache-1-1
1.2 软件需求
软件:
nginx-1.2.1.tar.gz
pcre-8.11.tar.gz
地址:
http://nginx.org/en/download.html
ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/
2. 安装Nginx
2.1 安装pcre
安装命令:
cd /home/start/tools
tar zxf pcre-8.11.tar.gz
cd pcre-8.11
./configure
make && make install
cd ../
安装过程:
[root@nginx-cache-1-1 tools]# tar zxf pcre-8.11.tar.gz
[root@nginx-cache-1-1 tools]# cd pcre-8.11
[root@nginx-cache-1-1 pcre-8.11]# ./configure
[root@nginx-cache-1-1 pcre-8.11]# make && make install
2.2 安装Nginx
1)安装命令:
useradd -M -s /sbin/nologin www
tar zxf nginx-1.2.1.tar.gz
cd nginx-1.2.1
./configure \
--user=www \
--group=www  \
--prefix=/application/nginx-1.2.1 \
--with-pcre  \
--with-http_stub_status_module \
--with-http_ssl_module \

make && make install
cd ..
ln -s /application/nginx-1.2.1 /application/nginx
echo '/usr/local/lib' >>/etc/ld.so.conf  
不执行这个会报错:nginx: error while loading shared libraries: libpcre.so.1: cannot open shared object file: No such file or directory
tail -1 /etc/ld.so.conf                
ldconfig 
###以下命令可以不操作###
echo 'export PATH=$PATH:/application/nginx/sbin' >>/etc/profile
source /etc/profile
echo ‘start for nginx by start 2012-01-26’ >>/etc/rc.local
echo ‘/application/nginx/sbin/nginx’ >>/etc/rc.local
tail -2 /etc/rc.local
2)安装过程:
[root@nginx-cache-1-1 tools] useradd -M -s /sbin/nologin www  <==添加Nginx系统运行帐户
[root@nginx-cache-1-1 tools] tar zxf nginx-1.2.1.tar.gz  <==解压Nginx
[root@nginx-cache-1-1 tools] cd nginx-1.2.1
[root@nginx-cache-1-1 nginx-1.2.1] ./configure \   <==编译安装
--user=www \
--group=www  \
--prefix=/application/nginx-1.2.1 \
--with-pcre  \
--with-http_stub_status_module \
--with-http_ssl_module 
[root@nginx-cache-1-1 nginx-1.2.1] make && make install 
[root@nginx-cache-1-1 nginx-1.2.1] ln -s /application/nginx-1.2.1 /application/nginx  <==创建软链接方便升级
[root@nginx-cache-1-1 nginx-1.2.1] echo '/usr/local/lib' >>/etc/ld.so.conf
[root@nginx-cache-1-1 nginx-1.2.1] tail -1 /etc/ld.so.conf  <==检查是否添加
/usr/local/lib
[root@nginx-cache-1-1 nginx-1.2.1] ldconfig  
[root@nginx-cache-1-1 nginx-1.2.1] cd ..
[root@nginx-cache-1-1 nginx-1.2.1] echo ‘export PATH=$PATH:/application/nginx/sbin’ >>/etc/profile <==将Nginx命令加入系统全局变量
[root@nginx-cache-1-1 nginx-1.2.1] source /etc/profile  <==使变量生效
[root@nginx-cache-1-1 nginx-1.2.1] echo ‘start for nginx by start 2012-01-26’ >>/etc/rc.local
[root@nginx-cache-1-1 nginx-1.2.1] echo ‘/application/nginx/sbin/nginx’ >>/etc/rc.local
参数说明:
--prefix=/application/nginx-1.2.1  <==指定安装位置
--with-http_stub_status_module  <==启用”server status”(服务状态)页
--with-http_ssl_module  <==启用SSL支持并且能够处理HTTPS请求。需要OpenSSL支持
--with-pcre  <==支持正则表达式

以下两个参数本文没有使用
--with-mail  <==启用IMAP4/POP3/SMTP代理模块
--with-http_realip_module  <==网上都是忽悠人的?
提示:http://wiki.nginx.org/HttpRealIpModule

2.3 启动检查
[root@nginx-cache-1-1 tools]# nginx   <==Nginx命令已经加入到系统全局变量
[root@nginx-cache-1-1 tools]# netstat -lnt
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State      
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      
tcp        0      0 :::22                       :::*                        LISTEN  
3. Nginx负载均衡

提示:Nginx主配置文件使用的是默认提供的,加入了Proxy的参数。

3.1 Proxy参数

client_max_body_size     300m;
client_body_buffer_size  128k;
proxy_connect_timeout    600;
proxy_read_timeout       600;
proxy_send_timeout       600;
proxy_buffer_size        16k;
proxy_buffers            4 32k;
proxy_busy_buffers_size 64k;
参数解释:
#允许客户端请求的最大的单个文件字节数  
client_max_body_size     300m;  
#缓冲区代理缓冲用户端请求的最大字节数 可以理解为先保存到本地再传给用户  
client_body_buffer_size  128k;  
#跟后端服务器连接的超时时间_发起握手等候响应超时时间  
proxy_connect_timeout    600;  
#连接成功后_等候后端服务器响应时间_其实已经进入后端的排队之中等候处理  
proxy_read_timeout       600;  
#后端服务器数据回传时间_就是在规定时间之内后端服务器必须传完所有的数据  
proxy_send_timeout       600;              
#代理请求缓存区_这个缓存区间会保存用户的头信息以供Nginx进行规则处理_一般只要能保存下头信息即可  
proxy_buffer_size        16k;              
#同上 告诉Nginx保存单个用的几个Buffer 最大用多大空间  
proxy_buffers            4 32k;               
#如果系统很忙的时候可以申请更大的proxy_buffers 官方推荐*2   
proxy_busy_buffers_size 64k; 
3.2 upstream模块
3.2.1 语法
官方地址:http://nginx.org/en/docs/http/ngx_http_upstream_module.html
官方提示:upstream模块默认被proxy_pass, fastcgi_pass, and memcached_pass 这三个参数调用
The ngx_http_upstream_module module allows to define groups of servers that can be referenced from the proxy_pass, fastcgi_pass, and memcached_pass directives.
官方示例:
upstream backend {
   server backend1.example.com       weight=5;  <==单独域名。如果不加端口,默认是80端口。weight代表权重,值越大被分配的几率越高;
   server backend2.example.com:8080;  <==域名加端口。转发到后端的指定端口上;
   server unix:/tmp/backend3;  <==指定socket文件(具体用法不祥)
   提示:Server如果接域名,需要内网有DNS服务器,或者在hosts文件做解析。Server后面还可以直接接IP或IP加端口
server 192.168.1.2
server 192.168.1.3:8080
   server backup1.example.com:8080   backup;  <==备份服务器,等上面指定的服务器都不可访问的时候会启用,backup的用法和Haproxy中用法一样;
   server backup2.example.com:8080   backup;
}
3.2.1 Upstream参数
官方原文:
weight=number
sets a weight of the server, by default 1.
设置该服务器的权重,默认值是1.这个数值越大,服务器会被转发更多的请求;
max_fails=number
sets a number of unsuccessful attempts to communicate with the server during a time set by the fail_timeout parameter after which it will be considered down for a period of time also set by the fail_timeout parameter. By default, the number of unsuccessful attempts is set to 1. A value of zero disables accounting of attempts. What is considered to be an unsuccessful attempt is configured by the proxy_next_upstream, fastcgi_next_upstream, and memcached_next_upstream directives. The http_404 state is not considered an unsuccessful attempt.
Nginx 尝试链接后端主机失败次数,这个数值是配合 proxy_next_upstream, fastcgi_next_upstream, and memcached_next_upstream这三个参数来使用的,当Nginx接收后端服务器返回这三个参数定义的状态码的时候,会将这个请求转发给 正常工作的后端服务器,例如404,502,503.Max_fails 默认值是1;
fail_timeout=time
sets
a time during which the specified number of unsuccessful attempts to communicate with the server should happen for the server to be considered down;
and a period of time the server will be considered down.
By default, timeout is set to 10 seconds.
在max_fails定义的失败次数后,距离下次检查的间隔时间,默认是10s;
backup
marks the server as a backup server. It will be passed requests when the primary servers are down.
这标志着这个服务器作为备份服务器,当主服务器全部宕机的时候,才会向他转发请求;
down
marks the server as permanently down; used along with the ip_hash directive.
这标志着服务器永远不可用,这个参数只配合ip_hash使用
示例:
upstream backend {
   server backend1.example.com     weight=5;  <==如果就是单个Server,没必要设置权重
   server 127.0.0.1:8080           max_fails=5 fail_timeout=10s; <==当检测次失败数等于5的时候,间隔10s再检查,这个参数和proxy/fasrcgi/memcached_next_upstream, 相关;
   server unix:/tmp/backend3;
   server backup1.example.com:8080 backup;  <==热备机器设置
}
max_fails=5 fail_timeout=10s
重 新加载nginx配置或WEB主机检测正常后,如果后端出现proxy_next_upstream中定义的错误(502),Nginx会根据 max_fails的值去后端服务器检测,如果max_fails是5 ,他就检测5次,如果5次都是502那么,他就会根据fail_timeout的值,等待10s再去检查,过10s后检查一次,如果还是502,那么继续 等待10s,再去检查,还是只检查一次,如果持续502,在不重新加载nginx配置或web站点没有恢复的情况下,每隔10s都只检测一次。
测试结果见5附录
3.2.2 调度算法
1)轮询(默认)
每个请求按时间顺序注意分配到不同的机器,相当于LVS中rr算法,如果后端服务器宕机(默认情况下只检测80端口,如果后端报502,404,403,503,还是会直接返回给用户),则会跳过该服务器,将请求分配给下一个服务器。
2)weight(权重)
在指定的轮询的基础上加上权重(默认是rr+weight),权重轮询和访问成正比,权重越大,转发的请求也就越多。可以根据服务器的配置和性能指定权重值大小,可以有效解决新旧服务器分配问题。
示例:
后端服务器192.168.1.2配置:E5520*2 CPU,8G内存
后端服务器192.168.1.3配置:Xeon(TM)2.80GHz * 2,4G内存
我希望在有30个请求到达前端时,其中20个请求交给192.168.1.3处理,剩余10个请求交给192.168.1.2处理,就可做如下配置;
upstream engine {
server 192.168.1.2 weight=1;
server 192.168.1.3 weight=2;

3)ip_hash
每个请求按访问的Ip的hash结果分配,当新的请求到达时,先将其客户端ip通过哈希算法哈希出一个值,在随后请求客户端Ip的哈希值只要相同,就会被分配至同一个服务器,该调度算法可以解决session问题,但有时会导致分配不均即,无法保证负载均衡。
提示:必须是最前端的服务器,后端也必须直接接应用服务器
示例:
upstream engine {
ip_hash;
server 192.168.1.2:80;
server 192.168.1.3:8080;
}
4)fair(第三方,NO)
按照后端服务器的响应时间来分配请求,响应时间短的优先分配。
示例:
upstream engine {
server 192.168.1.2;
server 192.168.1.3;
fair;
}
5)usr_hash(第三方,NO)
按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,后端服务器为缓存时比较有效。在upstream中加入hash语句,server语句中不能写入weight等其他的参数,hash_method是使用的hash算法。
upstream engine {
server squid1:3128;
server squid2:3128;
hash $request_uri;
hash_method crc32;
}
3.3 Proxy_pass 指令
3.3.1官方文档:
http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass
3.3.2官方定义:
This module makes it possible to transfer requests to another server.
此模块可以将请求转发到另一台服务器
3.4 Location 指令
Nginx中的location指令是NginxHttpCoreModule中重要指令。location比较简单且常用。
location 指令,是用来对rul进行匹配的,URI即语法中的/uri/,可以是字符串或正则表达式。但是如果是正则表达,必须指定前缀。
3.4.1 基本语法
语法:
location [=|~|~*|^~|@] /uri/ {···}
解释:
[ = ]  精确匹配,如果找到,立即停止搜索,并立即处理请求(优先级最高)
[ ~ ]  区分大小写
[ ^~ ] 之匹配字符串,不匹配正则表达式
[ ~*]  不区分大小写
[ @ ]  指定一个命名的location,一般只用于内部重定向请求
匹配过程
首先对字符串进行匹配查询,最确切的匹配将被使用。然后,正则表达式的匹配查询开始,匹配第一个结果后会停止搜索,如果没有找到正则表达式,将使用字符串的搜索结果,如果字符串和正则都匹配,那么正则优先级较高。

提示:本文没有针对location的匹配顺序,进行测试,总结起来就是“精确匹配优先”。具体怎么个精确匹配还需要读者自己体会。
4. Nginx代理
4.1 L4 负载均衡
4.1.1 Upstraem配置(机器不够就用多端口来演示)
1)权重轮询
upstream engine {
        server 192.168.18.211:80  weight=2;
        server 192.168.18.211:81  weight=3;
        server 192.168.18.211:82  weight=4;
}
2)ip_hash
upstream engine {
        server 192.168.18.211:80;
        server 192.168.18.211:81;
        server 192.168.18.211:82  down;
        ip_hash;
}
4.1.2 Server配置
server {
      listen 80;
      server_name nginx.san.com;
      location / {
      proxy_pass http://engine;
}
}
4.2 L7 负载均衡
4.2.1 根据URI转发
4.2.1.1 Upstream配置
upstream nginx {
        server 192.168.18.211:80;
}
upstream php {
        server 192.168.18.211:81;
}
upstream java {
        server 192.168.18.211:82;
}
4.2.1.2 虚拟主机配置
server {
      listen 80;
      server_name nginx.san.com;
      location /nginx/ {
      proxy_pass http://nginx/;
}
      location /php/ {
      proxy_pass http://php/;
}
      location /java/ {
      proxy_pass http://java/;
}
}
提示:关于结尾这个“/”问题我这没有测试,大家回去有兴趣的可以测试下!
4.2.2 根据扩展名转发(需要正则表达式支持)
4.2.2.1 Upstream配置
upstream nginx {
        server 192.168.18.211:80;
}
upstream php {
        server 192.168.18.211:81;
}
upstream java {
        server 192.168.18.211:82;
}
4.2.2.2 虚拟主机配置
server {
      listen 80;
      server_name nginx.san.com;
      location ~* /(.*\.jpg)$ {
      proxy_pass http://nginx/$1;
}
      location ~* /(.*\.gif)$ {
      proxy_pass http://php/$1;
}
      location ~* /(.*\.png)$ {
      proxy_pass http://java/$1;
}
}
4.3 Nginx SSL
配置文件(没有测试多台证书服务器)
server {
      listen 443 ssl;   <==指定https端口,这个“ssl”必须有不然报错
      server_name sso.eefocus.com;
      #access_log logs/sss-access.log;
      #error_log logs/ssl-error.log;
      ##SSL cert files##
      ssl_certificate  /usr/local/nginx/ssl/ee_com.crt;
      #ssl_certificate_key /usr/local/nginx/ssl/ees_com.key;
      ssl_certificate_key /usr/local/nginx/ssl/ee_com-nopass.key;
      #keepalive_timeout 60;
location / {
        proxy_pass https://192.168.18.61;
        proxy_set_header X-Forwarded-For $remote_addr;
        #proxy_set_header X-Forwarded-Proto https;
}
}
4.4 WEB日志客户端IP记录
4.4.1 X-Forwarded-For 字段
解释(维基百科):
X-Forwarded-For(XFF)是用来识别通过HTTP代理或负载均衡方式连接到Web服务器的客户端最原始的IP地址的HTTP请求头字段。
地址:http://zh.wikipedia.org/wiki/X-Forwarded-For
4.4.2 Apeche
4.4.2.1 Nginx配置
location ~* /(.*\.png)$ {
      proxy_pass http://java/$1;
      proxy_set_header X-Forwarded-For $remote_addr;
}
4.4.2.2 Apache日志格式配置(这里和HAProxy一样)
LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
提示:
1 注意大括号后面还有一个“i”;
2 (自己测试)大括号内“X-Forwarded-For”的值可以随意定义只要和Nginx中X-Forwarded-For 一致,不区分大小写
4.4.3 Nginx(WEB)
4.4.3.1 Nginx(Proxy)
示例:
location ~* /(.*\.jpg)$ {
      proxy_set_header X-Forwarded-For $remote_addr; 
      proxy_pass http://nginx/$1;
}
4.4.3.2 Nginx(WEB)日志格式配置
log_format  main  '$http_x_forwarded_for - $remote_user [$time_local] "$request" '
                     '$status $body_bytes_sent "$http_referer" '
                     '"$http_user_agent" ';
4.5 Nginx健康检查
4.5.1 upstream 配置(详细内容前面已经提到)
upstream php {
        server 10.0.11.82:81 weight=1;
        server 10.0.11.83:80 weight=3 max_fails=5 fail_timeout=10s;
}
4.5.2 server 配置
server {
      listen 80;
      server_name php.san.com;
      location / {
      proxy_pass http://php;
      proxy_set_header X-Forwarded-For $remote_addr;
      proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504 http_404;
}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics