nginx简单反向代理总结

nginx简单反向代理总结javascript

nginx 实现负载均衡。由于nginx在处理并发方面的优点,如今这个应用很是常见。
nginx 这个轻量级、高性能的 web server 主要能够干两件事情:php

〉直接做为http server(代替apache,对PHP须要FastCGI处理器支持);
〉另一个功能就是做为反向代理服务器实现负载均衡css

如下咱们就来举例说明如何使用 nginx 实现负载均衡。由于nginx在处理并发方面的优点,如今这个应用很是常见。固然了Apache的 mod_proxy和mod_cache结合使用也能够实现对多台app server的反向代理和负载均衡,可是在并发处理方面apache仍是没有 nginx擅长。html

a.环境:centos.5.7 OS, 同时安装nginx(8080)和apache(80)和php-fpm ,nginx用来做为反向代理服务器,放置到一台apache以前,做为用户访问的入口;
nginx仅仅处理静态页面,动态的页面(php请求)通通都交付给后台的两台apache来处理。
也就是说,能够把咱们网站的静态页面或者文件放置到nginx的目录下;动态的页面和数据库访问都保留到后台的apache服务器上。前端


b. 以下介绍两种方法实现server cluster的负载均衡。
咱们假设前端nginx(为127.0.0.1:8080)仅仅包含一个静态页面index.html,里面写this is nginx server
后台的一个apache服务器(分别为localhost:80)也能够两台,一台为index.php(里面测试代码为this is apache server 192.168.10.114;,假若有另外一台根目录仅仅放置一个test.php(里面测试代码为 this is apache server2“;)。java


c.针对不一样请求的负载均衡:node

d. 在最简单地构建反向代理的时候 (nginx仅仅处理静态不处理动态内容,动态内容交给后台的apache server来处理),咱们具体的设置为:在nginx.conf中修改:
复制代码 代码以下:
location ~ \.php$ {
proxy_pass 127.0.0.1:80 ;
}mysql

〉 这样当客户端访问localhost:8080/index.html的时候,前端的nginx会自动进行响应;
〉当用户访问localhost:8080/index.php的时候(这个时候nginx目录下根本就没有该文件),可是经过上面的设置 location ~ \.php$(表示正则表达式匹配以.php结尾的文件,详情参看location是如何定义和匹配的 http://wiki.nginx.org/NginxHttpCoreModule) ,nginx服务器会自动pass给 192.168.10.114的apache服务器了。该服务器下的test.php就会被自动解析,而后将html的结果页面返回给nginx,而后 nginx进行显示(若是nginx使用memcached模块或者squid还能够支持缓存),输出结果为打印server2。linux


1. 先安装好nginx软件和php-fpm软件和apache mysql软件。
#!bin/sh
yum -y install yum-fastermirror.noarch //安装fastermirrornginx

rpm -ivh  rpmforge-release-0.5.2-2.el5.rf.i386.rpm //安装rpmforge源

rpm -ivh  epel-release-5-4.noarch.rpm //安装epel源

cp -rf alt.ru.repo /etc/yum.repos.d //把alt.ru.repo拷贝到/etc/yum.repos.d目录中

yum -y update//更新一下

yum -y install mysql mysql-server //安装mysql数据库

chkconfig mysqld on//设置开机启动

service  mysqld start//设置启动mysqld进程

mysqladmin -u root password 123456//设置mysql密码

yum -y install nginx php-fpm //安装nginx和php-fpm

chkconfig nginx on//设置启动nginx

chkconfig php-fpm on

cp -rf nginx.conf /etc/nginx

cp -rf php-fpm.conf /etc

service nginx start

service php-fpm start

yum -y install php-cli php-mysql php-gd php-imap php-ldap php-odbc php-pear php-xml php-xmlrpc php-snmp php-mcrypt php-mhash php-mbstring php-dba php-bcmath php-tidy php-ncurses php-jpgraph

yum -y install  httpd php

chkconfig httpd on

service httpd start

上面的是最基本的命令安装好nginx和httpd和php-fpm以后就要作准备测试了。

2.修改配置文件
grep -v "#" /etc/nginx/nginx.conf>/etc/nginx.conf.1//去掉不用的#的内容

备份一下cp -rf /etc/nginx/nginx.conf /root

rm -rf /etc/nginx/nginx.conf//删除原来的配置

mv /etc/nginx/nginx.conf.1 nginx.conf//重命名

vi /etc/nginx/nginx.conf//配置文件以下:


user  nginx;
worker_processes  2;

worker_rlimit_nofile 100000;

error_log   /var/log/nginx/error.log;

pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
    use epoll;
}


http {
    include       /etc/nginx/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"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    tcp_nopush      on;
    tcp_nodelay     on;
    server_tokens   off;
    gzip            on;
    gzip_static     on;
    gzip_comp_level 5;
    gzip_min_length 1024;
    keepalive_timeout  65;
    limit_zone   myzone  $binary_remote_addr  10m;

    include /etc/nginx/conf.d/*.conf;

    server {
        limit_conn   myzone  10;
        listen      8080; //这里是修改的端口默认为80
        server_name  _;

 

        location / {
            root   /usr/share/nginx/html;//这里是网站的根目录随便改哈哈!
            index index.php index.html index.htm;//加上index.php
        }

        error_page  404              /404.html;

        location = /404.html {
            root   /usr/share/nginx/html;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/share/nginx/html;
        }

        location ~ \.php$ {
         proxy_pass   http://192.168.10.114:80;
        } //这行井号去掉填上apache 80端口由于在同一台机器上全部就是localhost.

        location ~ \.php$ {
            root          /usr/share/nginx/html;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;

 

    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;

            fastcgi_param  SCRIPT_FILENAME  /usr/share/nginx/html/$fastcgi_script_name;
            include        fastcgi_params;
        }

        location ~ /\.ht {
            deny  all;
        }
    }

}


每一个段落的解释说明以下:

#运行用户
user www-data;   
#启动进程,一般设置成和cpu的数量相等
worker_processes  1;

#全局错误日志及PID文件
error_log  /var/log/nginx/error.log;
pid        /var/run/nginx.pid;

#工做模式及链接数上限
events {
    use   epoll;             #epoll是多路复用IO(I/O Multiplexing)中的一种方式,可是仅用于linux2.6以上内核,能够大大提升nginx的性能
    worker_connections  1024;#单个后台worker process进程的最大并发连接数
    # multi_accept on;
}

#设定http服务器,利用它的反向代理功能提供负载均衡支持
http {
     #设定mime类型,类型由mime.type文件定义
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    #设定日志格式
    access_log    /var/log/nginx/access.log;

    #sendfile 指令指定 nginx 是否调用 sendfile 函数(zero copy 方式)来输出文件,对于普通应用,
    #必须设为 on,若是用来进行下载等应用磁盘IO重负载应用,可设置为 off,以平衡磁盘与网络I/O处理速度,下降系统的uptime.
    sendfile        on;
    #tcp_nopush     on;

    #链接超时时间
    #keepalive_timeout  0;
    keepalive_timeout  65;
    tcp_nodelay        on;
   
    #开启gzip压缩
    gzip  on;
    gzip_disable "MSIE [1-6]\.(?!.*SV1)";

    #设定请求缓冲
    client_header_buffer_size    1k;
    large_client_header_buffers  4 4k;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;

    #设定负载均衡的服务器列表
     upstream mysvr {
    #weigth参数表示权值,权值越高被分配到的概率越大
    #本机上的Squid开启3128端口
    server 192.168.8.1:3128 weight=5;
    server 192.168.8.2:80  weight=1;
    server 192.168.8.3:80  weight=6;
    }


   server {
    #侦听80端口
        listen       80;
        #定义使用www.xx.com访问
        server_name  www.xx.com;

        #设定本虚拟主机的访问日志
        access_log  logs/www.xx.com.access.log  main;

    #默认请求
    location / {
          root   /root;      #定义服务器的默认网站根目录位置
          index index.php index.html index.htm;   #定义首页索引文件的名称

          fastcgi_pass  www.xx.com;
         fastcgi_param  SCRIPT_FILENAME  $document_root/$fastcgi_script_name;
          include /etc/nginx/fastcgi_params;
        }

    # 定义错误提示页面
    error_page   500 502 503 504 /50x.html; 
        location = /50x.html {
        root   /root;
    }

    #静态文件,nginx本身处理
    location ~ ^/(p_w_picpaths|javascript|js|css|flash|media|static)/ {
        root /var/www/virtual/htdocs;
        #过时30天,静态文件不怎么更新,过时能够设大一点,若是频繁更新,则能够设置得小一点。
        expires 30d;
    }
    #PHP 脚本请求所有转发到 FastCGI处理. 使用FastCGI默认配置.
    location ~ \.php$ {
        root /root;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /home/www/www$fastcgi_script_name;
        include fastcgi_params;
    }
    #设定查看Nginx状态的地址
    location /NginxStatus {
        stub_status            on;
        access_log              on;
        auth_basic              "NginxStatus";
        auth_basic_user_file  conf/htpasswd;
    }
    #禁止访问 .htxxx 文件
    location ~ /\.ht {
        deny all;
    }
    
     }
}

以上是一些基本的配置,使用Nginx最大的好处就是负载均衡

若是要使用负载均衡的话,能够修改配置http节点以下:

#设定http服务器,利用它的反向代理功能提供负载均衡支持
http {
     #设定mime类型,类型由mime.type文件定义
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    #设定日志格式
    access_log    /var/log/nginx/access.log;

    #省略上文有的一些配置节点

    #。。。。。。。。。。

    #设定负载均衡的服务器列表
     upstream mysvr {
    #weigth参数表示权值,权值越高被分配到的概率越大
    server 192.168.8.1x:3128 weight=5;#本机上的Squid开启3128端口
    server 192.168.8.2x:80  weight=1;
    server 192.168.8.3x:80  weight=6;
    }

   upstream mysvr2 {
    #weigth参数表示权值,权值越高被分配到的概率越大

    server 192.168.8.x:80  weight=1;
    server 192.168.8.x:80  weight=6;
    }

   #第一个虚拟服务器
   server {
    #侦听192.168.8.x的80端口
        listen       80;
        server_name  192.168.8.x;

      #对aspx后缀的进行负载均衡请求
    location ~ .*\.aspx$ {

         root   /root;      #定义服务器的默认网站根目录位置
          index index.php index.html index.htm;   #定义首页索引文件的名称

          proxy_pass  http://mysvr ;#请求转向mysvr 定义的服务器列表

          #如下是一些反向代理的配置可删除.

          proxy_redirect off;

          #后端的Web服务器能够经过X-Forwarded-For获取用户真实IP
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          client_max_body_size 10m;    #容许客户端请求的最大单文件字节数
          client_body_buffer_size 128k;  #缓冲区代理缓冲用户端请求的最大字节数,
          proxy_connect_timeout 90;  #nginx跟后端服务器链接超时时间(代理链接超时)
          proxy_send_timeout 90;        #后端服务器数据回传时间(代理发送超时)
          proxy_read_timeout 90;         #链接成功后,后端服务器响应时间(代理接收超时)
          proxy_buffer_size 4k;             #设置代理服务器(nginx)保存用户头信息的缓冲区大小
          proxy_buffers 4 32k;               #proxy_buffers缓冲区,网页平均在32k如下的话,这样设置
          proxy_busy_buffers_size 64k;    #高负荷下缓冲大小(proxy_buffers*2)
          proxy_temp_file_write_size 64k;  #设定缓存文件夹大小,大于这个值,将从upstream服务器传

       }

     }
}


3.测试
a.[root@zh888 htdocs]# netstat -ntlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name  
tcp        0      0 127.0.0.1:199               0.0.0.0:*                   LISTEN      1636/snmpd         
tcp        0      0 127.0.0.1:9000              0.0.0.0:*                   LISTEN      3197/php-cgi       
tcp        0      0 0.0.0.0:3306                0.0.0.0:*                   LISTEN      1815/mysqld        
tcp        0      0 0.0.0.0:139                 0.0.0.0:*                   LISTEN      1740/smbd          
tcp        0      0 0.0.0.0:111                 0.0.0.0:*                   LISTEN      1612/portmap       
tcp        0      0 0.0.0.0:8080                0.0.0.0:*                   LISTEN      3136/nginx.conf//已经启动nginx 8080端口    
tcp        0      0 192.168.122.1:53            0.0.0.0:*                   LISTEN      1966/dnsmasq       
tcp        0      0 0.0.0.0:445                 0.0.0.0:*                   LISTEN      1740/smbd          
tcp        0      0 :::80                       :::*                        LISTEN      3029/httpd //httpd已经启动为80端口        
tcp        0      0 :::22                       :::*                        LISTEN      1682/sshd      


b.[root@zh888 htdocs]# ls /usr/local/apache/htdocs/
index.php
[root@zh888 htdocs]# ls /usr/share/nginx/html/
index.html
[root@zh888 htdocs]# cat /usr/local/apache/htdocs/index.php
this is apache server 192.168.10.114
[root@zh888 htdocs]# cat /usr/share/nginx/html/index.html
this is nginx server

 

 

 

[root@zh888 htdocs]# /usr/local/apache/bin/ab -c50 -n 50   http://192.168.10.114:8080/index.html //对index.html 50次请求和50次index.html
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 192.168.10.114 (be patient).....done


Server Software:        nginx
Server Hostname:        192.168.10.114
Server Port:            8080

Document Path:          /index.html
Document Length:        21 bytes

Concurrency Level:      50
Time taken for tests:   0.057 seconds
Complete requests:      50
Failed requests:        0
Write errors:           0
Total transferred:      11200 bytes
HTML transferred:       1050 bytes
Requests per second:    875.09 [#/sec] (mean)
Time per request:       57.137 [ms] (mean)
Time per request:       1.143 [ms] (mean, across all concurrent requests)
Transfer rate:          191.43 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0   10   5.7     10      19
Processing:     1   22  12.6     22      43
Waiting:        1   22  12.6     22      43
Total:         20   32   6.9     32      43

Percentage of the requests served within a certain time (ms)
  50%     32
  66%     36
  75%     38
  80%     39
  90%     42
  95%     42
  98%     43
  99%     43
 100%     43 (longest request)
 

apache 处理50次请求,50次index.php

[root@zh888 htdocs]# /usr/local/apache/bin/ab -c50 -n 50 http://192.168.10.114/index.php
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 192.168.10.114 (be patient).....done


Server Software:        Apache/2.2.19
Server Hostname:        192.168.10.114
Server Port:            80

Document Path:          /index.php
Document Length:        37 bytes

Concurrency Level:      50
Time taken for tests:   0.132 seconds
Complete requests:      50
Failed requests:        0
Write errors:           0
Total transferred:      11100 bytes
HTML transferred:       1850 bytes
Requests per second:    378.73 [#/sec] (mean)
Time per request:       132.019 [ms] (mean)
Time per request:       2.640 [ms] (mean, across all concurrent requests)
Transfer rate:          82.11 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0   57  33.9     58     114
Processing:    18   61  25.9     62     105
Waiting:        0   51  30.5     53     103
Total:        105  118   7.9    119     132

Percentage of the requests served within a certain time (ms)
  50%    119
  66%    123
  75%    125
  80%    127
  90%    130
  95%    131
  98%    132
  99%    132
 100%    132 (longest request)
 

nginx反向50次请求50次index.php

[root@zh888 htdocs]# /usr/local/apache/bin/ab -c50 -n 50 http://192.168.10.114:8080/index.php
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 192.168.10.114 (be patient).....done


Server Software:        nginx
Server Hostname:        192.168.10.114
Server Port:            8080

Document Path:          /index.php
Document Length:        162 bytes

Concurrency Level:      50
Time taken for tests:   0.102 seconds
Complete requests:      50
Failed requests:        10
   (Connect: 0, Receive: 0, Length: 10, Exceptions: 0)
Write errors:           0
Non-2xx responses:      40
Total transferred:      14170 bytes
HTML transferred:       6850 bytes
Requests per second:    489.35 [#/sec] (mean)
Time per request:       102.177 [ms] (mean)
Time per request:       2.044 [ms] (mean, across all concurrent requests)
Transfer rate:          135.43 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0   31  17.1     31      59
Processing:    15   31  17.4     25      79
Waiting:        0   24  21.3     19      78
Total:         44   62  10.1     62      82

Percentage of the requests served within a certain time (ms)   50%     62   66%     67   75%     70   80%     71   90%     75   95%     79   98%     82  

相关文章
相关标签/搜索