輕松實現Nginx HTTP 反向代理+負載均衡

jopen 11年前發布 | 54K 次閱讀 Nginx Web服務器
  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負載均衡</p>

    提示: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;
    }
    }
    </p>

    本文出自 “八一杠一的博客” 博客

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!