天天看點

Nginx中文手冊

Nginx中文手冊

一、 Nginx 基礎知識

二、 Nginx 安裝及調試

三、 Nginx Rewrite

四、 Nginx Redirect

五、 Nginx 目錄自動加斜線:

六、 Nginx Location

七、 Nginx expires

八、 Nginx 防盜鍊

九、 Nginx 通路控制

十、 Nginx日志處理

十一、 Nginx Cache

十二、 Nginx 負載均衡

十三、 Nginx簡單優化

十四、 如何建構高性能的LEMP環境

十五、 Nginx服務監控

十六、 常見問題與錯誤處理.

十七、 相關資源下載下傳

【前言】:

編寫此技術指南在于推廣普及NGINX在國内的使用,更友善的幫助大家了解和掌握NGINX

的一些使用技巧。本指南很多技巧來自于網絡和工作中或網絡上朋友們問我的問題.在此對

網絡上願意分享的朋友們表示感謝和緻意!歡迎大家和我一起豐富本技術指南提出更好的建

議!請朋友們關注: http://www.linuxtone.org 技術分享社群! 互想學習共同進步!

1、簡介

Nginx ("engine x") 是一個高性能的 HTTP 和 反向代理 伺服器,也是一個 IMAP/POP3/SMTP 

代理服

務器。 Nginx 是由 Igor Sysoev 為俄羅斯通路量第二的 Rambler.ru 站點開發的,它已經在該

站點運作超

過兩年半了。Igor 将源代碼以類BSD許可證的形式釋出。盡管還是測試版,但是,Nginx 已經

因為它的穩

定性、豐富的功能集、示例配置檔案和低系統資源的消耗而聞名了。

更多的請見官方wiki: http://wiki.codemongers.com/

2、 Nginx的優點

nginx做為HTTP伺服器,有以下幾項基本特性:

1) 處理靜态檔案,索引檔案以及自動索引;打開檔案描述符緩沖.

2) 無緩存的反向代理加速,簡單的負載均衡和容錯.

3) FastCGI,簡單的負載均衡和容錯.

4) 子產品化的結構。包括gzipping, byte ranges, chunked responses, 以及 SSI-filter等filter。

如果由FastCGI或其它代理伺服器處理單頁中存在的多個SSI,則這項處理可以并行運作,而不

需要互相等待。

5) 支援SSL 和 TLS SNI.

Nginx專為性能優化而開發,性能是其最重要的考量, 實作上非常注重效率 。它支援核心Poll模

型,

能經受高負載的考驗, 有報告表明能支援高達 50,000 個并發連接配接數。

Nginx具有很高的穩定性。其它HTTP伺服器,當遇到通路的峰值,或者有人惡意發起慢速連接配接

時,

也很可能會導緻伺服器實體記憶體耗盡頻繁交換,失去響應,隻能重新開機伺服器。例如目前apache

一旦上到

200個以上程序,web響應速度就明顯非常緩慢了。而Nginx采取了分階段資源配置設定技術,使得

它的CPU與

記憶體占用率非常低。nginx官方表示保持10,000個沒有活動的連接配接,它隻占2.5M記憶體,是以類

似DOS這

樣的攻擊對nginx來說基本上是毫無用處的。就穩定性而言, nginx比lighthttpd更勝一籌。

Nginx支援熱部署。它的啟動特别容易, 并且幾乎可以做到7*24不間斷運作,即使運作數個月

也不

需要重新啟動。你還能夠在不間斷服務的情況下,對軟體版本進行進行更新。

Nginx采用master-slave模型, 能夠充分利用SMP的優勢,且能夠減少工作程序在磁盤I/O的阻

塞延遲。當采用select()/poll()調用時,還可以限制每個程序的連接配接數。

Nginx代碼品質非常高,代碼很規範, 手法成熟, 子產品擴充也很容易。特别值得一提的是強大

的Upstream與Filter鍊。 Upstream為諸如reverse proxy, 與其他伺服器通信子產品的編寫奠定了

很好的

基礎。而Filter鍊最酷的部分就是各個filter不必等待前一個filter執行完畢。它可以把前一個filter

的輸出做為目前filter的輸入,這有點像Unix的管線。這意味着,一個子產品可以開始壓縮從後端

伺服器

發送過來的請求,且可以在子產品接收完後端伺服器的整個請求之前把壓縮流轉向用戶端。

Nginx采用了一些os提供的最新特性如對sendfile (Linux 2.2+),accept-filter (FreeBSD

4.1+),TCP_DEFER_ACCEPT (Linux 2.4+) 的支援,進而大大提高了性能

1、Pcre 安裝

./configure

make && make install

cd ../

2. nginx 編譯安裝

/configure --user=www --group=www --prefix=/usr/local/nginx/ --with-

http_stub_status_module

--with-openssl=/usr/local/openssl

更詳細的子產品定制與安裝請參照官方wiki.

3、Nginx 配置檔案測試:

# /usr/local/nginx/sbin/nginx -t //Debug 配置檔案的關鍵指令需要重點撐握.

2008/12/16 09:08:35 [info] 28412#0: the configuration file /usr/local/nginx/conf/nginx.conf

syntax is ok

was

tested successfully

3、 Nginx 啟動:

# /usr/local/nginx/sbin/nginx

4、 Nginx 配置檔案修改重新加載:

# kill -HUP `cat /usr/local/nginx/logs/nginx.pid `

1. Nginx Rewrite 基本标記(flags)

last - 基本上都用這個Flag。

※相當于Apache裡的[L]标記,表示完成rewrite,不再比對後面的規則

break - 中止Rewirte,不再繼續比對

redirect - 傳回臨時重定向的HTTP狀态302

permanent - 傳回永久重定向的HTTP狀态301

※原有的url支援正則 重寫的url不支援正則

2. 正規表達式比對,其中:

~ 為區分大小寫比對

~* 為不區分大小寫比對

!~ 和 !~* 分别為區分大小寫不比對及不區分大小寫不比對

3. 檔案及目錄比對,其中:

-f 和 !-f 用來判斷是否存在檔案

-d 和 !-d 用來判斷是否存在目錄

-e 和 !-e 用來判斷是否存在檔案或目錄

-x 和 !-x 用來判斷檔案是否可執行

3. Nginx 的一些可用的全局變量,可用做條件判斷:

$args

$content_length

$content_type

$document_root

$document_uri

$host

$http_user_agent

$http_cookie

$limit_rate

$request_body_file

$request_method

$remote_addr

$remote_port

$remote_user

$request_filename

$request_uri

$query_string

$scheme

$server_protocol

$server_addr

$server_name

$server_port

$uri

将所有linuxtone.org與netseek.linuxtone.org域名全部自跳轉到http://www.linuxtone.org

server {

    listen 80;

    server_name linuxtone.org netseek.linuxtone.org;

    index index.html index.php;

    root /data/www/wwwroot;

    if ($host !~ "^www\.linxtone\.org$") {

        rewrite ^(.*) http://www.linuxtone.org$1 redirect;

    }

    .....................

}

if (-d $request_filename){

    rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;

1.基本文法:[和上面rewrite正則比對文法基本一緻]

location [=|~|~*|^~] /uri/ { … }

示例1:

location = / {

    # matches the query / only.

    # 隻比對 / 查詢。

比對任何查詢,因為所有請求都已 / 開頭。但是正規表達式規則和長的塊規則将被優先和查詢

比對

示例2:

location ^~ /images/ {

    # matches any query beginning with /images/ and halts searching,

    # so regular expressions will not be checked.

    # 比對任何以 /images/ 開頭的任何查詢并且停止搜尋。任何正規表達式将不會被測試。

示例3:

location ~* \.(gif|jpg|jpeg)$ {

    # matches any request ending in gif, jpg, or jpeg. However, all

    # requests to the /images/ directory will be handled by

    # 比對任何以 gif、jpg 或 jpeg 結尾的請求。

1.根據檔案類型判斷,添加expires

# Add expires header for static content

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

    if (-f $request_filename) {

        root /data/www/wwwroot/bbs;

        expires 1d;

        break;

2、根據某個目錄判斷,添加expires

# serve static files

location ~ ^/(images|JavaScript|js|css|flash|media|static)/ {

    root /data/www/wwwroot/down;

    expires 30d;

1. 針對不同的檔案類型

#Preventing hot linking of images and other file types

location ~* ^.+\.(gif|jpg|png|swf|flv|rar|zip)$ {

    valid_referers none blocked server_names *.linuxtone.org linuxtone.org http://localhost

baidu.com;

    if ($invalid_referer) {

        rewrite ^/ http://www.linuxtone.org/images/default/logo.gif;

        # return 403;

2. 針對不同的目錄

location /img/ {

    root /data/www/wwwroot/bbs/img/;

    valid_referers none blocked server_names *.linuxtone.org http://localhost baidu.com;

        #return 403;

3. 同實作防盜鍊和expires的方法

    valid_referers none blocked server_names *.linuxtone.org linuxtone.org http://localhost ;

    access_log off;

    root /data/www/wwwroot/bbs;

    expires 1d;

    break;

1. Nginx 身份證驗證

#cd /usr/local/nginx/conf

#mkdir htpasswd

/usr/local/apache2/bin/htpasswd -c /usr/local/nginx/conf/htpasswd/tongji linuxtone

#添加使用者名為linuxtone

New password: (此處輸入你的密碼)

Re-type new password: (再次輸入你的密碼)

Adding password for user

http://count.linuxtone.org/tongji/data/index.html(目錄存在/data/www/wwwroot/tongji/data/

目錄

下)

将下段配置放到虛拟主機目錄,當通路http://count.linuxtone/tongji/即提示要密驗證:

location ~ ^/(tongji)/ {

    root /data/www/wwwroot/count;

    auth_basic "LT-COUNT-TongJi";

    auth_basic_user_file /usr/local/nginx/conf/htpasswd/tongji;

2. Nginx 禁止通路某類型的檔案.

如,Nginx下禁止通路*.txt檔案,配置方法如下.

location ~* \.(txt|doc)$ {

        root /data/www/wwwroot/linuxtone/test;

        #rewrite …..可以重定向到某個URL

方法2:

location ~* \.(txt|doc)${

    root /data/www/wwwroot/linuxtone/test;

    deny all;

執行個體:

禁止通路某個目錄

location ~ ^/(WEB-INF)/ {

3. 使用ngx_http_access_module限制ip通路

location / {

    deny 192.168.1.1;

    allow 192.168.1.0/24;

    allow 10.1.1.0/16;

詳細參見wiki: http://wiki.codemongers.com/NginxHttpAccessModule#allow

4. Nginx 下載下傳限制并發和速率

limit_zone linuxtone $binary_remote_addr 10m;

    server_name down.linuxotne.org;

    index index.html index.htm index.php;

    #Zone limit

    location / {

        limit_conn linuxtone 1;

        limit_rate 20k;

    ..........

隻允許客房端一個線程,每個線程20k.

【注】limit_zone linuxtone $binary_remote_addr 10m; 這個可以定義在主的

5. Nginx 實作Apache一樣目錄清單

    autoindex on;

6. 上檔案大小限制

主配置檔案裡加入如下,具體大小根據你自己的業務做調整。

client_max_body_size 10m;

十、 Nginx 日志處理

1.Nginx 日志切割

#contab -e

59 23 * * * /usr/local/sbin/logcron.sh /dev/null 2>&1

# cat /usr/local/sbin/logcron.sh

#!/bin/bash

log_dir="/data/logs"

time=`date +%Y%m%d`

/bin/mv ${log_dir}/access_linuxtone.org.log 

${log_dir}/access_count.linuxtone.org.$time.logkill -USR1 `cat /var/run/nginx.pid`

更多的日志分析與處理就關注(同時歡迎你參加讨論):http://bbs.linuxtone.org/forum-8-1.html

2.利用AWSTATS分析NGINX日志

設定好Nginx日志格式,仍後利用awstats進行分析.

請參考: http://bbs.linuxtone.org/thread-56-1-1.html

3. Nginx 如何不記錄部分日志

日志太多,每天好幾個G,少記錄一些,下面的配置寫到server{}段中就可以了

location ~ .*\.(js|jpg|JPG|jpeg|JPEG|css|bmp|gif|GIF)$ {

十一、Nginx Cache服務配置

如果需要将檔案緩存到本地,則需要增加如下幾個子參數:

proxy_store on;

proxy_store_access user:rw group:rw all:rw;

proxy_temp_path 緩存目錄;

其中,

proxy_store on 用來啟用緩存到本地的功能,

proxy_temp_path 用來指定緩存在哪個目錄下,如:proxy_temp_path html;

在經過上一步配置之後,雖然檔案被緩存到了本地磁盤上,但每次請求仍會向遠端拉取

檔案,為了避免去遠端拉取檔案,必須修改proxy_pass:

if ( !-e $request_filename) {

    proxy_pass http://mysvr;

即改成有條件地去執行proxy_pass,這個條件就是當請求的檔案在本地的

proxy_temp_path指定的目錄下不存在時,再向後端拉取。

更多更進階的應用可以研究ncache,官方網站: http://code.google.com/p/ncache/

詳細安裝請參照http://bbs.linuxtone.org 應用加速版ncache相關的貼子.

十二、Nginx 負載均衡

1. Nginx 負載均衡基礎知識

nginx的upstream目前支援4種方式的配置設定

1)、輪詢(預設)

每個請求按時間順序逐一配置設定到不同的後端伺服器,如果後端伺服器down掉,能自動剔除。

2)、weight

指定輪詢幾率,weight和通路比率成正比,用于後端伺服器性能不均的情況。

2)、ip_hash

每個請求按通路ip的hash結果配置設定,這樣每個訪客固定通路一個後端伺服器,可以解決session

的問題。

3)、fair(第三方)

按後端伺服器的響應時間來配置設定請求,響應時間短的優先配置設定。

4)、url_hash(第三方)

2. Nginx 負載均衡執行個體1

upstream bbs.linuxtone.org { #定義負載均衡裝置的Ip及裝置狀态

    server 127.0.0.1:9090 down;

     server 127.0.0.1:8080 weight=2;

     server 127.0.0.1:6060;

     server 127.0.0.1:7070 backup;

在需要使用負載均衡的server中增加

proxy_pass http://bbs.linuxtone.org/;

每個裝置的狀态設定為:

a) down 表示單前的server暫時不參與負載

b) weight 預設為1.weight越大,負載的權重就越大。

c) max_fails :允許請求失敗的次數預設為1.當超過最大次數時,傳回proxy_next_upstream 

子產品定義的錯誤

d) fail_timeout:max_fails次失敗後,暫停的時間。

e) backup: 其它所有的非backup機器down或者忙的時候,請求backup機器。是以這台機器

壓力會最輕。

nginx支援同時設定多組的負載均衡,用來給不用的server來使用。

client_body_in_file_only 設定為On 可以講client post過來的資料記錄到檔案中用來做debug

client_body_temp_path 設定記錄檔案的目錄 可以設定最多3層目錄

location 對URL進行比對.可以進行重定向或者進行新的代理 負載均衡

3. Nginx 負載均衡執行個體 2

按通路url的hash結果來配置設定請求,使每個url定向到同一個後端伺服器,後端伺服器為緩

存時比較有效,也可以用作提高Squid緩存命中率.

簡單的負載均等執行個體:

#vi nginx.conf //nginx主配置檔案核心配置

.........

#loadblance my.linuxtone.org

upstream my.linuxtone.org {

    ip_hash;

    server 127.0.0.1:8080;

    server 192.168.169.136:8080;

    server 219.101.75.138:8080;

    server 192.168.169.117;

    server 192.168.169.118;

    server 192.168.169.119;

include vhosts/linuxtone_lb.conf;

# vi proxy.conf

proxy_redirect off;

proxy_set_header Host $host;

proxy_set_header X-Real-IP $remote_addr;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

client_max_body_size 50m;

client_body_buffer_size 256k;

proxy_connect_timeout 30;

proxy_send_timeout 30;

proxy_read_timeout 60;

proxy_buffer_size 4k;

proxy_buffers 4 32k;

proxy_busy_buffers_size 64k;

proxy_temp_file_write_size 64k;

proxy_next_upstream error timeout invalid_header http_500 http_503 http_404;

proxy_max_temp_file_size 128m;

proxy_store_access user:rw group:rw all:r;

#nginx cache

#client_body_temp_path /data/nginx_cache/client_body 1 2;

proxy_temp_path /data/nginx_cache/proxy_temp 1 2;

#vi linuxtone_lb.conf

    server_name my.linuxtone.org;

    index index.php;

    root /data/www/wwwroot/mylinuxtone;

    if (-f $request_filename/index.php) {

        rewrite (.*) $1/index.php break;

    error_page 403 http://my.linuxtone.org/member.php?m=user&a=login;

        if ( !-e $request_filename) {

            proxy_pass http://my.linuxtone.org;

            break;

        }

        include /usr/local/nginx/conf/proxy.conf;

十三、Nginx簡單優化

1. 減小nginx編譯後的檔案大小 (Reduce file size of nginx)

預設的nginx編譯選項裡居然是用debug模式(-g)的(debug模式會插入很多跟蹤和

ASSERT之類),編譯以後一個nginx有好幾兆。去掉nginx的debug模式編譯,編譯以

後隻有幾百K

在 auto/cc/gcc,最後幾行有:

# debug

CFLAGS=”$CFLAGS -g”

注釋掉或删掉這幾行,重新編譯即可。

2. 修改Nginx的header僞裝伺服器

1) 修改nginx.h

#vi nginx-0.7.30/src/core/nginx.h

#define NGINX_VERSION "1.8"

#define NGINX_VER "LTWS/" NGINX_VERSION

#define NGINX_VAR "NGINX"

#define NGX_OLDPID_EXT ".oldbin"

2) 修改nginx_http_header_filter_module

#vi nginx-0.7.30/src/http/ngx_http_header_filter_module.c

将如下

static char ngx_http_server_string[] = "Server: nginx" CRLF;

修改為

static char ngx_http_server_string[] = "Server: LTWS" CRLF;

a) 修改nginx_http_header_filter_module

#vi nginx-0.7.30/src/http/ngx_http_special_response.c

将如下:

static u_char ngx_http_error_full_tail[] =

--------------------------------------------------------------------------------

" NGINX_VER "

" CRLF

"" CRLF

;

static u_char ngx_http_error_tail[] =

nginx

修改為:

"NGINX_VER"

http://www.linuxtone.org

LTWS

修改後重新編譯一下環境,

404錯誤的時候顯示效果圖(如果沒有指定錯誤頁的話):

利用curl指令檢視伺服器header

3. 為特定的CPU指定CPU類型編譯優化.

預設nginx使用的GCC編譯參數是-O

需要更加優化可以使用以下兩個參數

--with-cc-opt='-O3' \

--with-cpu-opt=opteron \

使得編譯針對特定CPU以及增加GCC的優化.

此方法僅對性能有所改善并不會有很大的性能提升,供朋友們參考.

CPUD類型确定:

# cat /proc/cpuinfo | grep "model name"

編譯優化參數參考:http://en.gentoo-wiki.com/wiki/Safe_Cflags

4. Tcmalloc優化Nginx 性能

# wget http://download.savannah.gnu.org/releases/libunwind/libunwind-0.99-alpha.tar.gz

# tar zxvf libunwind-0.99-alpha.tar.gz

# cd libunwind-0.99-alpha/

# CFLAGS=-fPIC ./configure

# make CFLAGS=-fPIC

# make CFLAGS=-fPIC install

# wget http://google-perftools.googlecode.com/files/google-perftools-0.98.tar.gz

# tar zxvf google-perftools-0.98.tar.gz

# cd google-perftools-0.98/

# ./configure

# make && make install

# echo "/usr/local/lib" > /etc/ld.so.conf.d/usr_local_lib.conf

# ldconfig

# lsof -n | grep tcmalloc

編譯nginx 加載google_perftools_module:

./configure --with-google_perftools_module

在主配置檔案加入nginx.conf 添加:

google_perftools_profiles /path/to/profile;

5. 核心參數優化

# vi /etc/sysctl.conf

#在末尾增加以下内容:

net.ipv4.tcp_fin_timeout = 30

net.ipv4.tcp_keepalive_time = 300

net.ipv4.tcp_syncookies = 1

net.ipv4.tcp_tw_reuse = 1

net.ipv4.tcp_tw_recycle = 1

net.ipv4.ip_local_port_range = 5000 65000

#使配置立即生效

/sbin/sysctl -p

十四、如何建構高性的LEMP

請參見: http://www.linuxtone.org/lemp/lemp.pdf

1、提供完整的配置腳本下載下傳:http://www.linuxtone.org/lemp/scripts.tar.gz

2、提供NGINX常見配置範例含(虛拟主機,防盜鍊,Rewrite,通路控制,負載均衡Discuz相關

程式靜态化及等等),你隻要稍稍修改即可線上應用。

3、将原版的xcache替換成EA,并提供相關簡單調優腳本及配置檔案。

更多的及更新資料請關注: http://www.linuxtone.org

十五、Nginx監控

1、 RRDTOOL+Perl腳本畫圖監控

先安裝好rrdtool ,關于rrdtool本文不作介紹,具體安裝請參照linuxtone監控版塊.

#cd /usr/local/sbnin

#wget http://blog.kovyrin.net/files/mrtg/rrd_nginx.pl.txt

#mv rrd_nginx.pl.txt rrd_nginx.pl

#chmod a+x rrd_nginx.pl

#vi rrd_nginx.pl //配置腳本檔案設定好路徑

#!/usr/bin/perl

use RRDs;

use LWP::UserAgent;

# define location of rrdtool databases

my $rrd = '/data/www/wwwroot/nginx/rrd';

# define location of images

my $img = '/data/www/wwwroot/nginx/html';

# define your nginx stats URL

my $URL = "http:// 219.32.205.13/nginx_status";

…………

【注】根據自己具體的狀況修改相應的路徑.

#crontab –e //加入如下

* * * * * /usr/local/sbin/rrd_nginx.pl

重新開機crond後,通過配置nginx虛拟主機指到/data/www/wwwroot/nginx/html目錄,通過crond

自動執行perl腳本會生成很多圖檔.

http://xxx/connections-day.png即可看到伺服器狀态圖。

2、 官方Nginx-rrd 監控服務(多虛拟主機)(推薦)

網址:http://www.nginx.eu/nginx-rrd.html

此解決方案其實是基于上述監控方案的一個改進和增強,同樣先安裝好rrdtool這個畫圖工

具和相應的perl子產品再做如下操作:

# yum install perl-HTML*

先建立好生成的庫存和圖檔存放錄

#mkdir -p /data/www/wwwroot/nginx/{rrd,html}

#cd /usr/local/sbin

#wget http://www.nginx.eu/nginx-rrd/nginx-rrd-0.1.4.tgz

#tar zxvf nginx-rrd-0.1.4.tgz

#cd nginx-rrd-0.1.4

#cd etc/

#cp nginx-rrd.conf /etc

#cd etc/cron.d

#cp nginx-rrd.cron /etc/cron.d

#cd /usr/local/src/nginx-rrd-0.1.4/html

# cp index.php /data/www/wwwroot/nginx/html/

#cd /usr/local/src/nginx-rrd-0.1.4/usr/sbin

#cp * /usr/sbin/

#vi /etc/nginx-rrd.conf

#####################################################

#

# dir where rrd databases are stored

RRD_DIR="/data/www/wwwroot/nginx/rrd";

# dir where png images are presented

WWW_DIR="/data/www/wwwroot/nginx/html";

# process nice level

NICE_LEVEL="-19";

# bin dir

BIN_DIR="/usr/sbin";

# servers to test

# server_utl;server_name

SERVERS_URL="http://219.32.205.13/nginx_status;219.32.205.13

http://www.linuxtone.org/nginx_status;www.linuxtone.org"" //根據你的具體情況做調整.

SEVERS_URL 格式 http://domain1/nginx_status;domain1

http://domain2/nginx_status;domain2

這種格式監控多虛拟主機連接配接狀态:

重點啟crond服務,仍後通過http://219.32.205.13/nginx/html/ 即可通路。配置過程很簡單!

3、 CACTI模闆監控Nginx

利用Nginx_status狀态來畫圖實作CACTI監控

nginx編譯時允許http_stub_status_module

# vi /usr/local/nginx/conf/nginx.conf

location /nginx_status {

    stub_status on;

    allow 192.168.1.37;

}# kill -HUP `cat /usr/local/nginx/logs/nginx.pid`

# wget http://forums.cacti.net/download.php?id=12676

# tar xvfz cacti-nginx.tar.gz

# cp cacti-nginx/get_nginx_socket_status.pl /data/cacti/scripts/

# cp cacti-nginx/get_nginx_clients_status.pl /data/cacti/scripts/

# chmod 755 /data/cacti/scripts/get_nginx*

檢測插件

# /data/cacti/scripts/get_nginx_clients_status.pl http://192.168.1.37/nginx_status

在cacti管理面闆導入

cacti_graph_template_nginx_clients_stat.xml

cacti_graph_template_nginx_sockets_stat.xml

十六、常見問題與錯誤處理

1、 400 bad request錯誤的原因和解決辦法

配置nginx.conf相關設定如下.

client_header_buffer_size 16k;

large_client_header_buffers 4 64k;

根據具體情況調整,一般适當調整值就可以。

2、 Nginx 502 Bad Gateway錯誤

proxy_next_upstream error timeout invalid_header http_500 http_503;

或者嘗試設定:

large_client_header_buffers 4 32k;

3、 Nginx出現的413 Request Entity Too Large錯誤

這個錯誤一般在上傳檔案的時候會出現,

編輯Nginx主配置檔案Nginx.conf,找到http{}段,添加

client_max_body_size 10m; //設定多大根據自己的需求作調整.

如果運作php的話這個大小client_max_body_size要和php.ini中的如下值的最大值

一緻或者稍大,這樣就不會因為送出資料大小不一緻出現的錯誤。

post_max_size = 10M

upload_max_filesize = 2M

4、 解決504 Gateway Time-out(nginx)

遇到這個問題是在更新discuz論壇的時候遇到的

一般看來, 這種情況可能是由于nginx預設的fastcgi程序響應的緩沖區太小造成的,

這将導緻fastcgi程序被挂起, 如果你的fastcgi服務對這個挂起處理的不好, 那麼最後就

極有可能導緻504 Gateway Time-out

現在的網站, 尤其某些論壇有大量的回複和很多内容的, 一個頁面甚至有幾百K。

預設的fastcgi程序響應的緩沖區是8K, 我們可以設定大點

在nginx.conf裡, 加入:

fastcgi_buffers 8 128k

這表示設定fastcgi緩沖區為8×128k

當然如果您在進行某一項即時的操作, 可能需要nginx的逾時參數調大點,例如設定成60秒:

send_timeout 60;

隻是調整了這兩個參數, 結果就是沒有再顯示那個逾時, 可以說效果不錯, 但是也

可能是由于其他的原因, 目前關于nginx的資料不是很多, 很多事情都需要長期的經驗

累計才有結果, 期待您的發現哈!

5、 如何使用Nginx Proxy

朋友一台伺服器運作tomcat 為8080端口,IP:192.168.1.2:8080,另一台機器

IP:192.168.1.8. 朋友想通過通路http://192.168.1.8即可通路tomcat服務.配置如下:

在192.168.1.8的nginx.conf上配置如下:

    server_name Java.linuxtone.org

        proxy_pass http://192.168.1.2:8080;

6、 如何關閉Nginx的LOG

access_log /dev/null;

error_log /dev/null;

Nginx反向代理tomcat伺服器 

一、Tomcat

基本配置

1.為Tomcat提供SysV腳本

2.catalina 腳本講解

3.telnet 登入管理Tomcat

4.配置Tomcat虛拟主機

5.Tomcat圖形管理接口

6.部署JSP網站案例

二、Nginx反向代理Tomcat伺服器 

1.Nginx将請求反向代理到後端Tomcat

2.Nginx将圖檔緩存到本地

3.Nginx将請求實作動靜分離 

注,實驗環境說明,作業系統:CentOS 6.4 x86_64,軟體版本:jdk-7u40、apache-tomcat-

7.0.42、Nginx-1.4.2,部落格中所用到的軟體請到這裡下載下傳:http://yunpan.cn/QGBCLwrZnpLMS

一、Tomcat 基本配置

注,在上一篇博文中我們已經示範安裝了Tomcat,這裡我們就不在示範,不清楚的博友可以

參考這篇博文,http://freeloda.blog.51cto.com/2033581/1299644,在上一篇博文中我們沒有

增加,SysV腳本,在這篇博文中我們來增加一下,下面我們就來具體示範一下。

[root@tomcat ~]# vim /etc/init.d/tomcat

#!/bin/sh

# Tomcat init script for Linux.

# chkconfig: 2345 96 14

# description: The Apache Tomcat servlet/JSP Container.

CATALINA_HOME=/usr/local/tomcat #注意你的腳本路徑

export CATALINA_HOME

# export CATALINA_OPTS="-Xms128m -Xmx256m"

exec $CATALINA_HOME/bin/catalina.sh $*

下面我們來增加執行權限,并加入服務清單設定開機自啟動,

[root@tomcat ~]# chmod +x /etc/init.d/tomcat

[root@tomcat ~]# chkconfig --add tomcat

[root@tomcat ~]# chkconfig tomcat --list

tomcat 0:關閉 1:關閉 2:啟用 3:啟用 4:啟用 5:啟用 6:關閉

下面我們來啟動一下Tomcat并測試一下,

[root@tomcat ~]# service tomcat start

Using CATALINA_BASE:  /usr/local/tomcat

Using CATALINA_HOME:  /usr/local/tomcat

Using CATALINA_TMPDIR: /usr/local/tomcat/temp

Using JRE_HOME:    /usr

Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar

檢視一下啟動的端口号,

[root@tomcat ~]# netstat -ntulp

Active Internet connections (only servers)

Proto Recv-Q Send-Q Local Address        Foreign Address       State    PID/Program name

tcp    0   0 0.0.0.0:22         0.0.0.0:*          LISTEN   1044/sshd

tcp    0   0 127.0.0.1:25        0.0.0.0:*          LISTEN   1121/master

tcp    0   0 127.0.0.1:6010       0.0.0.0:*          LISTEN   12988/sshd

tcp    0   0 127.0.0.1:6011       0.0.0.0:*          LISTEN   13053/sshd

tcp    0   0 :::8080           :::*            LISTEN   13088/java

tcp    0   0 :::22            :::*            LISTEN   1044/sshd

tcp    0   0 ::1:25           :::*            LISTEN   1121/master

tcp    0   0 ::1:6010          :::*            LISTEN   12988/sshd

tcp    0   0 ::1:6011          :::*            LISTEN   13053/sshd

tcp    0   0 ::ffff:127.0.0.1:8005    :::*            LISTEN   13088/java

tcp    0   0 :::8009           :::*            LISTEN   13088/java

用浏覽器通路一下,

好了,到這裡Tomcat的SysV腳本增加完成,下面我們來說一下catalina腳本。

首先我們來檢視一下這個腳本,

[root@tomcat bin]# catalina.sh -h

Using JRE_HOME:    /usr/java/jdk1.7.0_40

Usage: catalina.sh ( commands ... )

commands:

 debug       Start Catalina in a debugger

 debug -security  Debug Catalina with a security manager

 jpda start    Start Catalina under JPDA debugger

 run        Start Catalina in the current window

 run -security   Start in the current window with security manager

 start       Start Catalina in a separate window

 start -security  Start in a separate window with security manager

 stop       Stop Catalina, waiting up to 5 seconds for the process to end

 stop n      Stop Catalina, waiting up to n seconds for the process to end

 stop -force    Stop Catalina, wait up to 5 seconds and then use kill -KILL if still running

 stop n -force   Stop Catalina, wait up to n seconds and then use kill -KILL if still running

 configtest    Run a basic syntax check on server.xml - check exit code for result

 version      What version of tomcat are you running?

Note: Waiting for the process to end and use of the -force option require that 

$CATALINA_PID is defined

注,從幫助上來看,這個腳本使用還是挺簡單的。下面我們來說幾個常用的選項,

catalina.sh

下面我們就來具體示範一下,

[root@tomcat ~]# catalina.sh configtest

九月 21, 2013 11:08:26 下午 org.apache.catalina.core.AprLifecycleListener init

資訊: The APR based Apache Tomcat Native library which allows optimal performance in

production environments was not found on the java.library.path: 

/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib

九月 21, 2013 11:08:27 下午 org.apache.coyote.AbstractProtocol init

資訊: Initializing ProtocolHandler ["http-bio-8080"]

資訊: Initializing ProtocolHandler ["ajp-bio-8009"]

九月 21, 2013 11:08:27 下午 org.apache.catalina.startup.Catalina load

資訊: Initialization processed in 1269 ms

注,使用configtest選項時,得關閉Tomcat,不然會報錯。

啟動Tomcat,

[root@tomcat ~]# catalina.sh start

關閉Tomcat,

[root@tomcat ~]# catalina.sh stop

檢視Tomcat版本,

[root@tomcat ~]# catalina.sh version

Server version: Apache Tomcat/7.0.42

Server built:  Jul 2 2013 08:57:41

Server number: 7.0.42.0

OS Name:    Linux

OS Version:   2.6.32-358.el6.x86_64

Architecture:  amd64

JVM Version:  1.7.0_40-b43

JVM Vendor:   Oracle Corporation

好了,catalina腳本,我們就說到這裡了,下面我們來說一下telnet管理Tomcat。

注,在說telnet管理Tomcat之前,我們得先看一下預設的配置檔案,這裡面定義了預設的管理

端口,

[root@tomcat ~]# vim /usr/local/tomcat/conf/server.xml

<Server port="8005" shutdown="SHUTDOWN">

說明,定義了一個管理端口為8005,我們可以用telnet直接登入進本機的8005端口,來執行

SHUTDOWN指令,來關閉Tomcat執行個體。下面我們來具體示範一下,

先安裝telnet用戶端,

[root@tomcat ~]# yum install -y telnet

下面我們一測試并檢視,

[root@tomcat ~]# telnet localhost 8005

Trying ::1...

telnet: connect to address ::1: Connection refused

Trying 127.0.0.1...

Connected to localhost.

Escape character is '^]'.

SHUTDOWN #輸入SHOWDOWN就可以直接關閉Tomcat服務。

Connection closed by foreign host.

注,大家可以看到Tomcat伺服器已經關閉。好了,telnet管理我們就說到這裡,下面我們來說

一下,Tomcat虛拟主機的配置。

注,在說Tomcat虛拟主機之前,咱們來詳細的看看預設的配置檔案,雖然在上一篇部落格中全

部有講解,在這篇部落格中我還是再和大家簡單說一下,下面是預設配置檔案。大家可以看到,

絕大部分的配置檔案是注釋,包含在<!-- -->、全是注釋。下面我們就來具體的看看,注釋我

們就不說了,說具體的定義的内容

[root@tomcat ~]# cat /usr/local/tomcat/conf/server.xml

<?xml version='1.0' encoding='utf-8'?>

<!--

 Licensed to the Apache Software Foundation (ASF) under one or more

 contributor license agreements. See the NOTICE file distributed with

 this work for additional information regarding copyright ownership.

 The ASF licenses this file to You under the Apache License, Version 2.0

 (the "License"); you may not use this file except in compliance with

 the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software

 distributed under the License is distributed on an "AS IS" BASIS,

 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 See the License for the specific language governing permissions and

 limitations under the License.

-->

<!-- Note: A "Server" is not itself a "Container", so you may not

   define subcomponents such as "Valves" at this level.

   Documentation at /docs/config/server.html

<Server port="8005" shutdown="SHUTDOWN"> #大家可以看到,這裡是我們剛才講解的,

定義一個管理接口

 <!-- Security listener. Documentation at /docs/config/listeners.html

 <Listener className="org.apache.catalina.security.SecurityListener" />

 -->

 <!--APR library loader. Documentation at /docs/apr.html -->

 <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />

 <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-

howto.html -->

 <Listener className="org.apache.catalina.core.JasperListener" />

 <!-- Prevent memory leaks due to use of particular java/javax APIs-->

 <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />

 <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />

 <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

 <!-- Global JNDI resources

    Documentation at /docs/jndi-resources-howto.html

 <GlobalNamingResources>

  <!-- Editable user database that can also be used by

     UserDatabaseRealm to authenticate users

  -->

  <Resource name="UserDatabase" auth="Container"

       type="org.apache.catalina.UserDatabase"

       description="User database that can be updated and saved"

       factory="org.apache.catalina.users.MemoryUserDatabaseFactory"

       pathname="conf/tomcat-users.xml" />

 </GlobalNamingResources>

 <!-- A "Service" is a collection of one or more "Connectors" that share

    a single "Container" Note: A "Service" is not itself a "Container",

    so you may not define subcomponents such as "Valves" at this level.

    Documentation at /docs/config/service.html

 <Service name="Catalina"> #定義一個Service指令為Catalina

  <!--The connectors can use a shared executor, you can define one or more named thread

pools-->

  <!--

  <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"

    maxThreads="150" minSpareThreads="4"/>

  <!-- A "Connector" represents an endpoint by which requests are received

     and responses are returned. Documentation at :

     Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)

     Java AJP Connector: /docs/config/ajp.html

     APR (HTTP/AJP) Connector: /docs/apr.html

     Define a non-SSL HTTP/1.1 Connector on port 8080

  <Connector port="8080" protocol="HTTP/1.1"

        connectionTimeout="20000"

        redirectPort="8443" /> #這裡定義了一個連接配接器,協定為http,端口為8080,最大連接配接

逾時為20s,這裡還定義了一個SSL的重定向端口8443。我們可以根據需要進行修改。一般我

們都用80端口與443端口。

  <!-- A "Connector" using the shared thread pool-->

  <Connector executor="tomcatThreadPool"

        port="8080" protocol="HTTP/1.1"

        redirectPort="8443" />

  <!-- Define a SSL HTTP/1.1 Connector on port 8443

     This connector uses the JSSE configuration, when using APR, the

     connector should be using the OpenSSL style configuration

     described in the APR documentation -->

  <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"

        maxThreads="150" scheme="https" secure="true"

        clientAuth="false" sslProtocol="TLS" /> #這裡定義了一個SSL的案例,主要定義相關密

鑰與證書。

  <!-- Define an AJP 1.3 Connector on port 8009 -->

  <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" /> #這裡定義了一個支援

AJP協定的連接配接器。

  <!-- An Engine represents the entry point (within Catalina) that processes

     every request. The Engine implementation for Tomcat stand alone

     analyzes the HTTP headers included with the request, and passes them

     on to the appropriate Host (virtual host).

     Documentation at /docs/config/engine.html -->

  <!-- You should set jvmRoute to support load-balancing via AJP ie :

  <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">

  <Engine name="Catalina" defaultHost="localhost"> #這裡定義了一個名為Catalina的引擎,

并定義了一個預設主機為localhost。

   <!--For clustering, please take a look at documentation at:

     /docs/cluster-howto.html (simple how to)

     /docs/config/cluster.html (reference documentation) -->

   <!--

   <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>

   -->

   <!-- Use the LockOutRealm to prevent attempts to guess user passwords

      via a brute-force attack -->

   <Realm className="org.apache.catalina.realm.LockOutRealm">

    <!-- This Realm uses the UserDatabase configured in the global JNDI

       resources under the key "UserDatabase". Any edits

       that are performed against this UserDatabase are immediately

       available for use by the Realm. -->

    <Realm className="org.apache.catalina.realm.UserDatabaseRealm"

        resourceName="UserDatabase"/>

   </Realm>

   <Host name="localhost" appBase="webapps"

      unpackWARs="true" autoDeploy="true"> #這裡就是定義的虛拟主機。

    <!-- SingleSignOn valve, share authentication between web applications

       Documentation at: /docs/config/valve.html -->

    <!--

    <Valve className="org.apache.catalina.authenticator.SingleSignOn" />

    -->

    <!-- Access log processes all example.

       Documentation at: /docs/config/valve.html

       Note: The pattern used is equivalent to using pattern="common" -->

    <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"

        prefix="localhost_access_log." suffix=".txt"

        pattern="%h %l %u %t &quot;%r&quot; %s %b" /> #這裡定義了一個日志相關的屬

性。

   </Host>

  </Engine>

 </Service>

</Server>

好了,在這裡我們又簡單的說明一下,配置檔案下面我們就來具體示範一下怎麼配置虛拟主機

首先,我們來修改一下配置檔案,

[root@tomcat conf]# vim server.xml

#增加下面幾行

<Host name="www.test.com" appBase="/web/webapp"

   unpackWARs="true" autoDeploy="true">

     <Context path="/" docBase="/web/webapp" reloadable="true"/>

</Host>

接下來我們來建立文檔目錄與測試頁面,

[root@tomcat ~]# mkdir -pv /web/webapp

[root@tomcat ~]# cd /web/webapp

[root@tomcat webapp]# vim index.jsp

<%@ page language="java" %>

<%@ page import="java.util.*" %>

<html>

 <head>

  <title>JSP test page.</title>

 </head>

 <body>

  <% out.println("Welcome to test. Site, http://www.test.com"); %>

 </body>

</html>

現在我們來測試一下我們修改的配置檔案,

[root@tomcat ~]# service tomcat stop

^[[A[root@tomcat service tomcat configtest

Sep 22, 2013 2:15:47 AM org.apache.catalina.core.AprLifecycleListener init

INFO: The APR based Apache Tomcat Native library which allows optimal performance in

Sep 22, 2013 2:15:47 AM org.apache.coyote.AbstractProtocol init

INFO: Initializing ProtocolHandler ["http-bio-80"]

INFO: Initializing ProtocolHandler ["ajp-bio-8009"]

Sep 22, 2013 2:15:47 AM org.apache.catalina.startup.Catalina load

INFO: Initialization processed in 1294 ms

注,大家可以看到,我們這裡沒有報錯,說明配置都是正确的,若配置有錯誤,會在最後一行

提醒你。

再下面我們來啟動Tomcat并測試一下,

[root@tomcat ~]# netstat -ntulp Active Internet connections (only servers) Proto Recv-Q

Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:22 0.0.0.0:*

LISTEN 1044/sshd tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 1121/master tcp 0 0 

127.0.0.1:6010 0.0.0.0:* LISTEN 13368/sshd tcp 0 0 127.0.0.1:6011 0.0.0.0:* LISTEN

13387/sshd tcp 0 0 127.0.0.1:6012 0.0.0.0:* LISTEN 13407/sshd tcp 0 0 :::80 :::* LISTEN

13557/java tcp 0 0 :::22 :::* LISTEN 1044/sshd tcp 0 0 ::1:25 :::* LISTEN 1121/master tcp

0 0 ::1:6010 :::* LISTEN 13368/sshd tcp 0 0 ::1:6011 :::* LISTEN 13387/sshd tcp 0 0

::1:6012 :::* LISTEN 13407/sshd tcp 0 0 :::8009 :::* LISTEN 13557/java 

注,還有一點得說明一下,我這裡為了友善測試,将預設端口8080修改為了80端口。下面是

測試效果,

為了幫助大家了解,我們這裡再次講解一下,Host元件與Context元件以及相關屬性。

Host元件:

位于Engine容器中用于接收請求并進行相應處理的主機或虛拟主機,如前面我們自定義的内容

<Host name="www.server110.com" appBase="/web/webapp"

常用屬性說明:

name:定義虛拟主機的域名

appBase:此Host的webapps目錄,即存放非歸檔的web應用程式的目錄或歸檔後的WAR檔案

的目錄路徑;可以使用基于$CATALINA_HOME的相對路徑;

autoDeploy:在Tomcat處于運作狀态時放置于appBase目錄中的應用程式檔案是否自動進行

deploy;預設為true;

unpackWars:在啟用此webapps時是否對WAR格式的歸檔檔案先進行展開;預設為true;

主機名稱定義:

如果一個主機有兩個或兩個以上的主機名,額外的名稱均可以以别名的形式進行定義,如下:

<Host name="www.test.com" appBase="webapps" unpackWARs="true">

 <Alias>web.test.com</Alias>

Context元件:

Context在某些意義上類似于apache中的路徑别名,一個Context定義用于辨別tomcat執行個體中的

一個Web應用程式。如下面的定義:

  <!-- Tomcat Root Context -->

  <Context path="" docBase="/web/webapps"/>

  <!-- buzzin webapp -->

  <Context path="/bbs"

   docBase="/web/threads/bbs"

   reloadable="true">

  </Context>

  <!-- chat server -->

   <Context path="/chat" docBase="/web/chat"/>

  <!-- darian web -->

  <Context path="/darian" docBase="darian"/>

在Tomcat中,每一個context定義也可以使用一個單獨的XML檔案進行,其檔案的目錄為

$CATALINA_HOME/conf/<engine name>/<host name>。可以用于Context中的XML元素有

Loader,Manager,Realm,Resources和WatchedResource。

常用的屬性定義有:

docBase:相應的Web應用程式的存放位置;也可以使用相對路徑,起始路徑為此Context所屬

Host中appBase定義的路徑;切記,docBase的路徑名不能與相應的Host中appBase中定義的路

徑名有包含關系,比如,如果appBase為deploy,而docBase絕不能為deploy-bbs類的名字;

path:相對于Web伺服器根路徑而言的URI;如果為空“”,則表示為此webapp的根路徑;如果

context定義在一個單獨的xml檔案中,此屬性不需要定義;

reloadable:是否允許重新加載此context相關的Web應用程式的類;預設為false;

為了便于大家了解,我們這裡再定義一個Context并測試一下,

我們先來修改一下配置檔案

    unpackWARs="true" autoDeploy="true">

      <Context path="/" docBase="/web/webapp" reloadable="true"/>

      <Context path="/test" docBase="/web/test" reloadable="true"/> #增加這一行

 </Host>

下面來增加目錄文檔與測試檔案,

[root@tomcat webapp]# mkdir /web/test

[root@tomcat webapp]# cd /web/test

[root@tomcat test]# vim index.jsp

 <head><title>TomcatA</title></head>

  <h1><font color="red">TomcatA </h1>

  <table align="centre" >

   <tr>

    <td>Session ID</td>

  <% session.setAttribute("abc","abc"); %>

    <td><%= session.getId() %></td>

   </tr>

    <td>Created on</td>

    <td><%= session.getCreationTime() %></td>

  </table>

測試一下配置檔案是否有錯并啟動Tomcat,

[root@tomcat ~]# service tomcat configtest Using CATALINA_BASE: /usr/local/tomcat Using

CATALINA_HOME: /usr/local/tomcat Using CATALINA_TMPDIR: /usr/local/tomcat/temp Using

JRE_HOME: /usr Using CLASSPATH: 

/usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar Sep 22, 2013 2:40:57

AM org.apache.catalina.core.AprLifecycleListener init INFO: The APR based Apache Tomcat

Native library which allows optimal performance in production environments was not found

on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib Sep 22,

2013 2:40:58 AM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler

["http-bio-80"] Sep 22, 2013 2:40:58 AM org.apache.coyote.AbstractProtocol init INFO:

Initializing ProtocolHandler ["ajp-bio-8009"] Sep 22, 2013 2:40:58 AM 

org.apache.catalina.startup.Catalina load INFO: Initialization processed in 1352 ms

127.0.0.1:6010 0.0.0.0:* LISTEN 13587/sshd tcp 0 0 127.0.0.1:6011 0.0.0.0:* LISTEN

13945/java tcp 0 0 :::22 :::* LISTEN 1044/sshd tcp 0 0 ::1:25 :::* LISTEN 1121/master tcp

0 0 ::1:6010 :::* LISTEN 13587/sshd tcp 0 0 ::1:6011 :::* LISTEN 13387/sshd tcp 0 0

::1:6012 :::* LISTEN 13407/sshd tcp 0 0 ::ffff:127.0.0.1:8005 :::* LISTEN 13945/java tcp 0

0 :::8009 :::* LISTEN 13945/java 

下面我們就用浏覽器測試一下,

好了,到這裡我們的Tomcat虛拟主機的講解就到這裡了,下面我們來說一下Tomcat圖形管理

接口。

我們先來看一下預設的圖形配置界面,

注,大家注意看右上角,我用紅色方框标記出來的,大家可以看有三個按鈕,分别為

Server Status 主要用來檢視伺服器的狀态

Manager App 主要用來管理應用程式的部署及監控

Host Manager 主要用來管理虛拟主機

下面我們就來具休的配置一下,大家可以看到,你點選任何一個按鈕都要輸入使用者名和密碼的

,在我們配置之前我們先來說一下,Tomcat的Manager功能,

Manager的四個管理角色:

manager-gui - allows access to the HTML GUI and the status pages

manager-script - allows access to the text interface and the status pages

manager-jmx - allows access to the JMX proxy and the status pages

manager-status - allows access to the status pages only

注,這裡我說一下,上面的英文比較簡單我就不在裡翻譯了,大家自己看一下。

下面我們就來啟用manager功能,修改tomcat-user.xml檔案,添加如下行:

<role rolename="manager-gui"/>

<role rolename="admin-gui"/>

<user username="tomcat" password="tomcat" roles="manager-gui,admin-gui"/>

簡單解釋一下,Tomcat有内置的角色,我們這裡增加了兩個角色一個為manager-gui,另一個

為admin-gui,使用者名和密碼都為tomcat。

注,增加的内容一定要在<tomcat-users></tomcat-users>之間。不然,不會生效。好了,下

面我們一來測試一下配置檔案,并重新啟動一下Tomcat

/usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar Sep 22, 2013 3:08:44

2013 3:08:44 AM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler

["http-bio-80"] Sep 22, 2013 3:08:44 AM org.apache.coyote.AbstractProtocol init INFO:

Initializing ProtocolHandler ["ajp-bio-8009"] Sep 22, 2013 3:08:44 AM 

org.apache.catalina.startup.Catalina load INFO: Initialization processed in 1213 ms

14197/java tcp 0 0 :::22 :::* LISTEN 1044/sshd tcp 0 0 ::1:25 :::* LISTEN 1121/master tcp

::1:6012 :::* LISTEN 13407/sshd tcp 0 0 ::ffff:127.0.0.1:8005 :::* LISTEN 14197/java tcp 0

0 :::8009 :::* LISTEN 14197/java 

好了,下面我們用浏覽器檢視一下,

注,點選Server Status按鈕,讓你輸入使用者名和密碼。我這裡全部設定是tomcat。

然後,會出現以下界面。顯示全部伺服器運作狀态!大家可以仔細的看一下,我就不帶着大家

看了。

下面是應用程式部署管理界面,

下面是虛拟主機管理頁面,

注,我們一般在生産環境中用的最多是應用程式部署界面,可以進行熱布署應用程式,很友善

,大家可以嘗試一下。好了,圖形管理界面我們就說到這裡了,下面我們來說一下,Tomcat

的一個小案例。我們說了那麼多,有朋友就會說了,怎麼一個案例也沒有呢?下面我們就來布

署一個社交網站的案例JavaCenter Home。

首頁,我們來修改一下配置檔案,

<Host name="www.test.com" appBase="/web"

 <Context path="/" docBase="webapp" reloadable="true"/>

注,增加一下虛拟主機,檔案目錄為/web/webapp。

下面我們來解壓一下我們下載下傳好的JavaCenter Home網站程式,

[root@tomcat src]# tar xf JavaCenter_Home_2.0_GBK.tar.bz2

接下來将解壓好的JavaCenter Home程式移動到/web/webapp下,

[root@tomcat src]# cd JavaCenter_Home_2.0_GBK

[root@tomcat JavaCenter_Home_2.0_GBK]# mv * /web/webapp/

下面我們來測試一下配置檔案并啟動Tomcat服務,

[root@tomcat ~]# service tomcat configtest

Using JRE_HOME:    /usr/java/jdk1.6.0_21

Sep 23, 2013 5:31:18 PM org.apache.catalina.core.AprLifecycleListener init

/usr/java/jdk1.6.0_21/jre/lib/amd64/server:/usr/java/jdk1.6.0_21/jre/lib/amd64:/usr/java/jdk

1.6.0_21/jre/../lib/amd64:/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib

Sep 23, 2013 5:31:20 PM org.apache.coyote.AbstractProtocol init

Sep 23, 2013 5:31:20 PM org.apache.catalina.startup.Catalina load

INFO: Initialization processed in 2493 ms

tcp    0   0 0.0.0.0:22         0.0.0.0:*          LISTEN   1026/sshd

tcp    0   0 127.0.0.1:25        0.0.0.0:*          LISTEN   1256/master

tcp    0   0 127.0.0.1:6010       0.0.0.0:*          LISTEN   1339/sshd

tcp    0   0 0.0.0.0:3306        0.0.0.0:*          LISTEN   1165/mysqld

tcp    0   0 :::80            :::*            LISTEN   1499/java

tcp    0   0 :::22            :::*            LISTEN   1026/sshd

tcp    0   0 ::1:25           :::*            LISTEN   1256/master

tcp    0   0 ::1:6010          :::*            LISTEN   1339/sshd

tcp    0   0 :::8009           :::*            LISTEN   1499/java

下面我們用浏覽器通路一下,http://www.test.com(注,要想用域名通路,必須配置本機有

hosts檔案,Windows7hosts檔案目錄,C:\Windows\System32\drivers\etc\hosts)

注,上面的錯誤說明我們連接配接MySQL資料庫失敗。因為我們這裡還沒有安裝與配置嘛。下面我

們趕快來配置一下,

先安裝資料庫,我們這裡就用yum安裝一下,

[root@tomcat ~]# yum install -y mysql-server

下面來啟動并配置mysql,

[root@tomcat ~]# service mysqld start

Starting mysqld:                      [ OK ]

[root@tomcat ~]# mysql

Welcome to the MySQL monitor. Commands end with ; or \g.

Your MySQL connection id is 2

Server version: 5.1.69 Source distribution

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

好了,到這裡我們mysql就安裝完成了,下面我們來看一下我們的程式目錄,

[root@tomcat ~]# cd /web/webapp/

[root@tomcat webapp]# ls

admin    avatar.jsp     data     help.jsp  js.jsp    rss.jsp  userapp.jsp

admincp.jsp config.properties do.jsp    image    link.jsp   source   WEB-INF

api     contact.jsp    editor.jsp  index.jsp  magic.jsp  space.jsp xmlrpc.jsp

app.jsp   cp.jsp       errors    install   META-INF   template

attachment  crossdomain.xml  favicon.ico invite.jsp network.jsp theme

大家可以看到裡面有個install的目錄,下面我們用浏覽器通路一下,

http://www.test.com/install,會跳出一個安裝界面,如下圖

從圖中,我們可以看出,是以環境配置完成,都符合要求。下面我們點選“接受授權協定,開

始安裝JavaCenter Home”,會跳出下一界面,如下圖

從圖中,我們可以看出得輸入,資料庫名稱、資料庫使用者名、資料庫密碼。下面我們就來增加

一下,

Your MySQL connection id is 13

mysql> create database jcenter;

Query OK, 1 row affected (0.00 sec)

mysql> grant all privileges on jcenter.* to jcenter@'localhost' identified by '123456';

Query OK, 0 rows affected (0.00 sec)

mysql> grant all privileges on jcenter.* to jcenter@'127.0.0.1' identified by '123456';

mysql> flush privileges;

上面建立一個jcenter資料庫,授權通路一個jcenter使用者,密碼為123456。下面我們繼續配置

我們輸入剛才設定的資料庫使用者名、資料庫密碼、資料庫名稱。點選“設定完畢,檢測我的數

據庫配置”,圖顯示的3和4會看自動進行安裝,我們隻等一會即可。安裝完成的效果如下圖,

下面我們開通一個管理者空間,使用者名和密碼都為admin,如下圖

點選“開通管理者空間”,會跳出另一個界面,如下圖

我們點選“進入空間首頁”,效果如下圖

好了,到這裡我們的JavaCenter Home就全部配置完成了,我們第一階段的基本配置就這裡全

部完成,下面我們主要講解Nginx反向代理Tomcat伺服器。

二、Nginx反向代理Tomcat伺服器

0.測試環境準備階段

下面先看一下實驗拓撲,

接着來同步各節點時間,

[root@tomcat ~]# ntpdate 202.120.2.101

[root@nginx ~]# ntpdate 202.120.2.101

下面我們來安裝nginx伺服器,首先來解決nginx的依賴關系,

[root@nginx ~]# yum groupinstall -y "Development Tools" "Server Platform Deveopment"

[root@nginx ~]# yum install -y openssl-devel pcre-devel

下面我們來建立nginx使用者,

[root@nginx ~]# groupadd -r -g 108 nginx

[root@nginx ~]# useradd -r -g 108 -u 108 nginx

[root@nginx ~]# id nginx

uid=108(nginx) gid=108(nginx) 組=108(nginx)

接着我們來開始編譯和安裝,

[root@nginx src]# tar xf nginx-1.4.2.tar.gz

[root@nginx src]# cd nginx-1.4.2

[root@nginx nginx-1.4.2]# ls

auto CHANGES CHANGES.ru conf configure contrib html LICENSE man README src

[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

[root@nginx nginx-1.4.2]# make && make install

說明:

Nginx可以使用Tmalloc(快速、多線程的malloc庫及優秀性能分析工具)來加速記憶體配置設定,使用

此功能需要事先安裝gperftools,而後在編譯nginx添加--with-google_perftools_module選項即

可。

如果想使用nginx的perl子產品,可以通過為configure腳本添加--with-http_perl_module選項來實

現,但目前此子產品仍處于實驗性使用階段,可能會在運作中出現意外,是以,其實作方式這裡

不再介紹。如果想使用基于nginx的cgi功能,也可以基于FCGI來實作,具體實作方法請參照網

上的文檔。

下面我們為nginx提供SysV init腳本,

[root@nginx ~]# cat /etc/init.d/nginx

# 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 -eq 0 ] && rm -f $lockfile

restart() {

  configtest || return $?

  stop

  sleep 1

  start

reload() {

  echo -n $"Reloading $prog: "

  killproc $nginx -HUP

  RETVAL=$?

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

  restart|configtest)

  reload)

    rh_status_q || exit 7

  force-reload)

    force_reload

  status)

    rh_status

  condrestart|try-restart)

      ;;

  *)

    echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-

reload|configtest}"

    exit 2

esac

而後為此腳本賦予執行權限,

[root@nginx ~]# chmod +x /etc/init.d/nginx

添加至服務管理清單,并讓其開機自動啟動,

[root@nginx ~]# chkconfig --add nginx

[root@nginx ~]# chkconfig nginx on

而後就可以啟動服務并測試了,

[root@nginx ~]# service nginx start

正在啟動 nginx:                      [确定]

[root@nginx ~]# netstat -ntulp

tcp    0   0 0.0.0.0:80         0.0.0.0:*          LISTEN   14006/nginx

tcp    0   0 0.0.0.0:22         0.0.0.0:*          LISTEN   1029/sshd

tcp    0   0 127.0.0.1:25        0.0.0.0:*          LISTEN   1105/master

tcp    0   0 127.0.0.1:6010       0.0.0.0:*          LISTEN   1345/sshd

tcp    0   0 :::22            :::*            LISTEN   1029/sshd

tcp    0   0 ::1:25           :::*            LISTEN   1105/master

tcp    0   0 ::1:6010          :::*            LISTEN   1345/sshd

下面是測試結果,

好了,到這裡我們準備工作就全部完成了,下面們來簡單的配置一下Nginx反向代理Tomcat服

務器。

首先,我們來修改一下nginx的配置檔案,

[root@nginx ~]# cd /etc/nginx/

[root@nginx nginx]# cp nginx.conf nginx.conf.bak

[root@nginx nginx]# vim nginx.conf

#user nobody;

worker_processes 1;

#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;

      #root  html;

      #index index.html index.htm;

      proxy_pass http://192.168.18.201/; #注釋預設兩行,新增一行。

    #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;

  }

重新加載一下配置檔案,

[root@nginx ~]# service nginx reload

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok

nginx: configuration file /etc/nginx/nginx.conf test is successful

重新載入 nginx:                      [确定]

下面進行測試一下,(注,首先你得保證你的tomcat伺服器能正常通路,下面我們先來通路一

下tomcat伺服器,如下圖)

大家可以看到我們的tomcat伺服器可以正常通路,下面我們來看測試一下nginx可不可以進行

反向代理。(注,還有問題,這裡為了友善測試我們先将tomcat的預設主機設定為

www.test.com)

  <Engine name="Catalina" defaultHost="www.test.com">

重新啟動一下tomcat并測試,

tcp    0   0 127.0.0.1:6011       0.0.0.0:*          LISTEN   2744/sshd

tcp    0   0 0.0.0.0:3306        0.0.0.0:*          LISTEN   2382/mysqld

tcp    0   0 :::80            :::*            LISTEN   3299/java

tcp    0   0 ::1:6011          :::*            LISTEN   2744/sshd

tcp    0   0 :::8009           :::*            LISTEN   3299/java

下面我們來通路測試一下tomcat伺服器,

下面我們來測試看nginx是否能代理tomcat伺服器,

好了,大家可以看到我們成功設定了nginx反向代理tomcat伺服器。好了,大家可以看到,我

們網站上有很多的圖檔,每次通路都要去後端的tomcat伺服器上去取,很消耗伺服器資源。我

們下面将設定在nginx伺服器上緩存圖檔。

同樣的,我們先來修改配置檔案,

[root@nginx nginx]# cat nginx.conf

  proxy_cache_path /nginx/cache levels=1:2 keys_zone=first:10m inactive=24h 

max_size=1G; #建立緩存路徑與相關屬性

  upstream backend { #建立後端tomcat伺服器

  server 192.168.18.201 weight=1;

      #proxy_pass http://192.168.18.201/; #注釋原來的代理設定

      proxy_pass http://backend/; #啟動後端伺服器

  location ~* "\.(jpg|jpeg|png|gif|html|css|js)$" { #緩存圖檔與靜态内容

    proxy_pass http://backend;

    proxy_cache first;

    proxy_cache_valid 200 24h; #200狀态緩存24小時

    proxy_cache_valid 302 10m; #302狀态緩存10分鐘

    add_header X-Cache-Status $upstream_cache_status; #在http頭部增加一個字段顯示是否

指令緩存

下面我們來建立緩存目錄,

[root@nginx ~]# mkdir -pv /nginx/cache

mkdir: 已建立目錄 "/nginx"

mkdir: 已建立目錄 "/nginx/cache"

測試一下配置檔案是否有錯,

[root@nginx ~]# nginx -t

重新加載配置檔案,

那麼下面我們就來測試一下,

大家可以看到我們通路的所有的靜态内容都是命中的,X-Cache-Status: HIT,下面們來看一下

緩存的目錄,

[root@nginx ~]# cd /nginx/cache/

[root@nginx cache]# ls

0 1 2 3 4 5 6 7 8 9 b c d e

大家可以看到,緩存目錄當中有我們緩存的内容,好了到這裡我們的nginx緩存服務就配置完

成了,下面我們看一下如何實作動靜分離。

3.Nginx将請求實作動靜分離

首先,我們來說一下我們要實作的效果,上面我們已經将靜态内容緩存在nginx伺服器上,我

們想讓使用者請求的靜态内容到nginx去取,動态内容到tomcat伺服器上去取,這就能實作動靜

分享效果。同樣的首先我們來修改配置檔案,

max_size=1G;

  upstream backend {

  index index.jsp index.html;

    location ~* "\.(jsp|do)$" { #當請求的是jsp或do檔案時直接到tomcat上去取

      #proxy_pass http://192.168.18.201/;

      #proxy_pass http://backend/;

      proxy_pass http://backend;

  location = / {

    root html;

    rewrite ^/ http://192.168.18.201/index.jsp last;

  location ~* "\.(jpg|jpeg|png|gif|html|css|js)$" {

    proxy_cache_valid 200 24h;

    proxy_cache_valid 302 10m;

    add_header X-Cache-Status $upstream_cache_status;

下面我們來檢查一下配置檔案是否有誤,

下面我們來通路測試一下,

大家可以看到我們的靜态内容來自緩存,動态内容全部代理到後端的tomcat伺服器上了,說明

我們動态分離配置完成,好了到這裡我們的tomcat的基本配置與nginx反向代理tomcat的配置

就全部完成了,

Nginx502 bad gateway, 504 Gateway Time-out的徹解決方法 

VPS是256M的記憶體,CPU是四核心的,是以更多的我會在乎記憶體。而在我調試伺服器的時候通

常會遇到Nginx502 bad gateway和504 Gateway Time-out的錯誤。分析nginx.conf我發現

server和fastcgi的buffers過多,導緻fastcgi請求的數量過大,php-fpm無法及時處理而出錯。

循此思路我們可以再總體buffers不變的情況下減少請求數量,具體的ningx.conf改動細節如下

                server_names_hash_bucket_size 128;

                client_header_buffer_size 32k;

                large_client_header_buffers 1 128k;# 4 32k

                client_max_body_size 8m;

                sendfile on;

                tcp_nopush     on;

                keepalive_timeout 60;

                tcp_nodelay on;

                fastcgi_connect_timeout 300;

                fastcgi_send_timeout 300;

                fastcgi_read_timeout 300;

                fastcgi_buffer_size 128k;

                fastcgi_buffers 2 256k;#8 128

                fastcgi_busy_buffers_size 256k;

                fastcgi_temp_file_write_size 256k;

                fastcgi_intercept_errors on;

                gzip on;

                gzip_min_length  1k;

                gzip_buffers     1 64k; #4 16

                gzip_http_version 1.0;

                gzip_comp_level 2;

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

                gzip_vary on;

另外,php-fpm的預設靜态處理方式會使得php-cgi的程序長期占用記憶體而無法釋放,這也是導

緻nginx出錯的原因之一,是以可以将php-fpm的處理方式改成apache模式。

        <value name=”style”>apache-like</value>

從更改完畢到現在的測試表明上述方式的效果還是很明顯的,并沒有發現一次Nginx502 bad 

gateway或504 Gateway Time-out錯誤。當然,如果你的VPS或者伺服器的性能足夠好可以根

據具體情況不必做無謂的改動。

一般看來, 這種情況可能是由于nginx預設的fastcgi程序響應的緩沖區太小造成的, 這将導緻

fastcgi程序被挂起, 如果你的fastcgi服務對這個挂起處理的不好, 那麼最後就極有可能導緻504 

Gateway Time-out

現在的網站, 尤其某些論壇有大量的回複和很多内容的, 一個頁面甚至有幾百K

在nginx.conf裡, 加入:

fastcgi_buffers 8 128k 

當然如果您在進行某一項即時的操作, 可能需要nginx的逾時參數調大點, 例如設定成60秒:

我隻是調整了這兩個參數, 結果就是沒有再顯示那個逾時, 可以說效果不錯, 但是也可能是由于

其他的原因, 目前關于nginx的資料不是很多, 很多事情都需要長期的經驗累計才有結果, 期待您

的發現哈!

Nginx 502 Bad Gateway的含義是請求的PHP-CGI已經執行,但是由于某種原因(一般是讀取

資源的問題)沒有執行完畢而導緻PHP-CGI程序終止。

Nginx 504 Gateway Time-out的含義是所請求的網關沒有請求到,簡單來說就是沒有請求到可

以執行的PHP-CGI。

解決這兩個問題其實是需要綜合思考的,一般來說Nginx 502 Bad Gateway和php-fpm.conf的

設定有關,而Nginx 504 Gateway Time-out則是與nginx.conf的設定有關。

而正确的設定需要考慮伺服器自身的性能和訪客的數量等多重因素。

以我目前的伺服器為例子CPU是奔四1.5G的,記憶體1GB,CENTOS的系統,訪客大概是50人左

右同時線上。

但是線上的人大都需要請求PHP-CGI進行大量的資訊處理,是以我将nginx.conf設定為:

fastcgi_connect_timeout 300s;

fastcgi_send_timeout 300s;

fastcgi_read_timeout 300s;

fastcgi_buffer_size 128k;

fastcgi_buffers 8 128k;#8 128

fastcgi_busy_buffers_size 256k;

fastcgi_temp_file_write_size 256k;

fastcgi_intercept_errors on;

這裡最主要的設定是前三條,即

這裡規定了PHP-CGI的連接配接、發送和讀取的時間,300秒足夠用了,是以我的伺服器很少出現

504 Gateway Time-out這個錯誤。最關鍵的是php-fpm.conf的設定,這個會直接導緻502 Bad 

Gateway和504 Gateway Time-out。

下面我們來仔細分析一下php-fpm.conf幾個重要的參數:

php-fpm.conf有兩個至關重要的參數,一個是”max_children”,另一個是”

request_terminate_timeout”

我的兩個設定的值一個是”40″,一個是”900″,但是這個值不是通用的,而是需要自己計算的

計算的方式如下:

如果你的伺服器性能足夠好,且寬帶資源足夠充足,PHP腳本沒有系循環或BUG的話你可以直

接将”request_terminate_timeout”設定成0s。0s的含義是讓PHP-CGI一直執行下去而沒有時間

限制。而如果你做不到這一點,也就是說你的PHP-CGI可能出現某個BUG,或者你的寬帶不夠

充足或者其他的原因導緻你的PHP-CGI能夠假死那麼就建議你給”request_terminate_timeout”

賦一個值,這個值可以根據你伺服器的性能進行設定。一般來說性能越好你可以設定越高,20

分鐘-30分鐘都可以。由于我的伺服器PHP腳本需要長時間運作,有的可能會超過10分鐘是以

我設定了900秒,這樣不會導緻PHP-CGI死掉而出現502 Bad gateway這個錯誤。

而”max_children”這個值又是怎麼計算出來的呢?這個值原則上是越大越好,php-cgi的程序多

了就會處理的很快,排隊的請求就會很少。設定”max_children”也需要根據伺服器的性能進行

設定,一般來說一台伺服器正常情況下每一個php-cgi所耗費的記憶體在20M左右,是以我的”

max_children”我設定成40個,20M*40=800M也就是說在峰值的時候所有PHP-CGI所耗記憶體在

800M以内,低于我的有效記憶體1Gb。而如果我的”max_children”設定的較小,比如5-10個,那

麼php-cgi就會“很累”,處理速度也很慢,等待的時間也較長。如果長時間沒有得到處理的請求

就會出現504 Gateway Time-out這個錯誤,而正在處理的很累的那幾個php-cgi如果遇到了問

題就會出現502 Bad gateway這個錯誤。

nginx + keepalive 實作高可用負載均衡 

一、拓撲環境:

主nginx負載均衡器 192.168.166.203 

輔nginx負載均衡器 192.168.166.177

VIP位址 192.168.166.178

http://www.keepalived.org/download.html

tar -zxvf keepalived-1.2.1.tar.gz

cd keepalived-1.2.1

./configure --prefix=/usr/local/keepalived --sysconf=/etc

cp /usr/local/keepalived/etc/rc.d/init.d/keepalived /etc/rc.d/init.d/

cp /usr/local/keepalived/etc/sysconfig/keepalived /etc/sysconfig/

cp /usr/local/keepalived/sbin/keepalived /bin/

chkconfig --add keepalived

chmod 755 /etc/init.d/keepalived

chkconfig keepalived on

service keepalived start

二.修改配置檔案為以下内容: [master slave]

MASTER

vim /etc/keepalived/keepalived.conf

! Configuration File for keepalived

global_defs {

notification_email {

[email protected]

notification_email_from [email protected]

smtp_server xxx.smtp.com

smtp_connect_timeout 30

router_id LVS_DEVEL

vrrp_script Monitor_Nginx {

script "/root/monitor_nginx.sh"

interval 2

weight 2

vrrp_instance VI_1 {

state MASTER #(主機為MASTER,備用機為BACKUP)

interface eth0 #(HA監測網絡接口)

virtual_router_id 61 #(主、備機的virtual_router_id必須相同)

#mcast_src_ip 192.168.166.203 #(多點傳播的源IP,設定為本機外網IP,與VIP同一網卡)此項可

不設定

priority 90 #(主、備機取不同的優先級,主機值較大,備份機值較小,值越大優先級越高)

advert_int 1 #(VRRP Multicast廣播周期秒數)

authentication {

auth_type PASS #(VRRP認證方式)

auth_pass 1234 #(密碼)

track_script {

Monitor_Nginx #(調用nginx程序檢測腳本)

virtual_ipaddress {

192.168.166.178 #(VRRP HA虛拟位址)

###BACKUP方面隻需要修改state為BACKUP , priority比MASTER稍低就OK了

三:注:monitor_nginx.sh為監控nginx程序的腳本,内容如下

if [ "$(ps -ef | grep "nginx: master process"| grep -v grep )" == "" ]

then

/usr/local/nginx/sbin/nginx

sleep 5

killall keepalived

fi

#chmod +x monitor_nginx.sh

四.啟動keepalived

/usr/local/keepalived/sbin/keepalived -D -f /etc/keepalived/keepalived.conf

五.測試步驟

1. 通路VIP看是否能夠正常通路後端的web

2. 停止其中一個web看是否能将通路轉到另一台上

3. 停止兩台nginx上任何一個nginx程序看監控程序腳本是否會自動啟動nginx

4. 停止任何一台nginx上的keepalived程序看另一台是否接管vip

track_interface的意思是将Linux中你想監控的網絡接口卡監控起來,當其中的一塊出現故障是

keepalived都将視為路由器出現故障。

這裡請注意: virtual_router_id 61,同一組master/backup中,也就是如果你設定了多個VRRP

,同一組這個ID必須相同,不然啟動的時候主從都會把VIP給啟動了

keepalived 通過發送和接收多點傳播包中的同一個virtual_router_id 的中的成員的存活,來确定對

方的不可用,一旦檢測到對方的不可用,即會切換它的備份角色為主。

即:當真實機192.168.166.177上的keepalived 檢測到 真實機192.168.166.203上的keepalived 

不可用時,177上将使用vip:192.168.166.178對外服務并由backup角色轉變為master

keepalived+nginx實作 HA與負載均衡中keepalived負責實作HA功能,控制VIP(虛拟網絡位址)

轉移功能,nginx實作對realserver七層負載均衡功能,nginx提供代理服務和cache功能,DNS

服務可以負責前段VIP的負載均衡。

keepalived的配置

192.168.200.1 keepalived配置

smtp_server 127.0.0.1

router_id LVS_TEST_YDQ

state MASTER

interface eth0

virtual_router_id 61

priority 150

advert_int 1

auth_type PASS

auth_pass 1111

192.168.200.101/24 dev eth0 label eth0:0

vrrp_instance VI_2 {

state BACKUP

virtual_router_id 62

priority 100

auth_pass 2222

192.168.200.102/24 dev eth0 label eth0:1

vrrp_instance VI_3 {

virtual_router_id 63

priority 50

auth_pass 3333

192.168.200.103/24 dev eth0 label eth0:1

nginx配置 :

user nobody nobody;                                                          

worker_processes 1;                                                           

#error_log logs/error.log;                                                    

#error_log logs/error.log notice;                                             

error_log logs/error.log debug;                                               

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;                                              

sendfile on;                                                                  

#tcp_nopush on;                                                               

#keepalive_timeout 0;                                                         

keepalive_timeout 65;                                                         

gzip on;                                                                      

gzip_min_length 1k;                                                           

gzip_buffers 6 16k;                                                           

gzip_http_version 1.1;                                                        

gzip_comp_level 2;                                                            

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

gzip_vary on;                                                                 

# location / {                                                                

# root html;                                                                  

# index index.html index.htm;                                                 

# }                                                                           

error_page 404 /404.html;                                                     

upstream www.test.com {                                                      

server 192.168.11.37:80;                                                      

server 192.168.11.38:80;                                                      

server                                                                        

{                                                                             

listen 80;                                                                    

server_name www.test.com 192.168.166.178;                                    

index index.htm index.html;                                                   

#root /web/wwwroot;                                                           

location / {                                                                  

proxy_pass http://www.test.com;                                              

proxy_next_upstream http_500 http_502 http_503 error timeout invalid_header;  

proxy_set_header Host $host;                                                  

proxy_set_header X-Real-IP $remote_addr;                                      

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;                  

include proxy.conf;                                                           

log_format blog_test_com '$remote_addr - $remote_user [$time_local] $request '

'"$status" $body_bytes_sent "$http_referer" '                                 

access_log logs/blog_test_com;                                                

}                                            

繼續閱讀