1. 程式人生 > >nginx監控與效能調優

nginx監控與效能調優

監控

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