監控
nginx有自帶的監控模塊,編譯nginx的時候,加上參數 --with-http_stub_status_module
#配置指令
./configure --prefix=/usr/local
--user=nginx
--group=nginx
--with-http_ssl_module
--with-http_realip_module
--http-client-body-temp-path=/usr/local/var/tmp/nginx/client
--http-proxy-temp-path=/usr/local/var/tmp/nginx/proxy
--http-fastcgi-temp-path=/usr/local/var/tmp/nginx/fcgi
--http-scgi-temp-path=/usr/local/var/tmp/nginx/scgi
--http-uwsgi-temp-path=/usr/local/var/tmp/nginx/uwsgi
--with-http_geoip_module
--with-http_stub_status_module
然後修改nginx配置文件,添加監控狀態配置
location = /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
那麼訪問nginx的狀態,就可以通過 curl 127.0.0.1/nginx_status訪問了
很簡單的一個模塊,除了這個還有外部的工具比如:ngxtop監控請求信息
ngxtop 安裝:
安裝python-pip
yum install epel-release
yum install python-pip
安裝ngxtop
pip install ngxtop
常用指令如下:
ngxtop
ngxtop top remote_addr 查看訪問最多的IP
ngxtop -i 'status >= 400' print request status http_referer 列出4xx or 5xx 的相應
指定配置文件:ngxtop -c /etc/nginx/nginx.conf
查詢狀態是200:ngxtop -c /etc/nginx/nginx.conf -i 'status==200'
查詢訪問最多ip:ngxtop -c /etc/nginx/nginx.conf -g remote_addr
還有一種圖像化工具nginx-rrd,但是需要和php整合,感興趣的自行研究啊
我常乾的nginx優化
1.配置線程數和併發數
worker_processes 4 #cpu(取決於cpu的核數(如,2個四核的cpu計爲8),也可以配置成auto,讓nginx自己選擇工作線程數)
events{
worker_connections 10240;#每一個進程打開的最大連接數,包含了nginx與客戶端和nginx與upstream之間的連接(受限於操作系統)
multi_accept on; #可以一次建立多個連接
use epoll; # Linux下多路複用IO接口select/poll的增強版本,它能顯著提高程序在大量併發連接中只有少量活躍的情況下的系統CPU利用率
}
2.配置後端Server的長連接
upstream server_pool{
server localhost:8080 weight=1 max_fails=2 fail_timeout=30s;
server localhost:8081 weight=1 max_fails=2 fail_timeout=30s;
keepalive 300;#300個長連接
}
location /{
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_pass http://server_pool/;
}
3.啓用緩存、壓縮。nginx的緩存我認爲還有很大的侷限性,下面是我的靜態文件壓縮配置
gzip on;
gzip_disable "msie6";
gzip_proxied any;
gzip_min_length 1000;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript;
4.操作系統優化
1》配置文件/etc/sysctl.conf,如下:
sysctl -w net.ipv4.tcp_syncookies=1 #防止一個套接字在有過多試圖連接到達時引起過載
sysctl -w net.core.somaxconn=1024 #默認128,連接隊列
sysctl -w net.ipv4.tcp_fin_timeout=10 #timewait的超時時間
sysctl -w net.ipv4.tcp_tw_reuse=1 #os直接使用timevait的連接
sysctl -w net.ipv4.tcp_tw_recycle=0 #回收禁用
2》配置文件/etc/security/limits.conf,如下:
hard nofile 204800
soft nofile 204800
soft core unlimited
soft stack 204800
5.其他優化
sendfile on; #減少文件在應用和內核之間的拷貝
tcp_nopush on; #當數據包達到一定大小再發送
tcp_nodelay off; #有數據隨時發送(只用在應答需要非常快速的情況下)
測試nginx語法是否正確:nginx -t