nginx负载均衡篇(二)

来源:互联网 发布:域名注册的网站名称 编辑:程序博客网 时间:2024/05/02 14:47

需要模块:ngx_http_upstream_module +  ngx_http_proxy_module    或者   ngx_http_upstream_module +  ngx_http_fastcgi_module 

小知识:upstream 只能应用于http上下文,而proxy_pass可以应用于location,if in locationlimit_except上下文


先尝试基于http协议的反向代理:


vim  /etc/nginx/nginx.conf, 在http{}中添加如下配置:



    server {
        listen 80;
        server_name www.a.com;
        root /usr/share/nginx;


   location / {
        proxy_pass http://myapps/;            这里myapps后面必须要有 /
   }


    }
    upstream myapps{
       server 172.16.52.59   weight=1 max_fails=2 fail_timeout=4s;
       server 172.16.52.60   weight=1 max_fails=2 fail_timeout=4s;

        server 172.16.52.60   weight=1 max_fails=2 fail_timeout=4s   backup;     备用的sorry server
       #ip_hash;
       #health_check  interval=3s fails_number=2;


   }

测试:浏览器中输入www.a.com

说明:172.16.52.59和172.16.52.60这两台主机配置的是httpd服务,因此这里不必要一定要和前端的反向代理服务器配置一样的服务,即完全和服务无关,但是和端口有关。。。

调度算法: 

       1.ip_hash  :基于源地址hash,如果来自于同一个ip的请求,将定向到同一台服务器

      2.

其它:还没有介绍健康检查的配置,但是nginx的session会话保持有三种方式:

       1.基于ip,即会话的内容,一些headers

       2.基于cluster,只适用于小范围的主机,将缓存同步到其它节点主机,缺点是同步的数据量过大或者说同步频繁会消耗大量的带宽,因此只适用于局域网内数量少的主机。

       3.基于共享存储,有点,即使节点挂了也没有关系,因为缓存保留在专门的恭喜那个存储里面了,缺点是如果不同节点同时往共享存储里面写的话会存在导致共享存储里面的数据损坏,这是致命的。。。。


  • 实现动静分离
server {
listen 80;
server_name node31.huahualin
#rewrite   ^/?  /index.php  break;   把默认页面定向至index.php
#rewrite   /index.php   /   break;   把默认页面定向至根
        location ~* \.(gif|jpg|jpeg)$ {
                root /data/web/nginx3/;
rewrite ^/img/(.*)$ /images/$1 redirect;           重定向
}

      location / {
proxy_pass http://httpd/;                静态页面
}
location ~ \.php$ {
root /data/web/nginx3/php;
fastcgi_pass unix:/var/run/php-fpm.sock;                   动态页面
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /$fastcgi_script_name;      把uri映射为本地的资源路径的文件映射
include fastcgi_params;
}
error_page 404 /404.html;

valid_referers none blocked server_names example.*  *.example.com www.example.org/galeries/ ~\.google\.;
if ($invalid_referer) {
return 403;
}
}

upstream httpd {              定义后端主机
#least_conn;
ip_hash;
server 192.168.1.2:80 weight=2 ;
server 192.168.1.4:80 weight=1;
}

  • 缓存fastcgi
 mkdir /var/cache/fastcgi -pv      创建缓存目录
 chown nginx. /var/cache/fastcgi/ -R   修改缓存属主,确保有写权限

vim  nginx.conf

http  {
fastcgi_cache_path  /var/cache/fastcgi  levels=2:2 keys_zone=fcache:16m inactive=5m  max_size=1g;     只能定义在http上下文


    server {
listen 80;
server_name node31.huahualin.com;
root /data/web/nginx;
        
location ~ \.php$ {
root /data/web/nginx3/php;
fastcgi_pass unix:/var/run/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /$fastcgi_script_name;
include fastcgi_params;
fastcgi_cache  fcache;     调用缓存
fastcgi_cache_key $request_uri;
#fastcgi_cache_methods GET;
#fastcgi_cache_min_uses 2;     缓存至少使用次数
fastcgi_cache_valid 200 302 10m;
fastcgi_cache_valid 404 1m;
}

}

}


测试:  ab -n 5000 -c 500 http://node31.huahualin.com/index.php/


fastcgi_cache_path path  [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size];
定义缓存:缓存空间等;

可应用的上下文 :http 
缓存机制:
元数据:内存,即为keys_zone;
数据:磁盘,即为path; 

levels=#[:#[:#]]
levels=2:1

keys_zone=name:size
name: cache的标识符;
size:元数据cache大小;

max_size:缓存空间上限;




注意:调用缓存时,至少应该指定三个参数
fastcgi_cache
fastcgi_cache_key
fastcgi_cache_valid 


  • proxy_pass反代,只能应用于location中
如果是uri代理,带不带/很关键
如果是正则匹配,后面绝对不能带uri,即不能加/
如果上面的uri又被rewrite了,后面绝对不能带uri

(1) proxy_pass URL;
应用上下文:location, if in location, limit_except

proxy_pass后面的路径不带uri时,其会将location的uri传递给后端的主机;下面的示例会将/uri/传递给backend服务器;
location  /uri/ {
proxy_pass http://hostname;
}

proxy_pass后面的路径是一个uri时,其会将location的uri替换为后端主机自己的uri;
location  /uri/ {
proxy_pass http://hostname/new_uri/;
}

如果location定义其uri时使用的正则表达式模式匹配,则proxy_pass后的路径不能够使用uri;
location  ~*  \.(jpg|gif|jpeg)$  {
proxy_pass  http://HOSTNAME;
}

此处的http://HOSTNAME后面不能有任何uri,哪怕只有/也不可以;

  • 向相应报文添加首部
在server段中添加

add_header Via $server_addr;

调试浏览器F12:就会看到Via首部
  1. Connection:
    keep-alive
  2. Date:
    Sat, 02 Apr 2016 14:53:31 GMT
  3. ETag:
    "1f-52f7974429cdd"
  4. Server:
    nginx/1.8.1
  5. Via:
    192.168.1.3
  • 向后端主机日志添加原始客户端IP地址,参考博客:http://blog.csdn.net/a936676463/article/details/8961504
方法一:
vim nginx.conf
 server {
        listen 80;
        server_name node31.huahualin.com;
        root /data/web/nginx;
        add_header Via $server_addr;
        add_header X-Real-IP $remote_addr; ///将真实IP传递至后端主机 自定义的变量X-Real-IP

在后端主机httpd server的日志格式中添加X-Real-IP

vim /etc/httpd/conf/httpd.conf
   LogFormat "%{X-Real-IP}i %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

测试:
方法二:
vim nginx.conf
 server {
        listen 80;
        server_name node31.huahualin.com;
        root /data/web/nginx;
        add_header Via $server_addr;
        add_header X-Forwaded-For $proxy_add_x_forwarded_for; ///将真实IP传递至后端主机 自定义的变量X-Real-IP

在后端主机httpd server的日志格式中添加X-Real-IP

vim /etc/httpd/conf/httpd.conf
   LogFormat "%{X-Real-IP}
vim nginx.conf
 server {
        listen 80;
        server_name node31.huahualin.com;
        root /data/web/nginx;
        add_header Via $server_addr;
        add_header X-Real-IP $remote_addr; ///将真实IP传递至后端主机 自定义的变量X-Real-IP

在后端主机httpd server的日志格式中添加X-Real-IP

vim /etc/httpd/conf/httpd.conf
   LogFormat "%{X-Forwarded-For }i %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

测试:用浏览器强制刷新,不要用缓存!!后,查看后端主机的日志记录格式

  • 缓存proxy_pass
cat  /etc/nginx/nginx.conf


#user  nobody;
worker_processes  auto;


error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;


#pid        logs/nginx.pid;




events {
    worker_connections  1024;
}




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"';


    access_log  logs/access.log  main;


    sendfile        on;
    #tcp_nopush     on;


    #keepalive_timeout  0;
    keepalive_timeout  65;


    #gzip  on;


    server {
        listen       80;
        server_name  localhost;


        #charset koi8-r;


        #access_log  logs/host.access.log  main;


        location / {
            root   html;
            index  index.html index.htm;
        }


        #error_page  404              /404.html;


        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }


        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}


        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}


        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }




    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;


    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}




    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;


    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;


    #    ssl_session_cache    shared:SSL:1m;
    
#    ssl_session_timeout  5m;


    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;


    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


        gzip on;
gzip_http_version 1.0;
gzip_comp_level 6;
gzip_disable msie6;
gzip_min_length 2;
gzip_types  image/gif image/jpg image/jpeg image/png text/plain text/css text/xml application/json  application/xml application/java-script application/x-javascript;
        
        fastcgi_cache_path  /var/cache/fastcgi  levels=2:2 keys_zone=fcache:16m inactive=5m  max_size=1g;
proxy_cache_path   /var/cache/pcache levels=1:2 keys_zone=pcache:10m max_size=1g;


    server {
listen 80;
server_name node31.huahualin.com;
root /data/web/nginx;
add_header Via $server_addr;
        location ~* \.(gif|jpg|jpeg)$ {
                root /data/web/nginx3/;
rewrite ^/img/(.*)$ /images/$1 redirect;
}
location ~ \.php$ {
root /data/web/nginx3/php;
fastcgi_pass unix:/var/run/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /$fastcgi_script_name;
include fastcgi_params;
fastcgi_cache  fcache;
fastcgi_cache_key $request_uri;
fastcgi_cache_methods GET;
fastcgi_cache_min_uses 2;
fastcgi_cache_valid 200 302 2m;
fastcgi_cache_valid 404 1m;
}
error_page 404 /404.html;


location / {
proxy_pass http://httpd/;
proxy_cache pcache;        如果要关掉缓存  proxy_cache  off;
proxy_cache_key $request_uri;
proxy_cache_valid 200 302  5m;
proxy_cache_valid 404 1m;

# proxy_set_header Host $http_host;
}

valid_referers none blocked server_names example.*  *.example.com www.example.org/galeries/ ~\.google\.;
if ($invalid_referer) {
return 403;
}
}

upstream httpd {
ip_hash;
server 192.168.1.2:80 weight=2 ;
server 192.168.1.4:80 weight=1;
}
   
}


0 0
原创粉丝点击