傳統上基於進程或線程模型架構的web服務經過每進程或每線程處理併發鏈接請求,這勢必會在網絡和I/O操做時產生阻塞,其另外一個必然結果則是對內存或CPU的利用率低下。生成一個新的進程/線程須要事先備好其運行時環境,這包括爲其分配堆內存和棧內存,以及爲其建立新的執行上下文等。這些操做都須要佔用CPU,並且過多的進程/線程還會帶來線程抖動或頻繁的上下文切換,系統性能也會由此進一步降低。
在設計的最初階段,nginx的主要着眼點就是其高性能以及對物理計算資源的高密度利用,所以其採用了不一樣的架構模型。受啓發於多種操做系統設計中基於「事件」的高級處理機制,nginx採用了模塊化、事件驅動、異步、單線程及非阻塞的架構,並大量採用了多路複用及事件通知機制。在nginx中,鏈接請求由爲數很少的幾個僅包含一個線程的進程worker以高效的迴環(run-loop)機制進行處理,而每一個worker能夠並行處理數千個的併發鏈接及請求。
若是負載以CPU密集型應用爲主,如SSL或壓縮應用,則worker數應與CPU數相同;若是負載以IO密集型爲主,如響應大量內容給客戶端,則worker數應該爲CPU個數的1.5或2倍。
Nginx會按需同時運行多個進程:一個主進程(master)和幾個工做進程(worker),配置了緩存時還會有緩存加載器進程(cache loader)和緩存管理器進程(cache manager)等。全部進程均是僅含有一個線程,並主要經過「共享內存」的機制實現進程間通訊。主進程以root用戶身份運行,而worker、cache loader和cachemanager均應以非特權用戶身份運行。
主進程主要完成以下工做:
1. 讀取並驗正配置信息;
2. 建立、綁定及關閉套接字;
3. 啓動、終止及維護worker進程的個數;
4. 無須停止服務而從新配置工做特性;
5. 控制非中斷式程序升級,啓用新的二進制程序並在須要時回滾至老版本;
6. 從新打開日誌文件,實現日誌滾動;
7. 編譯嵌入式perl腳本;
worker進程主要完成的任務包括:
1. 接收、傳入並處理來自客戶端的鏈接;
2. 提供反向代理及過濾功能;
3. nginx任何能完成的其它任務;
cache loader進程主要完成的任務包括:
1. 檢查緩存存儲中的緩存對象;
2. 使用緩存元數據創建內存數據庫;
cache manager進程的主要任務:
1. 緩存的失效及過時檢驗;
Nginx的配置有着幾個不一樣的上下文:main、http、server、upstream和location(還有實現郵件服務反向代理的mail)。配置語法的格式和定義方式遵循所謂的C風格,所以支持嵌套,還有着邏輯清晰並易於建立、閱讀和維護等優點。
Nginx的代碼是由一個核心和一系列的模塊組成, 核心主要用於提供WebServer的基本功能,以及Web和Mail反向代理的功能;還用於啓用網絡協議,建立必要的運行時環境以及確保不一樣的模塊之間平滑地進行交互。不過,大多跟協議相關的功能和某應用特有的功能都是由nginx的模塊實現的。這些功能模塊大體能夠分爲事件模塊、階段性處理器、輸出過濾器、變量處理器、協議、upstream和負載均衡幾個類別,這些共同組成了nginx的http功能。事件模塊主要用於提供OS獨立的(不一樣操做系統的事件機制有所不一樣)事件通知機制如kqueue或epoll等。協議模塊則負責實現nginx經過http、tls/ssl、smtp、pop3以及imap與對應的客戶端創建會話。
在nginx內部,進程間的通訊是經過模塊的pipeline或chain實現的;換句話說,每個功能或操做都由一個模塊來實現。例如,壓縮、經過FastCGI或uwsgi協議與upstream服務器通訊,以及與memcached創建會話等。 php
配置nginx做爲web_Server使用html
安裝nginxnode
# mkdir /data/software -pv # cd/data/software/ # wget http://nginx.org/download/nginx-1.6.2.tar.gz 安裝以前先安裝一些基本的庫和依賴包 # yum install gccgcc-c++ openssl-devel pcre pcre-develzlib zlib-devel 建立web用戶: groupadd -r nginx useradd -r -g nginx -s /bin/false -M nginx tar zxvfnginx-1.6.2.tar.gz cd nginx-1.6.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
備註:--with-pcre 若是出現異常,能夠去掉此參數嘗試mysql
make &&make install && echo "install nginx ok"
檢查配置文件:linux
/usr/sbin/nginx–t
使用-V參數查看編譯參數:nginx
/usr/sbin/nginx–V
啓動nginxc++
使用如下腳本:git
vim/etc/init.d/nginx #!/bin/sh # # nginx - thisscript 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 functionlibrary. ./etc/rc.d/init.d/functions # Sourcenetworking configuration. ./etc/sysconfig/network # Check thatnetworking 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 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 chmod +x /etc/init.d/nginx chkconfig --add nginx chkconfig nginx on service nginxstatus service nginxstart service nginxrestart
安裝MySQL(通用二進制包)web
cd/data/software/ groupadd -r mysql useradd -g mysql -r -s /sbin/nologin -M -d /mydata/data mysql chown -R mysql:mysql /mydata/data tar zxvfmysql-5.5.40-linux2.6-x86_64.tar.gz -C /usr/local/ cd /usr/local/ ln -svmysql-5.5.40-linux2.6-x86_64/ mysql cd mysql chownmysql:mysql ./ -R ./scripts/mysql_install_db --user=mysql --datadir=/mydata/data/ cpsupport-files/my-large.cnf /etc/my.cnf
編輯my.cnf在mysqld組中添加:
datadir=/mydata/data log-error=/mydata/data/mysql-error.log cpsupport-files/mysql.server /etc/rc.d/init.d/mysqld chkconfig --add mysqld chkconfig mysqld on service mysqldstart
輸出mysqld man手冊的路徑
vim/etc/man.config MANPATH/usr/local/mysql/man
輸出頭文件的路徑
ln -sv/usr/local/mysql/include /usr/local/mysql
輸出mysqld庫文件路徑
echo"/usr/loca/mysql/lib" > /etc/ld.so.conf.d/mysql.conf ldconfig -v
安裝PHP
cd/data/software/ wget http://cn2.php.net/distributions/php-5.5.18.tar.gz wget http://ncu.dl.sourceforge.net/project/mcrypt/Libmcrypt/2.5.8/libmcrypt-2.5.8.tar.gz wget http://ncu.dl.sourceforge.net/project/mhash/mhash/0.9.9.9/mhash-0.9.9.9.tar.bz2 wget http://ncu.dl.sourceforge.net/project/mcrypt/MCrypt/2.6.8/mcrypt-2.6.8.tar.gz tar zxvf libmcrypt-2.5.8.tar.gz cdlibmcrypt-2.5.8 ./configure make && make install tar jxvfmhash-0.9.9.9.tar.bz2 cd mhash-0.9.9.9 ./configure make &&make install tar zxvf mcrypt-2.6.8.tar.gz cd mcrypt-2.6.8 echo"/usr/local/lib" >> /etc/ld.so.conf && ldconfig -v ./configure vim configure 19744 # $RM "$cfgfile"
註釋掉此行
make &&make install tar zxvfphp-5.5.18.tar.gz cd php-5.5.18 ./configure--prefix=/usr/local/php --with-mysql=/usr/local/mysql --with-openssl--enable-fpm --enable-sockets --enable-sysvshm--with-mysqli=/usr/local/mysql/bin/mysql_config --enable-mbstring--with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib-dir--with-libxml-dir=/usr --enable-xml --with-mhash --with-mcrypt--with-config-file-path=/etc --with-config-file-scan-dir=/etc/php.d --with-bz2--with-curl make &&make install cpphp.ini-production /etc/php.ini cp sapi/fpm/init.d.php-fpm /etc/rc.d/init.d/php-fpm chmod +x /etc/rc.d/init.d/php-fpm chkconfig --add php-fpm chkconfig php-fpm on cp /usr/local/php/etc/php-fpm.conf.default /usr/local/php/etc/php-fpm.conf vim /usr/local/php/etc/php-fpm.conf
配置fpm的相關選項爲你所須要的值,並啓用pid文件(以下最後一行):
pm.max_children =150 pm.start_servers= 8 pm.min_spare_servers= 5 pm.max_spare_servers= 10 pid =/usr/local/php/var/run/php-fpm.pid(這個參數能夠不用) service php-fpmstart lsof -i :9000
整個PHP5和nginx
Nginx vim/etc/nginx/nginx.conf
啓用如下選項:
location ~ \.php${ root html; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; include fastcgi_params; }
並在所支持的主頁面格式中添加php格式的主頁,相似以下:
location / { root html; index index.phpindex.html index.htm; } 建立測試頁面: # mkdir -pv/website/data # cat >>/website/data/index.php <<EOF > <? > phpinfo(); > ?> > EOF Nginx.conf修改 location / { root /website/data; index index.php index.html index.htm; }
備註:這裏遇到如下問題:
問題1:
52055#0: *1 FastCGI sent in stderr: "Primary script unknown" whilereading response header from upstream
將:
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
改成:
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
nginx識別不到/scripts路徑,因此phpinfou驗證信息沒法正成經過。改爲如上就是:$document_root就是針對/website/data目錄下的php文件進行解析。
問題2:
一切正常以後發現phpininfo的頁面爲空白頁
修改vim /etc/php.ini
short_open_tag =On
訪問一切正常:
安裝xcache,爲PHP加速
cd/data/software/ wget http://xcache.lighttpd.net/pub/Releases/3.2.0/xcache-3.2.0.tar.gz tar zxvfxcache-3.2.0.tar.gz cd xcache-3.2.0 /usr/local/php/bin/phpize ./configure --enable-xcache--with-php-config=/usr/local/php/bin/php-config make &&make install mkdir -p/etc/php.d cp xcache.ini /etc/php.d/ vim /etc/php.d/xcache.ini extension = /usr/local/php/lib/php/extensions/no-debug-non-zts-20121212/xcache.so
指定具體的路徑
service php-fpmrestart
Nginx虛擬主機的配置:
server { listen 8080; server_name localhost; location /bbs { root /website; index index.html index.htmindex.php; } error_page 404 /404.html; location = /404.html { root /website/bbs; } }
這裏定義了一個虛擬主機,訪問:
http://xxx.xxx.xxx.xxx:8080/bbs,實際訪問的是:
http://xxx.xxx.xxx.xxx:8080/website/bbs目錄
404錯誤頁面重定向,能夠隱藏版本信息,正常頁面以下:須要在HTTP區域開啓:
fastcgi_intercept_errors on; 選項
而後在server中配置好:
error_page 404 /404.html; location =/404.html { root /website/bbs; }
error_page 404 /404.html; error_page 502 503 504 /50x.html; error_page 403 http://xxx.xxx.xxx.xxx/forbidden.html; # error_page 404 =@fetch; location =/404.html { root /website/bbs; }
Upstream 模塊
Upstream backup { Server www.xxx.com weight=5; Server www.xxx.com :8080 Server www.xxx.com down; #全部服務器掛了以後,會把請求交給此服務器 Ip_hash; #開啓回話保持機制 }
這裏nginx支持三種會話機制:
Round-robin
Ip_hash
Least_conn
配置nginx作反向代理服務器
這裏須要兩臺web node1 node2
配置nginx配置文件:
HTTP區域定義:
upstream webserver { server 172.16.100.101:80 weight=1; server 172.16.100.102:80 weight=1; } server { listen 80; server_name localhost; location / { proxy_pass http://webserver; } }
# nginx –t&& service nginx restart
實現負載均衡
URL重寫
以下:
Server { Listen 8080; Server_name localhost; Location / { Root html; Index index.html; Rewrite^/bbs/(.*)$ http://172.16.100.101/form/$1; } Error_page 404/404.html; Localtion =/404.html { Root html; } }
IE訪問:
http://172.16.100.128:8080/bbs/
server { listen 8080; server_name localhost; location / { root html; index index.html index.htmindex.php; rewrite^/bbs/(.*)$ /forum/$1; } }
訪問http://172.16.100.128:8080/bbs/ 跳轉到http://172.16.100.128:8080/forum
Bbs目錄不存在,這裏是實現的是本機跳轉。
Last :本次重寫完成,重啓協下一輪檢查
Break:本次重寫結束後,直接後續操做
經常使用指令使用:
alias 指令: Location /bbs/ { alias /website/bbs/; index index.html index.htm; }
訪問http://xxx.xxx.xxx.xxx/bbs/index.html重定向到
http://xxx.xxx.xxx.xxx/website/bbs/index.html;
Location指令:
Location /bbs/ { Root /website/; index index.html index.htm; }
訪問http://xxx.xxx.xxx.xxx/bbs/ 實際訪問是
http://xxx.xxx.xxx.xxx/website/bbs;
注意二者的區別
HTTP access 模塊:
Nginx緩存機制:
nginx 緩存:
cache:共享內存,存儲鍵和緩存對象元數據
磁盤空間,存儲數據
proxy_cache_path: 不能定義在server{}中
緩存目錄,子目錄級別
proxy_cache_path/nginx/cache/first level=1:2:1 keys_zone=first:20m max_size=1G; cache_manager:LRU
配置以下:
HTTP區域配置:
http { proxy_cache_path/nginx/cache/first levels=1:2:1 keys_zone=first:20m max_size=1g; } Server { add_header X-Cache "$upstream_cache_status from$server_addr"; location / { proxy_pass http://webserver; proxy_set_header Host $host; proxy_set_header X-Real-IP$remote_addr; proxy_cache first; proxy_cache_valid 200 10m } }
另外三個經常使用的緩存:
Open_log_cache:日誌緩存
Open_file_cache:
Fastcgi_cache:
壓縮功能:
gzip on; gzip_min_lenght 1000; gzip_proxied expired no-cache no-storeprivate auth; gzip_types text/plain application/xml;
nginx 實現動靜分離
upstream phpsrvs{ server 172.16.100.101:80 weight=1; server 172.16.100.102:80 weight=1; } Upstream imgsrvs{ Server 172.16.100.103:80 weight=1; Server 172.16.100.103:80 weight=1; } http { server { location / { root/web/htdocs; index index.phpindex.html; } Location ~*\.php${ Fastcgi_passhttp://phpsrvs; } Location ~*」\.(jpg|jpeg|jif|png)$」 { Proxy_passhttp://imgsrvs; } } }
安裝memcached
cd/data/software/ wget https://cloud.github.com/downloads/libevent/libevent/libevent-1.4.14b-stable.tar.gz wget http://memcached.org/files/memcached-1.4.21.tar.gz tar zxvflibevent-1.4.14b-stable.tar.gz cd libevent-1.4.14b-stable ./configure --prefix=/usr/local/libevent make && make install tar zxvfmemcached-1.4.21.tar.gz cd memcached-1.4.21 ./configure --enable-sasl--prefix=/usr/local/memcached --with-libevent=/usr/local/libevent make && make install
memcached的經常使用選項說明
-l<ip_addr>:指定進程監聽的地址;
-d: 以服務模式運行;
-u<username>:以指定的用戶身份運行memcached進程;
-m <num>:用於緩存數據的最大內存空間,單位爲MB,默認爲64MB;
-c <num>:最大支持的併發鏈接數,默認爲1024;
-p <num>: 指定監聽的TCP端口,默認爲11211;
-U <num>:指定監聽的UDP端口,默認爲11211,0表示關閉UDP端口;
-t<threads>:用於處理入站請求的最大線程數,僅在memcached編譯時開啓了支持線程纔有效;
-f <num>:設定Slab Allocator定義預先分配內存空間大小固定的塊時使用的增加因子;
-M:當內存空間不夠使用時返回錯誤信息,而不是按LRU算法利用空間;
-n: 指定最小的slab chunk大小;單位是字節;
-S: 啓用sasl進行用戶認證
啓動memcached
/usr/local/memcached/bin/memcached -m128 -n 20 -f 1.1 -vv -u nobody –d
Memcached操做:
telnet localhost 11211
add mykey 0 12 5
hello
get mykey
memcached啓動腳本:
#!/bin/bash # # Init file formemcached # # chkconfig: - 8614 # description:Distributed memory caching daemon # # processname:memcached # config:/etc/sysconfig/memcached ./etc/rc.d/init.d/functions ## Defaultvariables PORT="11211" USER="nobody" MAXCONN="1024" CACHESIZE="64" OPTIONS="" RETVAL=0 prog="/usr/local/memcached/bin/memcached" desc="Distributedmemory caching" lockfile="/var/lock/subsys/memcached" start() { echo -n $"Starting $desc(memcached): " daemon $prog -d -p $PORT -u $USER -c$MAXCONN -m $CACHESIZE -o "$OPTIONS" RETVAL=$? echo [ $RETVAL -eq 0 ] && touch$lockfile return $RETVAL } stop() { echo -n $"Shutting down $desc(memcached): " killproc $prog RETVAL=$? echo [ $RETVAL -eq 0 ] && rm -f$lockfile return $RETVAL } restart() { stop start } reload() { echo -n $"Reloading $desc ($prog):" killproc $prog -HUP RETVAL=$? echo return $RETVAL } case"$1" in start) start ;; stop) stop ;; restart) restart ;; condrestart) [ -e $lockfile ] && restart RETVAL=$? ;; reload) reload ;; status) status $prog RETVAL=$? ;; *) echo $"Usage: $0{start|stop|restart|condrestart|status}" RETVAL=1 esac exit $RETVAL chmod +x /etc/rc.d/init.d/memcached chkconfig --add memcached servicememcached start
動態修改使用內存:
# cat/etc/sysconfig/memcached PORT="11211" USER="nobody" MAXCONN="1024" CACHESIZE="128" OPTIONS=""
編輯/etc/init.d/memcached
# Defaultvariables PORT="11211" USER="nobody" MAXCONN="1024" CACHESIZE="64" OPTIONS="" [ -f/etc/sysconfig/memcached ] && ./etc/sysconfig/memcached
此行便可
安裝memcached的php擴展
cd /data/software/ wget http://pecl.php.net/get/memcache-2.2.7.tgz wget https://codeload.github.com/junstor/memadmin/zip/master tar zxvfmemcache-2.2.7.tgz cd memcache-2.2.7 /usr/local/php/bin/phpize ./configure --with-php-config=/usr/local/php/bin/php-config --enable-memcache make && make install cat /etc/php.d/memcache.ini extension =/usr/local/php/lib/php/extensions/no-debug-non-zts-20121212/memcache.so [root@localhostmemcache-2.2.7]# service php-fpm restart
測試php使用memcached
# cat/website/data/test.php <?php $mem = newMemcache; $mem->connect("127.0.0.1",11211) or die("Could notconnect"); $version =$mem->getVersion(); echo"Server's version: ".$version."<br/>\n"; $mem->set('testkey','Hello World', 0, 600) or die("Failed to save data at the memcachedserver"); echo "Storedata in the cache (data will expire in 600 seconds)<br/>\n"; $get_result =$mem->get('testkey'); echo"$get_result is from memcached server."; ?>
[root@localhostmemcache-2.2.7]#
證實PHP程序已經可使用memcached
Nginx 整個memcached
upstream webserver { server 172.16.100.101:80 weight=1; server 172.16.100.102:80 weight=1; } server { listen 80; server_name localhost; location / { set $memcached_key $uri; memcached_pass 127.0.0.1:11211; default_type text/html; error_page 404 @fallback; } location @fallback { proxy_pass http://webserver; proxy_set_header Host $host; proxy_set_header X-Real-IP$remote_addr; }
配置memadmin-master
unzipmemadmin-master.zip mv memadmin-master /website/data/memadmin http://172.16.100.128:8080/memadmin
配置memcached緩存mysqld數據
Memcached 和MySQL都已經安裝完成
CREATE DATABASEmem_test; USE men_test; CREATE TABLE mem( id int(7) NOT NULL AUTO_INCREMENT, name char(8) DEFAULT NULL, PRIMARY KEY(id) ) ENGINE=innodb AUTO_INCREMENT=10 DEFAULT CHARSET=utf8; INSERT INTOmem VALUES(1,'tome'),(2,'james'),(3,'jack'),(4,'mary'),(5,'zhang'),(6,'lisi'),(7,'wangwu'),(8,'hello'),(9,'huhu'); GRANT SELECT ON mem.* to memcache@'%' IDENTIFIED BY '123456'; FLUSH PRIVILEGES;
建立PHP測試頁面:
# cat/website/data/memcache.php <?php $memcachehost ='127.0.0.1'; $memcacheport =11211; $memcachelife =60; $memcache = newMemcache; $memcache->connect($memcachehost,$memcacheport)or die ("Could not connect"); $query="select* from mem limit 10"; $key=md5($query); if(!$memcache->get($key)) { $conn=mysql_connect("127.0.0.1","memcache","12345"); mysql_select_db(memcache_test); $result=mysql_query($query); while($row=mysql_fetch_assoc($result)) { $arr[]=$row; } $f = 'mysql'; $memcache->add($key,serialize($arr),0,30); $data = $arr ; } else{ $f = 'memcache'; $data_mem=$memcache->get($key); $data = unserialize($data_mem); } echo $f; echo"<br>"; echo"$key"; echo"<br>"; //print_r($data); foreach($data as$a) { echo "number is<b><font color=#FF0000>$a[id]</font></b>"; echo "<br>"; echo "name is<b><font color=#FF0000>$a[name]</font></b>"; echo "<br>"; } ?>
[root@localhostdata]#