為什麼Nginx(發音同 engine x)的性能要比Apache高得多?這得益於Nginx使用了最新的epoll(Linux 2.6內核)和kqueue(freebsd)網絡I/O模型,而Apache則使用的是傳統的select模型。

目前Linux下能夠承受高並發訪問的Squid、Memcached都採用的是epoll網絡I/O模型。
處理大量的連接的讀寫,Apache所採用的select網絡I/O模型非常低效。

下面用一個比喻來解析Apache採用的select模型和Nginx採用的epoll模型進行之間的區別:


假設你在大學讀書,住的宿舍樓有很多間房間,你的朋友要來找你。

select版宿管大媽就會帶著你的朋友挨個房間去找,直到找到你為止。

而epoll版宿管大媽會先記下每位同學的房間號,你的朋友來時,只需告訴你的朋友你住在哪個房間即可,不用親自帶著你的朋友滿大樓找人。

如果來了10000個人,都要找自己住這棟樓的同學時,select版和epoll版宿管大媽,誰的效率更高,不言自明。

同理,在高並發服務器中,輪詢I/O是最耗時間的操作之一,select和epoll的性能誰的性能更高,同樣十分明了。

官網:http://www.nginx.org/

由於 yum 內沒nginx所以先裝 epel

32位元

rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/i386/epel-release-5-4.noarch.rpm

64位元
rpm -Uvh
http://download.fedora.redhat.com/pub/epel/5/x86_64/epel-release-5-4.noarch.rpm

安裝完nginx之後 建議把epel移除,因為我OS是採用CentOS,如果你是fedora的用戶就沒差了,

可直接用rpm –e 把剛安裝的epel套件移除

yum repolist (讓yum重新生效)

yum install nginx

# 安裝spawn-fcgi
可參考
http://www.cyberciti.biz/faq/rhel-fedora-install-configure-nginx-php5/

安装php:
yum install php-pear-Net-Socket php-pear php-common php-gd php-devel php php-mbstring php-pear-Mail php-cli php-imap php-snmp php-pdo php-xml php-pear-Auth-SASL php-ldap php-pear-Net-SMTP php-mysql

安装spawn-fcgi:
yum install spawn-fcgi
mv 419.sh /etc/init.d/php_cgi 

###  419.sh 是設置php_cgi啟動的腳本 網路上google一下應該找得到

### 不然就自已做一個唄,下面的是原始碼

#!/bin/sh
#
# php-cgi - php-fastcgi swaping via  spawn-fcgi
#
# chkconfig:   - 85 15
# description:  Run php-cgi as app server
# processname: php-cgi
# config:      /etc/sysconfig/phpfastcgi (defaults RH style)
# pidfile:     /var/run/php_cgi.pid
# Note: See how to use this script :
#
http://www.cyberciti.biz/faq/rhel-fedora-install-configure-nginx-php5/
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0
spawnfcgi="/usr/bin/spawn-fcgi"
php_cgi="/usr/bin/php-cgi"
prog=$(basename $php_cgi)
server_ip=127.0.0.1
server_port=9000
server_user=nginx
server_group=nginx
server_childs=5
pidfile="/var/run/php_cgi.pid"
# do not edit, put changes in /etc/sysconfig/phpfastcgi
[ -f /etc/sysconfig/phpfastcgi ] && . /etc/sysconfig/phpfastcgi
start() {
    [ -x $php_cgi ] || exit 1
    [ -x $spawnfcgi ] || exit 2
    echo -n $"Starting $prog: "
    daemon $spawnfcgi -a ${server_ip} -p ${server_port} -u ${server_user} -g ${server_group} -P ${pidfile} -C ${server_childs} -f ${php_cgi}
    retval=$?
    echo
    return $retval
}
stop() {
    echo -n $"Stopping $prog: "
    killproc -p ${pidfile} $prog -QUIT
    retval=$?
    echo
    [ -f ${pidfile} ] && /bin/rm -f ${pidfile}
    return $retval
}
restart(){
    stop
    sleep 2
    start
}
rh_status(){
    status -p ${pidfile} $prog
}
case "$1" in
    start)
        start;;
    stop)
        stop;;
    restart)
        restart;;
    status)
        rh_status;;
    *)
        echo $"Usage: $0 {start|stop|restart|status}"
        exit 3
esac


chmod +x /etc/init.d/php_cgi
/etc/init.d/php_cgi start
chkconfig --add php_cgi
chkconfig  --level  345  php_cgi  on

============================================

測試nginx是否正常work
/usr/sbin/nginx -t

正常的話應該顯示如下
the configuration file /usr/local/webserver/nginx/conf/nginx.conf syntax is ok
the configuration file /usr/local/webserver/nginx/conf/nginx.conf was tested successfully

============================================

測試
ab -n 10000 -c 200
http://10.10.50.48:80/index.html
要執行 1000 次的 connection, 200 次的 concurrent (並行, 同時).

Time taken for tests: 總共執行花了多久的時間.(以上 1000 次共多久)

Requests per second: 每秒平均可以處理多少個 connection.

============================================
/etc/php.ini
session 的使用必須有幾個要素
(1) /etc/php.ini 的設定
session.auto_start = 0 (或1)
如果 session.auto_start = 0 則必須先執行 session_start()
如果 session.auto_start = 1 就不必執行 session_start()

============================================

設定  vim /etc/nginx/nginx.conf
############################################
#
# This is the main Nginx configuration file. 
#
# More information about the configuration options is available on
#   * the English wiki -
http://wiki.nginx.org/Main
#   * the Russian documentation - http://sysoev.ru/nginx/
#
###########################################

#----------------------------------------------------------------------
# Main Module - directives that cover basic functionality
#
#  
http://wiki.nginx.org/NginxHttpMainModule
#
#----------------------------------------------------------------------

user              nginx;

#指定工作洐生 進程數 (建議為總核心數或總核心數的二倍)
worker_processes  16;

error_log  /var/log/nginx/error.log;
#error_log  /var/log/nginx/error.log  notice;
#error_log  /var/log/nginx/error.log  info;

pid        /var/run/nginx.pid;

#----------------------------------------------------------------------
# Events Module
#
#  
http://wiki.nginx.org/NginxHttpEventsModule
#
#----------------------------------------------------------------------

events {
    #Linux 建議採用 epoll 模組,FreeBSD 建議採用 kqueue 模組
    use epoll;
    #允許連接數
    worker_connections  300000;
}

#----------------------------------------------------------------------
# HTTP Core Module
#
#  
http://wiki.nginx.org/NginxHttpCoreModule
#
#----------------------------------------------------------------------

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    server_tokens off;     #關閉版本顯示
    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  /var/log/nginx/access.log  main;

#設定請求緩衝 size limits
    client_header_timeout  3m;
    client_body_timeout    3m;
    send_timeout           3m;
    client_header_buffer_size    1k;
    large_client_header_buffers  4 4k;
#啟用網頁壓縮
    gzip on;
    gzip_min_length  1100;
    gzip_buffers     4 8k;
    gzip_types       text/plain text/html text/css image/x-icon image/bmp;
    output_buffers   1 32k;
    postpone_output  1460;
    sendfile         on;
    tcp_nopush       on;
    tcp_nodelay      on;
    #send_lowat       12000;
    #keepalive_timeout  75 20;
    keepalive_timeout  0;

#lingering_time     30;
#lingering_timeout  10;
#reset_timedout_connection  on;

    #sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    #keepalive_timeout  65;

    #gzip  on;
    #
    # The default server
    #
    server {
        listen       80;
        server_name  _;

        charset en_US.UTF-8;

        #access_log  logs/host.access.log  main;

        location / {
            root   /var/www/html;
            index  index.html index.htm;
        }
    #設定查看Nginx狀態的地址    

#http://210.242.195.82/NginxStatus/ 即可看到類似如下內容:
#Active connections: 328
#server accepts handled requests
#9309 8982 28890
#Reading: 1 Writing: 3 Waiting: 324

#第一行表示現在活躍的連接數

#第三行的第三個數字表示Nginx運行到當前時間接受到的總請求數,假如快達到了上限,就需要加大上限值#了。
#在服务器使用htpasswd生成密码
#htpasswd -bd nginx_passwd username password
#ex:
#需先touch 一個 nginx_passwd 文件
#htpasswd -bd nginx_passwd nginx 123456

        location /NginxStatus {
        stub_status             on;
        access_log              on;
        auth_basic              "NginxStatus";
        #auth_basic_user_file  /etc/nginx/htpasswd;
        }

        # redirect server error pages to the static pag

#加入這筆 405 可解決post問題
    error_page 405 = $uri;

        error_page  404              /404.html;
        location = /404.html {
            root   /usr/share/nginx/html;
        }

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/share/nginx/html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass  
http://127.0.0.1;
        #}

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

            location ~ \.php$ {
            root           html ;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        location ~ /\.ht {
            deny  all;
        #}
    }

    # Load config files from the /etc/nginx/conf.d directory
    include /etc/nginx/conf.d/*.conf;

}

============================================
設定virtual host  vim /etc/nginx/conf.d/
每個virtual host 設定一設定  只要 /etc/nginx/nginx.conf中 有 include /etc/nginx/conf.d/*.conf; 它就會自動把 virtual host設定載入

============================================

要讓virtual host 支援php
則必需在conf.d中的每個virtualhost設定檔加入 (目前我測的結果是醬子我想應該有更好的方法>.<)
server {
        listen 80;
        server_name test.com.tw;
        access_log /var/log/nginx/test/test.access.log combined;
        error_log /var/log/nginx/test/test.error.log;
        location /
        {
        root /var/www/test.com.tw;
        index index.html index.htm index.php;
        }
       location ~ \.php$ {
            root           /var/www/test.com.tw;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }
    location ~ /\.ht {
            deny  all;
        }
        }   

============================================================

log的備份,由於nginx 不支援 cronolog只好自已寫,我是有看到有網友寫可以成功支援cronolog的方式

不過一樣我試不出來 我太弱了 = =

#!/bin/bash

# 每天0點執行
BAKLOG_LIST="/etc/nginx/baklog_list"
LOGS_PATH="/var/log/nginx/"
BAK_PATH="/etc/nginx/logs/backup_log/"
ls  $LOGS_PATH > $BAKLOG_LIST
sed -i 's/access.log/ /g' $BAKLOG_LIST
sed -i 's/error.log/ /g' $BAKLOG_LIST

if ! [ -d $BAK_PATH ];then
mkdir -p $BAK_PATH
fi

cd $LOGS_PATH
tar zcvf `date +%Y%m%d_%H`.tar.gz *
mv  ${BACKUP_PATH}*.tar.gz $BAK_PATH

rm -rf *

#重建nginx log
kill -USR1 `cat /var/run/nginx.pid`

cat $BAKLOG_LIST | while read list

do
cd $LOGS_PATH
if ! [ -d $list  ];then
mkdir -p $list
fi
done

arrow
arrow
    全站熱搜

    neo2124 發表在 痞客邦 留言(1) 人氣()