Nginx 负载均衡

nginx支持http和tcp负载均衡。
http和tcp均可以配置多个server和后端服务器。
http和tcp负载均衡链接是在nginx上,每建立一个链接nginx都会建立链接到后端服务器,nginx只负责中转,相似nginx的反向代理有Squid,Apache,后端直接获取的ip不是客户端的真实地址,能够经过代理设置在header中获取。
tcp负载均衡1.9.0版本后开始支持。
nginx能够配置health_check检测后端服务器是否正常,目前只有商业版本支持。

搭建过程:node

  1. 安装nginx
    apt-get install nginx (1.4.6)
    nginx -s reload #从新加载配置

    1.9.0要手动安装
    sudo apt-get install libpcre3 libpcre3-dev
    sudo apt-get install zlib1g-dev

    wget http://nginx.org/download/nginx-1.9.0.tar.gz
    tar -zxvf nginx-1.9.0.tar.gz
    ./configure --prefix=/etc/nginx --with-stream
     
  2. 配置nginx
    user www-data;
    worker_processes 4;
    pid /run/nginx.pid;

    events {       
        worker_connections 768;       
        # multi_accept on;
    }

    # tcp负载均衡配置
    stream {
        # 可配置多个server
        server {
             listen 1034;
             proxy_pass app;
        }
        upstream app {
             server 192.168.0.3:1034;
             server 192.168.0.4:1034;
         }
    }

    # http负载均衡配置
    http {        
        # 后端服务器     
        upstream frontends {               
            server 127.0.0.1:8078;               
            server 127.0.0.1:8079;               
        }       

        sendfile on;       
        tcp_nopush on;       
        tcp_nodelay on;       
        keepalive_timeout 65;       
        types_hash_max_size 2048;       

        # server_tokens off;       
        # server_names_hash_bucket_size 64;       
        # server_name_in_redirect off;       
        include /etc/nginx/mime.types;       
        default_type application/octet-stream;       

        # access_log /var/log/nginx/access.log;       
        access_log /dev/null;       #关闭access log
        error_log /var/log/nginx/error.log;
     

    gzip on;
    gzip_disable "msie6";

    # 可配置多个server监听多个端口
    server {
        # 监听端口
        listen 8080;

        # Allow file uploads
        client_max_body_size 50M;

        location ^~ /static/ {
            root /var/www;
            if ($query_string) {
                expires max;
            }
        }

        location = /favicon.ico {
            rewrite (.*) /static/favicon.ico;
        }

        location = /robots.txt {
            rewrite (.*) /static/robots.txt;
        }

        location / {
            proxy_pass_header Server;
            proxy_set_header Host $http_host;
            proxy_redirect off;
            proxy_set_header X-forwarded-for $proxy_add_x_forwarded_for; #(1)获取源IP
            proxy_set_header X-Real-IP $remote_addr;  #(2)获取源IP
            proxy_set_header X-Scheme $scheme;
            proxy_pass http://frontends;
        }
    }
    include /etc/nginx/conf.d/*.conf;
    #include /etc/nginx/sites-enabled/*;
}nginx

    nginx默认开启access和error日志,日志处理很差可能会形成十几G甚至更多的日志,
access_log /var/log/nginx/access.log;   改为 access_log /dev/null;
    nginx默认开启80端口,须要手动注释掉 include /etc/nginx/sites-enabled/*;
/dev/null 相似黑洞,扔进去不占空间。后端

相关文章
相关标签/搜索