Nginx反向代理,健康狀態檢測,過載保護及配置文件詳解

簡介
javascript

Nginx("engine x")是一個高性能的HTTP和反向代理 服務器,也是一個IMAP/POP3/SMTP 代理服務器。Nginx 是由Igor Sysoev爲俄羅斯訪問量第二的Rambler.ru站點開發的,第一個公開版本0.1.0發佈於2004年10月4日。其將源代碼以類BSD許可證的形式發佈,因它的穩定性、佔有內存少,併發能力強、豐富的功能集、示例配置文件和低系統資源的消耗而聞名php


1、Nginx的主配置文件詳解(nginx.conf)css

user nobody nobody; #運行用戶與組html

worker_processes 6; #啓動進程,一般設置與CPU數相同java

worder_cpu_affinity 4; #明確指定使用哪些CPU 如使用一、3核心: 1000 0010node

worker_rlimit_nofile 51200; #設置最大系統鏈接數nginx

worker_priority 1; #指定調用CPU優先級;取值範圍(-20~20)git

#error_log logs/error.log; github

#error_log logs/error.log notice; #錯誤日誌及日誌級別;日誌級別有:(debug|info|notice|warn|error|crit|alert|emerg)web

#error_log logs/error.log info;

#pid logs/nginx.pid; #PID文件路徑

lock_file logs/nginx.lock; #鎖文件路徑

events { #事件模塊

use epoll; #指定事件驅動模型;(kqueue|rtsig|epoll|select|poll|eventport)

worker_connections 51200; #定義鏈接數限制;當超過1024時,須使用"ulimit -n"來解除系統鏈接限制

}

http { #設置HTTP服務器模塊

include mime.types; #設置MIME類型

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; #指定Nginx是否調用sedfile函數

#autoindex on; #開啓索引功能,適合下載服務器,默認關閉

#tcp_nopush on; #防止網絡阻塞

#tcp_nodelay on; #防止網絡阻塞

#keepalive_timeout 0;

keepalive_timeout 65; #鏈接超時時間,單位秒

server_names_hash_bucket_size 128; #服務器名字Hash表大小

large_client_header_buffers 4 32k; #設定請求緩存大小

client_header_buffer_size 2k; #客戶端請求頭部緩衝區大小

client_body_buffer_size 512k; #客戶端請求主休緩衝區大小

client_header_timeout 60; #客戶端請求頭部超時時間

client_max_body_size 8M; #設置經過Nginx上傳的文件大小

proxy_connect_timeout 20; #代理鏈接超時時間

proxy_send_timeout 60; #代理髮送超時時間

proxy_read_timeout 20; #代理接收超時時間

proxy_buffer_size 16k; #代理服務器保存用戶頭信息的緩衝區大小

proxy_buffers 4 64k; #存放後臺服務器緩衝區數量與大小

proxy_busy_buffers_size 128k; #高負荷下緩衝大小

proxy_temp_file_write_size 128k; #設置緩存文件夾大小

proxy_temp_path /usr/cache_one; #設置緩存文件夾位置

######指定緩衝區的路徑、存儲方式及大小

proxy_cache_path /usr/proxy_cache_path levels=1:2 keys_zone=cache_one:200m inactive=1d max_size=30g;

gzip on; #開啓Gzip壓縮功能

gzip_min_length 1k; #最小壓縮文件大小

gzip_buffers 4 16k; #壓縮緩存區

gzip_http_version 1.1; #壓縮版本

gzip_proxied off; #在代理中是否啓用壓縮功能

gzip_comp_level 5; #壓縮級別;默認爲1,取值範圍(1-9)

######壓縮文件類型

gzip_types text/plain application/x-javascript text/css application/xml application/javascript;

gzip_vary on;

upstream allen { #定義負載均衡配置,必須定義在"server"以外

ip_hash; #基於客戶端IP地址完成請求的分發,能夠實現同一個客戶端的請求發送到同一臺服務器;有三種調度算法:輪詢(round-robin)、ip哈希(ip_hash)和最少鏈接(least_conn)

server 172.16.14.2 weight=1;#定義一個後端服務器;weight:權重 max_fails:最大失敗鏈接次數,失敗鏈接超時時間由fail_timeout設置 fail_timeout:等待請求目標服務器發送響應時長 backup:全部服務器都故障時才啓用此服務器 down:手動記錄此服務器不在作任何處理請求

server 172.16.14.3 weight=1;

}

server { #定義一個虛擬主機,能夠定義多個

listen 80; #監聽端口

server_name www.allen.com; #定義主機名稱

#charset koi8-r; #設置字符集

#access_log logs/host.access.log main;

location / { #能夠定義多個,也能夠嵌套

root /web; #設置網站文件存放目錄

index index.php index.html index.htm; #設置默認訪問主頁

}

location /status {

stub_status on; #開啓Nginx狀態監測

access_log off; #關閉日誌訪問

}

location ~ \.php$ { #定義以".php"結尾的文件

root /web; #定義php服務器網站存放目錄

fastcgi_pass 172.16.14.2:9000; #定義fastcgi服務器地址及端口

fastcgi_index index.php; #定義默認訪問主頁

fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;

include fastcgi_params; #定義fastcgi訪問文件

}

#location ~ .*\.(gif|jep|jpeg|png|bmp|swf|js|css|js|)$ {

# proxy_cache cache_one; #設置緩存區

# proxy_cache_valid 200 304 12h; #設置緩存時間

# proxy_cache_valid 301 302 1m;

# proxy_cache_valid any 1m;

# proxy_set_header Host $host; #設置發送到代理服務器請求頭部添加額外信息

# proxy_set_header X-Real-IP $remote_addr;

# proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

# proxy_pass http://allen;

#}

#location / {

# if ($request_method == 「PUT」) { #若是客戶請求動做爲"PUT"就轉到定義的地址

# proxy_pass http://www.allen.com:8080;

# }

# if ($request_uri ~ "\.(jpg|gif|jpeg|png)$") { #若是客戶端請求"uri"有已經定義的文件結尾的文件就轉到定義好的地址而後跳出

# proxy_pass http://p_w_picpathservers;

# break;

# }

#if ($http_user_agent ~ MSIE) { #若是客戶端請求使用的瀏覽器是IE,無論請求地址是什麼都轉到"/msie/"下面並跳出

#rewrite ^(.*)$ /msie/$1 break;

註釋:

·last - 完成重寫指令,以後搜索相應的URI或location。

·break - 完成重寫指令。

·redirect - 返回302臨時重定向,若是替換字段用http://開頭則被使用。

·permanent - 返回301永久重定向

#}

#}

#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; #定義以".php"結尾的所有轉到指定的地址

#}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000

#

# 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 { #定義一個HTTPS服務器

# listen 443;

# server_name localhost;

# ssl on;

# ssl_certificate cert.pem; #私鑰文件

# ssl_certificate_key cert.key; #頒發的證書

# ssl_session_timeout 5m; #會話超時時間

# ssl_protocols SSLv2 SSLv3 TLSv1; #SSL協議版本

# ssl_ciphers HIGH:!aNULL:!MD5;

# ssl_prefer_server_ciphers on;

# location / {

# root html;

# index index.html index.htm;

# }

#}

}

if語句

語法:if (condition) { ... }

默認值:none

使用字段:server, location

判斷一個條件,若是條件成立,則後面的大括號內的語句將執行,相關配置從上級繼承。

能夠在判斷語句中指定下列值:

·一個變量的名稱;不成立的值爲:空字符傳""或者一些用「0」開始的字符串。

·一個使用=或者!=運算符的比較語句。

·使用符號~*和~模式匹配的正則表達式:

URL重寫模塊(Rewrite)

·~爲區分大小寫的匹配。

·~*不區分大小寫的匹配(allen匹配Allen)。

·!~和!~*意爲「不匹配的」。

·使用-f和!-f檢查一個文件是否存在。

·使用-d和!-d檢查一個目錄是否存在。

·使用-e和!-e檢查一個文件,目錄或者軟連接是否存在。

·使用-x和!-x檢查一個文件是否爲可執行文件。

正則表達式的一部分能夠用圓括號,方便以後按照順序用$1-$9來引用。

示例配置:

if ($http_cookie ~* "id=([^;] +)(?:;|$)" ) {
set $id $1;
}
if ($request_method = POST ) {
return 405;
}
if (!-f $request_filename) {
break;
proxy_pass http://127.0.0.1;
}
if ($slow) {
limit_rate 10k;
}
if ($invalid_referer) {
return 403;
}
if ($args ^~ post=140){
rewrite ^ http://example.com/ permanent;
}

<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>


Nginx負載均衡配置

下面使用一個案例來介紹Nginx如何配置負載均衡:

153336759.gif

註釋: 這裏爲方便作實驗就使用一個網段

Nginx服務器作負載均衡調度器,這個拓撲圖中只作了一臺調度器,也就是單點故障,這樣會成會整個系統的瓶頸,這裏就不作高可用了,固然後續會介紹高可用的實現

兩臺WEB服務器就使用"Apahce"來實現,這裏使用rpm包安裝方式;而後提供一個測試頁面

一、編譯安裝Nginx

######安裝Nginx依賴環境
[root@nginx ~]# yum -y groupinstall "Development tools" "Server Platform Development"
[root@nginx ~]# yum -y install pcre-devel
=====================================================
######添加Nginx運行用戶
[root@nginx ~]# useradd -r nginx
[root@nginx ~]# tar xf nginx-1.4.2.tar.gz
[root@nginx ~]# cd nginx-1.4.2
######編譯安裝Nginx
[root@nginx nginx-1.4.2]# ./configure \
>   --prefix=/usr \                      #Nginx安裝目錄
>   --sbin-path=/usr/sbin/nginx \        #nginx執行程序安裝路徑
>   --conf-path=/etc/nginx/nginx.conf \  #Nginx主配置文件存放路徑
>   --error-log-path=/var/log/nginx/error.log \   #日誌文件存放路徑
>   --http-log-path=/var/log/nginx/access.log \
>   --pid-path=/var/run/nginx/nginx.pid  \        #PID文件存放路徑
>   --lock-path=/var/lock/nginx.lock \            #鎖文件存放路徑
>   --user=nginx \                                #指定運行Nginx用戶
>   --group=nginx \                               #指定運行Nginx組
>   --with-http_ssl_module \                      #開啓SSL加密模塊
>   --with-http_flv_module \                      #支持flv流媒體模塊
>   --with-http_stub_status_module \              #開啓狀態檢測模塊
>   --with-http_gzip_static_module \              #開啓gzip靜態壓縮模塊
>   --http-client-body-temp-path=/var/tmp/nginx/client/ \ #客戶端請求的緩存目錄
>   --http-proxy-temp-path=/var/tmp/nginx/proxy/ \        #代理緩存目錄
>   --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ \       #fcgi緩存目錄
>   --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi \         #uwsgi緩存目錄
>   --http-scgi-temp-path=/var/tmp/nginx/scgi \           #scgi緩存目錄
>   --with-pcre                                           #啓動正則表達式
[root@nginx nginx-1.4.2]# make && make install

二、爲Nginx提供Sysv服務腳本

#!/bin/sh
# nginx - this script starts and stops the nginx daemon
# chkconfig:   - 85 15
# description:  Nginx is an HTTP(S) server, HTTP(S) reverse \
#               proxy and IMAP/POP3 proxy server
# processname: nginx
# config:      /etc/nginx/nginx.conf
# config:      /etc/sysconfig/nginx
# pidfile:     /var/run/nginx.pid
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0
nginx="/usr/sbin/nginx"
prog=$(basename $nginx)
NGINX_CONF_FILE="/etc/nginx/nginx.conf"
[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx
lockfile=/var/lock/subsys/nginx
make_dirs() {
   # make required directories
   user=`nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
   options=`$nginx -V 2>&1 | grep 'configure arguments:'`
   for opt in $options; do
       if [ `echo $opt | grep '.*-temp-path'` ]; then
           value=`echo $opt | cut -d "=" -f 2`
           if [ ! -d "$value" ]; then
               # echo "creating" $value
               mkdir -p $value && chown -R $user $value
           fi
       fi
   done
}
start() {
    [ -x $nginx ] || exit 5
    [ -f $NGINX_CONF_FILE ] || exit 6
    make_dirs
    echo -n $"Starting $prog: "
    daemon $nginx -c $NGINX_CONF_FILE
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}
stop() {
    echo -n $"Stopping $prog: "
    killproc $prog -QUIT
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}
restart() {
    configtest || return $?
    stop
    sleep 1
    start
}
reload() {
    configtest || return $?
    echo -n $"Reloading $prog: "
    killproc $nginx -HUP
    RETVAL=$?
    echo
}
force_reload() {
    restart
}
configtest() {
  $nginx -t -c $NGINX_CONF_FILE
}
rh_status() {
    status $prog
}
rh_status_q() {
    rh_status >/dev/null 2>&1
}
case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart|configtest)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
            ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
        exit 2
esac

三、將Nginx加入到系統服務並啓動

[root@nginx ~]# chmod +x /etc/rc.d/init.d/nginx
[root@nginx ~]# chkconfig --add nginx
[root@nginx ~]# service nginx start
正在啓動 nginx:                                           [肯定]

四、查看Nginx進程並訪問測試

[root@nginx ~]# ps aux|grep nginx
root      2557  0.0  0.2  44444   816 ?        Ss   15:20   0:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
nginx     2558  0.7  0.5  44852  1508 ?        S    15:20   0:00 nginx: worker process

161803289.gif

五、在WEB1服務器上安裝Httpd並啓動

[root@web1 ~]# yum -y install httpd
[root@web1 ~]# service httpd start

六、爲WEB1服務器提供一個測試頁面並作訪問測試

[root@web1 ~]# echo 'web1 172.16.14.2' > /var/www/html/index.html

162315232.gif

七、在WEB2服務器上面安裝Httpd並啓動

[root@web2 ~]# yum -y install httpd
[root@web2 ~]# service httpd start

八、爲WEB2服務器提供一個測試頁面並作訪問測試

[root@web2 ~]# echo 'web1 172.16.14.3' > /var/www/html/index.html

164046303.gif


配置Nginx實現均衡

一、修改主配置文件

#user  nobody;
worker_processes  4;
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
worker_rlimit_nofile    51200;
#pid        logs/nginx.pid;
events {
    use epoll;
    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;
    server_names_hash_bucket_size 128; 
    client_header_buffer_size 32k;
    large_client_header_buffers 4 32k;
    client_max_body_size 300m;
    client_body_buffer_size 512k;
    sendfile        on;
    tcp_nopush      on;
    keepalive_timeout  65;
    proxy_connect_timeout   20;
    proxy_send_timeout      60;
    proxy_read_timeout      20;
    proxy_buffer_size       16k;
    proxy_buffers           4 64k;
    proxy_busy_buffers_size 128k;
    proxy_temp_file_write_size 128k;
    gzip  on;
    gzip_min_length  1k;
    gzip_buffers     4 16k;
    gzip_http_version 1.1;
    gzip_comp_level 5;
    gzip_vary on;
    upstream allen {
        server 172.16.14.2;
        server 172.16.14.3;
     }
    server {
        listen       80;
        server_name  localhost;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location / {
            proxy_pass  http://allen;
            index  index.html index.htm;
        }
        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

二、測試Nginx主配置文件語法,並從新加載

[root@nginx ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@nginx ~]# service nginx reload

三、訪問Nginx主機驗證是否實現負載均衡,有時可能須要多刷新幾下

171759347.gif

171802603.gif


Nginx實現後端健康狀態檢測

一、修改Nginx主配置文件以下

    upstream allen {
        server 172.16.14.2      backup;
        server 172.16.14.3      max_fails=3 fail_timeout=2s;
    }
註釋:
backup:做爲備份服務器,當全部服務器都中止了服務,此時backup備份機會啓用
max_fails:請求超時後,最大檢測後端服務器次數
fail_timeout:超時時間;默認爲10s

二、從新加載配置文件

[root@nginx ~]# service nginx reload

三、測試是否訪問的頁面爲WEB2服務器的

195854519.gif

四、中止WEB2服務器的Httpd服務,驗證是否請求的爲WEB1服務器內容

[root@web2 ~]# service httpd stop
Stopping httpd:                                            [  OK  ]

200039480.gif

五、把WEB2服務器Httpd服務啓動,此時請求到的內容爲WEB2服務器;這裏就不在測試了


給Nginx添加第三方模塊實現過載保護

一、下載擴展補丁包,解壓並打補丁 點此下載

[root@nginx ~]# unzip nginx-http-sysguard-master.zip
[root@nginx ~]# cd nginx-1.4.2
[root@nginx nginx-1.4.2]# patch -p1 < ../nginx-http-sysguard-master/nginx_sysguard_1.3.9.patch

二、從新編譯安裝Nginx

[root@nginx nginx-1.4.2]# ./configure \
>   --prefix=/usr \
>   --sbin-path=/usr/sbin/nginx \
>   --conf-path=/etc/nginx/nginx.conf \
>   --error-log-path=/var/log/nginx/error.log \
>   --http-log-path=/var/log/nginx/access.log \
>   --pid-path=/var/run/nginx/nginx.pid  \
>   --lock-path=/var/lock/nginx.lock \
>   --user=nginx \
>   --group=nginx \
>   --with-http_ssl_module \
>   --with-http_flv_module \
>   --with-http_stub_status_module \
>   --with-http_gzip_static_module \
>   --http-client-body-temp-path=/var/tmp/nginx/client/ \
>   --http-proxy-temp-path=/var/tmp/nginx/proxy/ \
>   --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ \
>   --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi \
>   --http-scgi-temp-path=/var/tmp/nginx/scgi \
>   --with-pcre \
>   --add-module=/root/nginx-http-sysguard-master/
[root@nginx nginx-1.4.2]# make && make install

三、修改Nginx配置文件添加過載保護;這裏說明下爲了測試方便,把CPU負載調的比較低

[root@nginx nginx-1.4.2]# cd /etc/nginx/
[root@nginx nginx]# vim nginx.conf
######在"server"模塊中添加以下內容
        sysguard on;    #開啓過載保護功能
        sysguard_load load=0.3 action=/loadlimit;    #cpu負載超過0.3就保護,"action"過載保護動做
        #sysguard_mem swapratio=20% action=/swaplimit; #交換分區過載保
        #sysguard_mem free=100M action=/freelimit;     #內存過載保護
        location /loadlimit {
            return 503;    #系統過載返回503
        }
註釋:因爲新添加了功能須要重啓Nginx服務
[root@nginx nginx]# service nginx restart

四、安裝"htop"工具,監測負載

[root@nginx ~]# yum -y install htop
[root@nginx ~]# htop

183123647.gif

五、在另外一臺主機使用apache自帶的壓力測試工具ab作壓測;在壓測前先訪問一下是否正常如:

183423261.gif

######作壓力測試
[root@web1 ~]# ab -n 50000 -c 1000 http://172.16.14.1/index.html

六、查看Nginx服務器的負載情況

183747988.gif

七、測試訪問Nginx服務器是否能正常訪問

184029799.gif

Nginx負載均衡、後端服務器健康狀態檢測及如何添加第三方擴展模塊到此結束,感謝各位博友的關注!!!!!!

相關文章
相關標籤/搜索