1、爲何要用nginx?它和tomcat的區別又是什麼?javascript
1. 從應用方面
tomcat通常是作動態解析纔會用獲得,支持jsp的解析,須要配置JDK支持;nginx,則通常是作靜態,自己不具有動態解析功能,須要配置其餘插件或經過其餘軟件協同才具有動態功能,好比php,tomcat,或者proxypass到win2008的iis服務器作ASP的動態連接等,但nginx在靜態上的功能很是強大,
也可作訪問控制,並且能夠作成各類協議負載服務器,包括流媒體的也能夠作,具體能夠去官方網站閱讀文檔;
2. 在性能方面
若是再不作系統調優的狀況下,tomcat通常支持併發並不高100個差很少了;而nginx在靜態方面支持併發輕鬆達幾萬。
簡單的總結一下,就是二者應用領域不同,tomcat是作java等語言的動態解析,而nginx則是一款功能強大的負載軟件,配合各類插件能夠實現各類功能。php
2、Nginx工做原理css
Nginx是一款開源代碼的高性能HTTP服務器和反向代理服務器,同時支持IMAP/POP3/SMTP代理服務。Nginx由內核和模塊組成,完成工做是經過查找配置文件將客戶端請求映射到一個location block(location是用於URL匹配的命令),location配置的命令會啓動不一樣模塊完成工做。html
Nginx模塊分爲核心模塊,基礎模塊和第三方模塊。前端
核心模塊:HTTP模塊、EVENT模塊(事件)、MAIL模塊。java
基礎模塊:HTTP Access模塊、HTTP FastCGI模塊、HTTP Proxy模塊、HTTP Rewrite模塊。node
第三方模塊:HTTP Upstream Request Hash模塊、Notice模塊、HTTP Access Key模塊。nginx
3、CentOS7下安裝nginxc++
1.執行命令:mkdir temp 2.執行命令:cd temp 3.上傳文件:nginx-1.8.1.tar.gz,pcre-8.35.tar.gz,zlib-1.2.8.tar.gz 4.執行命令:yum install -y gcc gcc-c++ 5.執行命令:tar -zxvf pcre-8.35.tar.gz 6.執行命令:cd /root/temp/pcre-8.35 7.執行命令:./configure 8.執行命令:make 9.執行命令:make install 10.執行命令:cd /root/temp/ 11.執行命令:tar -zxvf zlib-1.2.8.tar.gz 12.執行命令:cd zlib-1.2.8 13.執行命令:./configure 14.執行命令:make 15.執行命令:make install 16.執行命令:cd /root/temp/ 17.執行命令:tar -zxvf nginx-1.8.1.tar.gz 18.執行命令:mkdir /usr/local/nginx 19.執行命令:cd nginx-1.8.1 20.執行命令:./configure --prefix=/usr/local/nginx/ 21.執行命令:make 22.執行命令:make install 23.執行命令:ln -s /usr/local/lib/libpcre.so.1 /lib64 24.打開防火牆80端口: -A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
啓動
啓動代碼格式:nginx安裝目錄地址 -c nginx配置文件地址
例如:
[root@libingbin sbin]# /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.confweb
啓動操做
/usr/nginx/sbin/nginx (/usr/nginx/sbin/nginx -t 查看配置信息是否正確)
中止操做
中止操做是經過向nginx進程發送信號(信號是Linux所使用的進程間通訊的最古老的方式。它是在軟件層次上對中斷機制的一種模擬,是一種異步通訊的方式 。一個完整的信號週期包括三個部分,信號的產生,信號在進程中的註冊,信號在進程中的註銷,執行信號處理函數。)來進行的。
步驟1:
查詢nginx主進程號
ps -ef | grep nginx
在進程列表裏 面找master進程,它的編號就是主進程號了。
步驟2:發送信號
從容中止Nginx:
kill -QUIT 主進程號
快速中止Nginx:
kill -TERM 主進程號
強制中止Nginx(pkill做用:經過程序的名字,直接殺死全部進程;kill做用:根據進程號殺死進程;killall做用:經過程序的名字,直接殺死全部進程;xkill做用:殺死桌面圖形界面的程序):
pkill -9 nginx
另外,若在nginx.conf配置了pid文件存放路徑則該文件存放的就是Nginx主進程號,若是沒指定則放在nginx的logs目錄下。有了pid文 件,咱們就不用先查詢Nginx的主進程號,而直接向Nginx發送信號了,命令以下:
kill -信號類型 '/usr/nginx/logs/nginx.pid'
平滑重啓
若是更改了配置就要重啓Nginx,要先關閉Nginx再打開?不是的,能夠向Nginx 發送信號,平滑重啓。
平滑重啓命令:
kill -HUP 住進稱號或進程號文件路徑
或者使用
/usr/nginx/sbin/nginx -s reload
注意,修改了配置文件後最好先檢查一下修改過的配置文件是否正 確,以避免重啓後Nginx出現錯誤影響服務器穩定運行。判斷Nginx配置是否正確命令以下:
nginx -t -c /usr/nginx/conf/nginx.conf
或者
/usr/nginx/sbin/nginx -t
4、Nginx配置文件
配置文件主要由四部分組成:main(全區設置),server(主機配置),upstream(負載均衡服務器設置),和location(URL匹配特定位置設置)。
1)全局變量
#Nginx的worker進程運行用戶以及用戶組 #user nobody nobody; #Nginx開啓的進程數 worker_processes 1; #worker_processes auto; #如下參數指定了哪一個cpu分配給哪一個進程,通常來講不用特殊指定。若是必定要設的話,用0和1指定分配方式. #這樣設就是給1-4個進程分配單獨的核來運行,出現第5個進程是就是隨機分配了。eg: #worker_processes 4 #4核CPU #worker_cpu_affinity 0001 0010 0100 1000 #定義全局錯誤日誌定義類型,[debug|info|notice|warn|crit] #error_log logs/error.log info; #指定進程ID存儲文件位置 #pid logs/nginx.pid; #一個nginx進程打開的最多文件描述符數目,理論值應該是最多打開文件數(ulimit -n)與nginx進程數相除,可是nginx分配請求並非那麼均勻,因此最好與ulimit -n的值保持一致。 #vim /etc/security/limits.conf # * soft nproc 65535 # * hard nproc 65535 # * soft nofile 65535 # * hard nofile 65535 worker_rlimit_nofile 65535;
2)事件配置
events { #use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll模型是Linux 2.6以上版本內核中的高性能網絡I/O模型,若是跑在FreeBSD上面,就用kqueue模型。 use epoll; #每一個進程能夠處理的最大鏈接數,理論上每臺nginx服務器的最大鏈接數爲worker_processes*worker_connections。理論值:worker_rlimit_nofile/worker_processes #注意:最大客戶數也由系統的可用socket鏈接數限制(~ 64K),因此設置不切實際的高沒什麼好處 worker_connections 65535; #worker工做方式:串行(必定程度下降負載,但服務器吞吐量大時,關閉使用並行方式) #multi_accept on; }
3)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"'; #定義日誌的格式。後面定義要輸出的內容。 #1.$remote_addr 與$http_x_forwarded_for 用以記錄客戶端的ip地址; #2.$remote_user :用來記錄客戶端用戶名稱; #3.$time_local :用來記錄訪問時間與時區; #4.$request :用來記錄請求的url與http協議; #5.$status :用來記錄請求狀態; #6.$body_bytes_sent :記錄發送給客戶端文件主體內容大小; #7.$http_referer :用來記錄從那個頁面連接訪問過來的; #8.$http_user_agent :記錄客戶端瀏覽器的相關信息 #鏈接日誌的路徑,指定的日誌格式放在最後。 #access_log logs/access.log main; #只記錄更爲嚴重的錯誤日誌,減小IO壓力 error_log logs/error.log crit; #關閉日誌 #access_log off; #默認編碼 #charset utf-8; #服務器名字的hash表大小 server_names_hash_bucket_size 128; #客戶端請求單個文件的最大字節數 client_max_body_size 8m; #指定來自客戶端請求頭的hearerbuffer大小 client_header_buffer_size 32k; #指定客戶端請求中較大的消息頭的緩存最大數量和大小。 large_client_header_buffers 4 64k; #開啓高效傳輸模式。 sendfile on; #防止網絡阻塞 tcp_nopush on; tcp_nodelay on; #客戶端鏈接超時時間,單位是秒 keepalive_timeout 60; #客戶端請求頭讀取超時時間 client_header_timeout 10; #設置客戶端請求主體讀取超時時間 client_body_timeout 10; #響應客戶端超時時間 send_timeout 10; #FastCGI相關參數是爲了改善網站的性能:減小資源佔用,提升訪問速度。 fastcgi_connect_timeout 300; fastcgi_send_timeout 300; fastcgi_read_timeout 300; fastcgi_buffer_size 64k; fastcgi_buffers 4 64k; fastcgi_busy_buffers_size 128k; fastcgi_temp_file_write_size 128k; #gzip模塊設置 #開啓gzip壓縮輸出 gzip on; #最小壓縮文件大小 gzip_min_length 1k; #壓縮緩衝區 gzip_buffers 4 16k; #壓縮版本(默認1.1,前端若是是squid2.5請使用1.0) gzip_http_version 1.0; #壓縮等級 1-9 等級越高,壓縮效果越好,節約寬帶,但CPU消耗大 gzip_comp_level 2; #壓縮類型,默認就已經包含text/html,因此下面就不用再寫了,寫上去也不會有問題,可是會有一個warn。 gzip_types text/plain application/x-javascript text/css application/xml; #前端緩存服務器緩存通過壓縮的頁面 gzip_vary on;
4)虛擬主機基本設置
#虛擬主機定義 server { #監聽端口 listen 80; #訪問域名 server_name localhost; #編碼格式,若網頁格式與此不一樣,將被自動轉碼 #charset koi8-r; #虛擬主機訪問日誌定義 #access_log logs/host.access.log main; #對URL進行匹配 location / { #訪問路徑,可相對也可絕對路徑 root html; #首頁文件。如下按順序匹配 index index.html index.htm; } #錯誤信息返回頁面 #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; } #訪問URL以.php結尾則自動轉交給127.0.0.1 # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { # proxy_pass http://127.0.0.1; #} #php腳本請求所有轉發給FastCGI處理 # 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 /scripts$fastcgi_script_name; # include fastcgi_params; #} #禁止訪問.ht頁面 (需ngx_http_access_module模塊) # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { # deny all; #} } #HTTPS虛擬主機定義 # HTTPS server # #server { # listen 443 ssl; # server_name localhost; # ssl_certificate cert.pem; # ssl_certificate_key cert.key; # ssl_session_cache shared:SSL:1m; # ssl_session_timeout 5m; # ssl_ciphers HIGH:!aNULL:!MD5; # ssl_prefer_server_ciphers on; # location / { # root html; # index index.html index.htm; # } #}
5)Nignx狀態監控
#Nginx運行狀態,StubStatus模塊獲取Nginx自啓動的工做狀態(編譯時要開啓對應功能) #location /NginxStatus { # #啓用StubStatus的工做訪問狀態 # stub_status on; # #指定StubStaus模塊的訪問日誌文件 # access_log logs/Nginxstatus.log; # #Nginx認證機制(需Apache的htpasswd命令生成) # #auth_basic "NginxStatus"; # #用來認證的密碼文件 # #auth_basic_user_file ../htpasswd; #} 訪問:http://IP/NginxStatus(測試就不加密碼驗證相關)
6)反向代理
#如下配置追加在HTTP的全局變量中 #nginx跟後端服務器鏈接超時時間(代理鏈接超時) proxy_connect_timeout 5; #後端服務器數據回傳時間(代理髮送超時) proxy_send_timeout 5; #鏈接成功後,後端服務器響應時間(代理接收超時) proxy_read_timeout 60; #設置代理服務器(nginx)保存用戶頭信息的緩衝區大小 proxy_buffer_size 16k; #proxy_buffers緩衝區,網頁平均在32k如下的話,這樣設置 proxy_buffers 4 32k; #高負荷下緩衝大小(proxy_buffers*2) proxy_busy_buffers_size 64k; #設定緩存文件夾大小,大於這個值,將從upstream服務器傳 proxy_temp_file_write_size 64k; #反向代理緩存目錄 proxy_cache_path /data/proxy/cache levels=1:2 keys_zone=cache_one:500m inactive=1d max_size=1g; #levels=1:2 設置目錄深度,第一層目錄是1個字符,第2層是2個字符 #keys_zone:設置web緩存名稱和內存緩存空間大小 #inactive:自動清除緩存文件時間。 #max_size:硬盤空間最大可以使用值。 #指定臨時緩存文件的存儲路徑(路徑需和上面路徑在同一分區) proxy_temp_path /data/proxy/temp #服務配置 server { #偵聽的80端口 listen 80; server_name localhost; location / { #反向代理緩存設置命令(proxy_cache zone|off,默認關閉因此要設置) proxy_cache cache_one; #對不一樣的狀態碼緩存不一樣時間 proxy_cache_valid 200 304 12h; #設置以什麼樣參數獲取緩存文件名 proxy_cache_key $host$uri$is_args$args; #後7端的Web服務器能夠經過X-Forwarded-For獲取用戶真實IP proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #代理設置 proxy_pass http://IP; #文件過時時間控制 expires 1d; } #配置手動清楚緩存(實現此功能需第三方模塊 ngx_cache_purge) #http://www.123.com/2017/0316/17.html訪問 #http://www.123.com/purge/2017/0316/17.html清楚URL緩存 location ~ /purge(/.*) { allow 127.0.0.1; deny all; proxy_cache_purge cache_one $host$1$is_args$args; } #設置擴展名以.jsp、.php、.jspx結尾的動態應用程序不作緩存 location ~.*\.(jsp|php|jspx)?$ { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://http://IP; }
7)負載均衡
#負載均衡服務器池 upstream my_server_pool { #調度算法 #1.輪循(默認)(weight輪循權值) #2.ip_hash:根據每一個請求訪問IP的hash結果分配。(會話保持) #3.fair:根據後端服務器響應時間最短請求。(upstream_fair模塊) #4.url_hash:根據訪問的url的hash結果分配。(需hash軟件包) #參數: #down:表示不參與負載均衡 #backup:備份服務器 #max_fails:容許最大請求錯誤次數 #fail_timeout:請求失敗後暫停服務時間。 server 192.168.1.109:80 weight=1 max_fails=2 fail_timeout=30; server 192.168.1.108:80 weight=2 max_fails=2 fail_timeout=30; } #負載均衡調用 server { ... location / { proxy_pass http://my_server_pool; } }
8)URL重寫
#根據不一樣的瀏覽器URL重寫 if($http_user_agent ~ Firefox){ rewrite ^(.*)$ /firefox/$1 break; } if($http_user_agent ~ MSIE){ rewrite ^(.*)$ /msie/$1 break; } #實現域名跳轉 location / { rewrite ^/(.*)$ https://example.com$1 permanent; }
9)IP限制
#限制IP訪問 location / { deny 192.168.0.2; allow 192.168.0.0/24; allow 192.168.1.1; deny all; }
10)Nginx相關命令
#啓動nginx nginx #關閉nginx nginx -s stop #平滑重啓 kill -HUP `cat /usr/local/nginx/logs/nginx.pid` 11)Nginx啓動腳本 #!/bin/bash #chkconfig: 2345 80 90 #description:auto_run PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin export PATH # Check if user is root if [ $(id -u) != "0" ]; then echo "Error: You must be root to run this script!\n" exit 1 fi NGINXDAEMON=/usr/local/nginx/sbin/nginx PIDFILE=/usr/local/nginx/logs/nginx.pid function_start() { echo -en "\033[32;49;1mStarting nginx......\n" echo -en "\033[39;49;0m" if [ -f $PIDFILE ]; then printf "Nginx is runing!\n" exit 1 else $NGINXDAEMON printf "Nginx is the successful start!\n" fi } function_stop() { echo -en "\033[32;49;1mStoping nginx......\n" echo -en "\033[39;49;0m" if [ -f $PIDFILE ]; then kill `cat $PIDFILE` printf "Nginx program is stoped\n" else printf "Nginx program is not runing!\n" fi } function_reload() { echo -en "\033[32;49;1mReload nginx......\n" echo -en "\033[39;49;0m" function_stop function_start } function_restart() { echo -en "\033[32;49;1mRestart nginx......\n" echo -en "\033[39;49;0m" printf "Reload Nginx configure...\n" $NGINXDAEMON -t kill -HUP `cat $PIDFILE` printf "Nginx program is reloding!\n" } function_kill() { killall nginx } function_status() { if ! ps -ef|grep -v grep|grep 'nginx:' > /dev/null 2>&1 then printf "Nginx is down!!!\n" else printf "Nginx is running now!\n" fi } if [ "$1" = "start" ]; then function_start elif [ "$1" = "stop" ]; then function_stop elif [ "$1" = "reload" ]; then function_reload elif [ "$1" = "restart" ]; then function_restart elif [ "$1" = "kill" ]; then function_kill elif [ "$1" = "status" ]; then function_status else echo -en "\033[32;49;1m Usage: nginx {start|stop|reload|restart|kill|status}\n" echo -en "\033[39;49;0m" fi
<!-- Start -->
獲知及時信息,請關注個人我的微信訂閱號:0與1的那點事
<!-- End -->