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 相似黑洞,扔進去不佔空間。後端

相關文章
相關標籤/搜索