配置Nginx,完善Nginx啓動腳本

 

備忘錄:配置Nginx,完善Nginx啓動腳本
2009-04-28 16:55

#!/bin/sh
#
### see http://www.muduo.net/index.php/uid-8974-action-viewspace-itemid-310023
#
### 腳本2寫的比較完善,相比腳本1增加了在線升級及配置語法檢測功能
#
# 腳本3是根據腳本1完善過來的。由於nginx本身不能通過pipe來傳遞日誌數據,如apache那樣直接。
# 所以,在這裏通過fifo(named pipe)來將日誌數據傳遞給cronolog,再通過cronolog將日誌按照指定的格式來寫日誌文件。
# 腳本通過檢索 nginx.conf 來查找日誌文件的位置,然後通過監測該日誌文件是否爲fifo(test -p file),
# 如果不是fifo文件,則刪掉該文件,並執行 mkfifo $fife生成fifo文件。
# 通過cat $fifofile,寫入到cronolog的管道中,從而實現日誌的輪轉。基本實現了較好的功能。
# 有興趣的朋友可以把腳本2和腳本3進行整合,實現更加完美的功能 :)
#
# Modified:劉勝 <[email protected]>
# 改進0:腳本3無需依賴 start-stop-daemon 命令
# 改進1:增加 ps, test 選項
# 改進2:修改LOGDIR,日誌輪換格式 [/usr/local/nginx/logs/20071221/access.log]
# 改進3:修改LOGDIR,日誌輪換格式 [/usr/local/nginx/logs/access.log.20071221] 參考log4j日誌輪換格式
# 改進4:修復 restart時 日誌輪換失效(在d_start後執行d_cronologs命令;注意d_stop後不能執行d_killcronologs命令)
# 改進5:增加 upgrade 選項,支持在線升級
#
# chkconfig: 2345 08 99
# description: Starts, stops nginx
#
#dscription: Startup script for nginx webserver on Debian. Place in /etc/init.d and
# run 'sudo update-rc.d nginx defaults', or use the appropriate command on your
# distro.
#
# Author: Ryan Norbauer <[email protected]>
# Modified: Geoffrey Grosenbach http://topfunky.com
# Modified: chunshengster <[email protected]>

set -e

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DESC="Nginx/0.6.22"
NAME=nginx
DAEMON=/usr/local/nginx/sbin/$NAME
CONFIG=/usr/local/nginx/conf/nginx.conf
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME
#CRONOLOG=/usr/local/sbin/cronolog
CRONOLOG=cronolog
#LOGDIR=/data1/nginxlogs/%Y-%m-%d/
#LOGDIR=/usr/local/nginx/logs/%Y%m%d/
LOGDIR=/usr/local/nginx/logs
LOGEND=.%Y%m%d

# Gracefully exit if the package has been removed.
test -x $DAEMON || exit 0

#functions
d_getlogs(){
LOGS=`grep -E "[access|error]_log" $CONFIG | grep -v "#" | awk '{print $2}' | cut -d/; -f 1`
echo "d_getlogs()...ok"
}
d_mkfifo(){
echo "d_mkfifo()..."
logs=$*
#echo $logs
for log in $logs;do
   #echo "mkfifo $log";
   if test ! -p $log; then
    echo "make fifo log $log..."
    rm -v $log;
    mkfifo $log
   fi
done;
echo "d_mkfifo()...ok"
}
d_mkfifolog(){
echo "d_mkfifolog()..."
LOGS=`grep -E "[access|error]_log" $CONFIG | grep -v "#" | awk '{print $2}' | cut -d/; -f 1`
d_mkfifo $LOGS;
echo "d_mkfifolog()...ok"
}
d_cronologs(){
echo "d_cronologs()..."
LOGS=`grep -E "[access|error]_log" $CONFIG | grep -v "#" | awk '{print $2}' | cut -d/; -f 1`
#echo $LOGS
d_mkfifo $LOGS;
for log in $LOGS; do
   logname=`basename $log`
   #echo "$logname"
   #cat $log | $CRONOLOG $LOGDIR/$logname &
   #cat $log | $CRONOLOG $LOGDIR/$logname.%Y%m%d &
   cat $log | $CRONOLOG $LOGDIR/$logname$LOGEND &
done
echo "d_cronologs()...ok"
}
d_killcronologs(){
echo "d_killcronologs()..."
LOGS=`grep -E "[access|error]_log" $CONFIG | grep -v "#" | awk '{print $2}' | cut -d/; -f 1`
pids_cat=`pidof cat`
pids_cronolog=`pidof cronolog`
for pid in pids_cronolog pids_cat; do
   kill -9 $pid
done
if test -z `pidof cat` -a test -z `pidof cronolog`; then
   echo "All depended pids are killed !"
else
   echo "Not all the pids are killed !"
fi
echo "d_killcronologs()...ok"
}
d_start() {
echo "### Starting $DESC: $NAME"
$DAEMON -c $CONFIG || echo " already running"
}

d_stop() {
echo "### Stopping $DESC: $NAME"
test -f $PIDFILE && kill -QUIT `cat $PIDFILE`
}

d_reload() {
echo "### Reloading $DESC configuration ..."
kill -HUP `cat $PIDFILE` || echo " can't reload"
}
d_ps() {
ps -ef | egrep '(PID|nginx|cronolog)' | grep -v grep | grep -v ".sh"
#ps aux | egrep '(PID|nginx|cronolog)' | grep -v grep | grep -v ".sh"
}

configtest() {
#ebegin "Checking nginx' configuration"
#/usr/sbin/nginx -c /etc/nginx/nginx.conf -t
#eend $? "failed, please correct errors above"
echo "### Checking $DESC configuration..."
$DAEMON -c $CONFIG -t
}

upgrade() {
configtest || return 1
echo "### Upgrading $DESC: $NAME"
echo "### 1) Sending USR2 to old binary"
kill -USR2 `cat $PIDFILE` &>/dev/null
echo "### 2) Sleeping 3 seconds before pid-files checking"
sleep 3
if [ ! -f $PIDFILE.oldbin ]; then
   echo "### E File with old pid not found"
   return 1
fi
if [ ! -f $PIDFILE ]; then
   echo "### E New binary failed to start"
   return 1
fi
echo "### 3) Sleeping 3 seconds before WINCH"
sleep 3 ; kill -WINCH `cat $PIDFILE.oldbin`

echo "### 4) Sending QUIT to old binary"
   kill -QUIT `cat $PIDFILE.oldbin`
echo "### 5) Upgrade completed"
d_ps
sleep 3
#eend $? "Upgrade failed"
}

case "$1" in
start)
d_ps
d_start
d_cronologs
echo "."
;;
stop)
d_ps
d_stop
d_killcronologs
echo "."
;;
reload)
d_reload
echo "### Reloading $DESC: OK"
;;
restart)
echo "### Restarting $DESC: $NAME"
d_ps
d_stop;   #d_killcronologs #不能增加,否則異常退出
# One second might not be time enough for a daemon to stop,
# if this happens, d_start will fail (and dpkg will break if
# the package is being upgraded). Change the timeout if needed
# be, or change d_stop to have start-stop-daemon use --retry.
# Notice that using --retry slows down the shutdown process somewhat.
sleep 3
d_ps
d_start; d_cronologs
echo "### Restarting $DESC: OK"
        ;;
mklog)
d_mkfifolog
;;
test)
echo "### Checking $DESC configuration..."
$DAEMON -c $CONFIG -t
$DAEMON -v
;;
ps)
#d_ps
$DAEMON -v
;;
upgrade)
upgrade
echo "### Upgrade $DESC: OK"
;;
*)
echo "### Usage: $SCRIPTNAME {start|stop|restart|reload|test|ps|upgrade}" >&2
exit 3
;;
esac

d_ps

exit 1

---------

http://cache.baidu.com/c?word=cronolog%2Cnginx&url=http%3A//my%2Edonews%2Ecom/terryzhou/&p=8b2a965986cc41ac42a7f8364f48&user=baidu#baidusnap1

http://my.donews.com/terryzhou/2007/11/07/nginx-web%e6%9c%8d%e5%8a%a1%e5%99%a8/

Nginx,它的發音爲“engine X”, 是一個高性能的HTTP和反向代理服務器,同時也是一個IMAP/POP3/SMTP 代理服務器.Nginx
是由 Igor Sysoev爲俄羅斯訪問量第二的 Rambler.ru站點開發的,它已經在該站點運行超過兩年半了。直到2007年4月,俄羅 斯大約有20%左右的虛擬主機是由nignx服務或代理的。Google在線安全博客中統計nginx服務或代理了大約所有Internet虛擬主機的4%。而netcraft的統計顯示,nginx服務的主機在過去的一年裏以四倍的速度增長。短短的幾年裏,它的排名已躍進第9。(參見:http://survey.netcraft.com/Reports/200707/ )

現在,Igor 將源代碼以類BSD許可證的形式發佈。Nginx因爲它的穩定性、豐富的模塊庫、靈活的配置和低系統資源的消耗而聞名.業界一致認爲它是Apache2.2+mod_proxy_balancer的輕量級代替者,不僅是因爲響應靜態頁面的速度非常快,而且它的模塊數量達到Apache的近2/3。對proxy 和 rewrite 模塊的支持很徹底,還支持mod_fcgi、ssl 、vhosts ,適合用來做mongrel clusters的前端HTTP響應。

nginx做爲HTTP服務器,有以下幾項基本特性:
–>處理靜態文件,索引文件以及自動索引;打開文件描述符緩衝.
–>無緩存的反向代理加速,簡單的負載均衡和容錯.
–>FastCGI,簡單的負載均衡和容錯.
–>模塊化的結構。包括gzipping, byte ranges, chunked responses,以及 SSI-filter等filter。如果由FastCGI或其它代理服務器處理單頁中存在的多個SSI,則這項處理可以並行運行,而不需要相互等待。
–>支持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 (Linux2.2+),accept-filter (FreeBSD4.1+),TCP_DEFER_ACCEPT (Linux 2.4+)的支持,從而大大提高了性能。

當然,nginx還很年輕,多多少少存在一些問題,比如:
–>Nginx是俄羅斯人創建,目前文檔方面還不是很完善.因爲文檔大多是俄語,所以文檔方面這也是個障礙.
–>儘管nignx的模塊比較多,但它們還不夠完善。
–>對腳本的支持力度不夠。

這些問題,nginx的作者和社區都在努力解決,我們有理由相信nginx將繼續以高速的增長率來分享輕量級HTTP服務器市場,會有一個更美好的未來。

http://www.riceonfire.org/emiller/nginx-modules-guide.html#create_loc_conf 開發Nginx模塊
High-Level Overview of Nginx's Module Delegation
Nginx modules have three roles we'll cover:
-handlers process a request and produce output
-filters manipulate the output produced by a handler
-load-balancers choose a backend server to send a request to, when more than one backend server is eligible

http://www.phpchina.com/bbs/redirect.php?tid=45848&goto=lastpost&sid=z0PPk5
由於現在的BT下載軟件越來越多了,我們如何限制下載的併發數和速率呢?apache需要三方模塊,nginx就不用了:)
在nginx利用兩個指令即可實現:limit_zone(limit_conn) 來限制併發數,limit_rate來限制下載的速率,請看上面的配置實例.
               #Zone limit
               location / {
                   limit_conn   one 1;
                   limit_rate 20k;
               }

http://www.google.cn/trends?q=memcached%2C%2CJCS%2Coscache%2CJCache&ctab=0&hl=zh-CN&geo=all&date=all memcached,,JCS,oscache,JCache 的流行程度。
http://smallbizit.ctocio.com.cn/tips/336/7699336.shtml   大型網站架構之:Wikimedia的體系結構
關於wikimedia服務器的文章
  平臺:Apache,Linux,MySQL,PHP,Squid,LVS,Lucene搜索,分佈式對象高速緩存Memcached,Lighttpd圖像服務器
  統計信息:
  8 百萬文章,覆蓋了超過100中語言
  世界前10最繁忙的站點
  指數增長:訪問者/流量/服務器數量在每4-6個月翻倍;高峯期30000HTTP請求量;3 Gbit/s 數據流量;
  3個數據中心:坦帕[美國佛羅里達州西部港市]、阿姆斯特丹、漢城
  350個服務器,從1x P4到2x Xeon Quad-Core排列,0.5 - 16 GB內存
  大約6個人員管理
  3個不同的州設有3個羣集器

在192.168.0.82上安裝Nginx-0.6.17版
$ uname -a # Linux localhost.localdomain 2.6.9-22.EL #1 Mon Sep 19 18:20:28 EDT 2005 i686 i686 i386 GNU/Linux
//107 Linux ubuntu 2.6.22-14-server #1 SMP Sun Oct 14 23:34:23 GMT 2007 i686 GNU/Linux
//121 Linux mail.infothunder.com 2.6.9-22.ELsmp #1 SMP Mon Sep 19 18:32:14 EDT 2005 i686 i686 i386 GNU/Linux
$ cd /home/appusr/lius/src/
$ tar zxvf pcre-7.4.tar.gz
$ cd pcre-7.4
$ ./configure
$ make
# make install # root 權限
$ tar nginx-0.6.17.tar.gz
$ cd nginx-0.6.17
$ ./configure --with-md5=/usr/lib --with-sha1=/usr/lib --with-openssl=/usr/include --with-http_stub_status_module
$ make
# make install
# cp nginx.sh /usr/local/nginx/conf
# cp start-stop-daemon /usr/local/nginx/conf
# cd /usr/local/nginx/conf
# chmod +x *.sh start-stop-daemon
# vi nginx.sh # 添加當前路徑 .

# ./nginx.sh start # 【失敗,無法使用start-stop-daemon啓動】
Starting nginx-0.6.17: start-stop-daemon: /lib/tls/libc.so.6: version `GLIBC_2.4' not found (required by start-stop-daemon)
# ls -lt /lib/tls/libc*   # 版本過低,在Ubuntu中【/lib/libc.so.6 -> libc-2.6.1.so】
lrwxrwxrwx 1 root root      13 Mar 1 2007 /lib/tls/libc.so.6 -> libc-2.3.4.so
-rwxr-xr-x 1 root root 1454462 Aug 20 2005 /lib/tls/libc-2.3.4.so

http://man.chinaunix.net/linux/debian/debian_faq.html 7.2 如何升級一個運行中的程序
Debian GNU/Linux 系統的內核支持運行中替換文件.—— 我們另外提供可一個稱作start-stop-daemon 程序用於啓動時驅動進程或內核運行級別發生變化時停掉進程(如,由多用戶到單用戶模式或到關機模式).包含某個進程的軟件包安裝時,安裝腳本停止和重起進程調用用的也是這個程序.

# /usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
2007/12/06 14:44:53 [emerg] 21836#0: getpwnam("www-data") failed in /usr/local/nginx/conf/nginx.conf:3
2007/12/06 14:44:53 [emerg] 21836#0: the configuration file /usr/local/nginx/conf/nginx.conf test failed
# vi nginx.conf # 將第二行 usr www-data 修改爲 user nobody nobody;
# /usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
2007/12/06 14:49:29 [info] 21850#0: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
2007/12/06 14:49:29 [info] 21850#0: the configuration file /usr/local/nginx/conf/nginx.conf was tested successfully

http://blog.chinaunix.net/u/26862/showart_384362.html web負載均衡與反向代理之/RHEL AS4/nginx-0.5.17
# 定義啓動腳本
# /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf # 啓動81端口
# ps aux|grep nginx|grep -v grep   # 檢查ngins進程是否啓動:
# netstat -ln # 查看端口81是否存在
tcp        0      0 0.0.0.0:81                  0.0.0.0:*                   LISTEN     
# http://192.168.0.82:81/status/ # 無法訪問,修改nginx.conf 的 localtion /status部分對IP的限制;
# kill -9 nginx 《slave process的pid》
# killall -9 nginx

# 給nginxstatus做身份驗證:
# htpasswd -c htpasswd lius

查看nginxstatus:
http://192.168.0.82/nginxstatus/,輸入驗證帳號密碼,即可看到類似如下內容:
Active connections: 328
server accepts handled requests
9309 8982 28890
Reading: 1 Writing: 3 Waiting: 324
第一行表示目前活躍的連接數
第三行的第三個數字表示Nginx運行到當前時間接受到的總請求數,如果快達到了上限,就需要加大上限值了。

查看日誌:
#cd /usr/local/nginx
#tail -f logs/access.logs(查看訪問情況)


驗證Nginx功能:
-負載均衡,是否能自動恢復。。。pass http://192.168.2.107:81/test2/
-負載均衡,是否能根據特殊HTTP頭信息(如手機號),指向特點服務器。。。第三方補丁,根據url的hash來定向;
-日誌格式,是否能保存特殊HTTP頭信息。。。參考 http://blogger.org.cn/blog/more.asp?name=lhwork&id=21841
-設備配置,是否能配置/dev/shm的大小(缺省128M內存虛擬路徑)。。。手工修改方式成功,自動方式未實際測試;
-測試文件,設置從定向到php/jsp等,生成文件,通過X-Accel-Redirect返回給Nginx,使用sendfile發送。
-支持PHP腳本,通過FastCGI/spawn-fcgi
-支持Ruby腳本,通過FastCGI或者moral

http://blog.s135.com/read.php?314 Nginx 0.5.33 + PHP 5.2.5(FastCGI)搭建勝過Apache 10倍的Web服務器(第2版)

上一篇:sax2 和nvidia-setting無法調整15寸LCD顯示器分辨率的解決   下一篇:ubuntu使用中文man
http://www.cneduz.com/it/Linux/Guide/382867.html

應用程序如果遵循POSIX或者使用GLIBC(2.2和更高版本),通常使用/dev/shm作共享內存(shm_open,shm_unlink)。/dev/shm是一個臨時文件系統(tmpfs),可以從/etc/fstab中mount。因此,支持標準的參數例如"size",可以用來增加或者減少在/dev/shm上的tmpfs大小.(默認的,它的大小是系統RAM的一半)。

lius@ubuntu:/usr/local/nginx/conf$ df -k
Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/sda1              3889892   1348528   2343768 37% /
varrun                  127952       208    127744   1% /var/run
varlock                 127952         0    127952   0% /var/lock
udev                    127952        36    127916   1% /dev
devshm                  127952         0    127952   0% /dev/shm

http://blogger.org.cn/blog/more.asp?name=lhwork&id=21841 #設定日誌格式
        log_format main         '$remote_addr - $remote_user [$time_local] '
                                                '"$request" $status $bytes_sent '
                                                '"$http_referer" "$http_user_agent" '
                                                '"$gzip_ratio"';

        log_format download '$remote_addr - $remote_user [$time_local] '
                                                '"$request" $status $bytes_sent '
                                                '"$http_referer" "$http_user_agent" '
                                                '"$http_range" "$sent_http_content_range"';

日誌問題:1,記錄特殊http頭信息;2;自動切換,每天一個日誌文件。

http://cache.baidu.com/c?word=nginx%2Clog%2Cdaily&url=http%3A//linux%2Echinaunix%2Enet/bbs/archiver/%3Ftid%2D905873%2Ehtml&p=9374c64ad7c259e608e2947d514089&user=baidu
apache的rotatelogs不是很好的麼?幹嗎要自己去那麼費勁?
在apache的虛擬主機中設置:
CustomLog "|/opt/apache/bin/rotatelogs /var/log/apache/aaa/aaa_access_log-%g%m%d 86400 480" combinedio

如果你想自己寫的話,這樣的方法也許能夠參考一下(我使用的Nginx沒有apache的rotatelogs,所以自己寫個腳本,你可以參考一下):

1、crontab中設置如下
# root crontab entry:
59 23 * * *   /opt/nginx/bin/nginx-aaa.rotatelog 2>&1 > /dev/null

2、截斷腳本
## nginx-aaa.rotatelog
cd /var/log/nginx/aaa
/bin/mv aaa_access_log aaa_access_log-`/bin/date +"%y%m%d"`
/bin/kill -USR1 `/bin/cat /var/run/nginx/nginx.pid`


http://wiki.codemongers.com/NginxSimpleRubyFCGI 通過FastCGI支持Ruby的腳本;
Need a Ruby guy to step up and expand on this: Can the following be used/modified to support simple Ruby CGI?
fcgi_handler.rb http://dev.rubyonrails.org/browser/trunk/railties/lib/fcgi_handler.rb

http://wiki.codemongers.com/NginxChsHttpUpstreamRequestHashModule 根據URL進行hash選擇的負載均衡(需要第三方補丁)
本模塊由第三方提供,不包含在 Nginx 的源碼發佈版中。安裝介紹等請看 這裏.
The upstream_hash module provides simple upstream load distribution by hashing a configurable variable (e.g., the request URI, incoming HTTP headers, or some combination). Example usage:
upstream backend {
    server server1;
    server server2;
    hash   $request_uri;
}
Here, Nginx will choose server1 or server2 by hashing the request URI ($request_uri).

http://wiki.codemongers.com/NginxHttpGeoModule 通過geo定義變量
geo $geo {
    default          0;
    127.0.0.1/32     2;
    192.168.1.0/24   1;
    10.1.0.0/16      1;
}

http://wiki.codemongers.com/NginxHttpFlvStreamModule 支持特殊文件類型(flv)

http://wiki.codemongers.com/NginxChsHttpProxyModule 反向代理,加緩存(參考)
location /images/ {
    root                 /data/www;
    error_page           404 = /fetch$uri;
}
location /fetch {
    internal;
    proxy_pass           http://backend;
    proxy_store          on;
    proxy_store_access   user:rw group:rw all:r;
    proxy_temp_path      /data/temp;
    alias                /data/www;
}


http://hi.baidu.com/xilihwala/blog/item/2130b8128ccdebccc3fd7837.html 如何在反向代理中加快大文件處理
Serving Big Files with PHP/Rails faster
(1 Apache - mod_xsendfile 2 nginx - X-Accel-Redirect 3 lighttpd(lighty) - x-sendfile)
http://wiki.codemongers.com/NginxXSendfile 通過X-SendFile加速
Lighttpd has this feature and there is a mod_xsendfile for Apache2.
location /protected/ {
    internal;
    root   /some/path;
}
add_header("X-Accel-Redirect: /protected/iso.img");
X-Accel-Limit-Rate: 1024
X-Accel-Buffering: yes|no
X-Accel-Charset: utf-8
http://blog.kovyrin.net/2006/11/01/nginx-x-accel-redirect-php-rails/ Using X-Accel-Redirect Header With Nginx to Implement Controlled Downloads (with rails and php examples)

http://bianbian.lilydoc.net/index.php/technology/linux/156.html 設置多少個Nginx工作進程才合適?
搜索到原作者的話:
一般一個進程足夠了,你可以把連接數設得很大。如果有SSL、gzip這些比較消耗CPU的工作,而且是多核CPU的話,可以設爲和CPU的數量一樣。或者要處理很多很多的小文件,而且文件總大小比內存大很多的時候,也可以把進程數增加,以充分利用IO帶寬(主要似乎是IO操作有block)。
As a general rule you need the only worker with large number of worker_connections, say 10,000 or 20,000.
However, if nginx does CPU-intensive work as SSL or gzipping and you have 2 or more CPU, then you may set worker_processes to be equal to CPU number.
Besides, if you serve many static files and the total size of the files is bigger than memory, then you may increase worker_processes to utilize a full disk bandwidth.
——Igor Sysoev
經我實踐配置,多cpu+gzip+N多小文件+文件總大小大大超過內存 的環境(BBS啦~),設置爲cpu的兩倍較好。(不過一個nginx是4.3M噢)

2 Responses to “[譯]nginx的worker_processes設爲多少才合適?”

輕 Says: October 21st, 2007 at 06:25:04
在我的實際使用中(nginx+php-cgi),還是覺得CPU*1爲好
一個CPU開啓多個worker_processes的話,會導致負載瞬間狂升至20+
相反一個CPU只開一個的話,會很穩!

bianbian Says:
October 22nd, 2007 at 01:03:05
嗯,這個要根據環境調節的。我的是8個CPU的服務器。。。另外,可以修改nginx的cc make參數,把gcc的-g(debug)參數去掉。可以大大減小編譯後的bin大小。
-----------------
# nginx.conf.hh 支持根據手機號分發

user nobody nobody;
worker_processes 4;

#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;

#pid        logs/nginx.pid;


events {
    use epoll;
    worker_connections 2048;
}


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"
   "$http_x_up_calling_line_id"
   "$upstream_addr"
   $upstream_response_time '
   ;

    access_log /usr/local/nginx/logs/access.log main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout 0;
    keepalive_timeout 65;

    gzip on;

    #設定負載均衡的服務器列表
    upstream resin0 {
        server 10.28.1.35:8080 weight=5;
        server 10.28.1.37:8080 weight=1;
    }
    upstream resin1 {
        server 10.28.1.35:8080 weight=1;
        server 10.28.1.37:8080 weight=5;
    }
    upstream resin2 {
        server 10.28.1.38:8080 weight=5;
    }
    upstream resin3 {
        server 10.28.1.3:8080 weight=2;
    }

    server {
        listen       80;
        server_name localhost;

        #charset koi8-r;

        #access_log logs/host.access.log main;

        location / {
            root   /home/www/html;
            index index.html index.htm;
        }

        location /NginxStatus {
            stub_status             on;
            access_log              /usr/local/nginx/logs/NginxStatus.log;
            auth_basic              "NginxStatus";
            auth_basic_user_file    htpasswd;
        }

        #對 "/store" 啓用負載均衡
        location /store {
            if ( $http_x_up_calling_line_id ~ ^86139 ) {
                rewrite ^(/store/)(.*)$ /store139/$2 last;
            }
            if ( $http_x_up_calling_line_id ~ ^86136 ) {
                rewrite ^(/store/)(.*)$ /store136/$2 last;
            }
            rewrite ^(/store/)(.*)$ /store135/$2 last;
        }
        location /store139 {
            proxy_pass      http://resin3/store;
            include         proxy.conf;
        }
        location /store136 {
            proxy_pass      http://resin2/store;
            include         proxy.conf;
        }
        location /store135 {
            proxy_pass      http://resin1/store;
            include         proxy.conf;
        }
        location /drminf {
            proxy_pass      http://resin0/drminf;
            include         proxy.conf;
        }

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

      }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章