歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> 關於Linux >> 【nginx】配置文件的優化

【nginx】配置文件的優化

日期:2017/3/1 12:20:54   编辑:關於Linux
1、編譯安裝過程優化 在編譯Nginx時,默認以debug模式進行,而在debug模式下會插入很多跟蹤和ASSERT之類的信息,編譯完成後,一個Nginx要有好幾兆字節。在編譯前取消Nginx的debug模式,編譯完成後Nginx只有幾百千字節,因此可以在編譯之前,修改相關源碼,取消debug模式,具體方法如下: 在Nginx源碼文件被解壓後,找到源碼目錄下的auto/cc/gcc文件,修改如下幾行 sed -i 's@CFLAGS="$CFLAGS -g"@#CFLAGS="$CFLAGS -g"@' auto/cc/gcc 為特定的CPU指定CPU類型編譯優化 在編譯Nginx時,默認的GCC編譯參數是“-O”,要優化GCC編譯,可以使用以下兩個參數: --with-cc-opt='-O3' --with-cpu-opt=CPU #為特定的 CPU 編譯,有效的值包括:pentium, pentiumpro, pentium3, pentium4, athlon, opteron, amd64, sparc32, sparc64, ppc64 要確定CPU類型,可以通過如下命令: cat /proc/cpuinfo | grep "model name" nginx配置參數
--prefix=/usr/local/nginx \
--error-log-path=/data/logs/error/error.log \
--http-log-path=/data/logs/access/access.log \
--pid-path=/var/run/nginx/nginx.pid  \
--lock-path=/var/lock/nginx.lock \   \
--conf-path=/etc/nginx/nginx.conf \
--sbin-path=/usr/sbin/nginx \
--user=www \
--group=webgrp \
--vhost-domain=example.com \
--pro-language=php \
--with-http_ssl_module \
--with-http_realip_module \
--with-http_addition_module \
--with-http_image_filter_module \
--with-http_sub_module \
--with-http_dav_module \
--with-http_flv_module \
--with-http_mp4_module \
--with-http_gzip_static_module \
--with-http_concat_module \
--with-http_random_index_module \
--with-http_secure_link_module \
--with-http_degradation_module \
--with-http_sysguard_module \
--with-backtrace_module \
--with-http_stub_status_module \
--with-http_upstream_check_module \
--with-google_perftools_module \
--with-http_geoip_module\
--with-pcre=/usr/local/src/pcre-8.35 \
--with-http_image_filter_module\

2、隱藏版本號 在nginx配置文件的http標簽內加入“server_tokens off; ”參數,也可以放大server標簽和location標簽中 或者在源代碼中更改 src/core/nginx.h #define NGINX_VERSION "1.6.2" // 修改為想要的版本號如2.4.3 #define NGINX_VER "nginx/" 改為 Apache src/http/ngx_http_header_filter_module.c static char ngx_http_server_string[] ="Server:nginx" //改為apache
src/http/ngx_http_special_response.c
static u_char ngx_http_error_full_tail[] =
"<hr><center>" NGINX_VER "</center>" CRLF
"</body>" CRLF
"</html>" CRLF
;
  
  
static u_char ngx_http_error_tail[] =
"<hr><center>nginx</center>" CRLF
"</body>" CRLF
"</html>" CRLF
;   
//改為apache

3、利用TCMalloc優化Nginx的性能 TCMalloc的全稱為Thread-Caching Malloc,是谷歌開發的開源工具“google-perftools”中的一個成員。與標准的glibc庫的malloc相比,TCMalloc庫在內存分配效率和速度上要高很多,這在很大程度上提高了服務器在高並發情況下的性能,從而降低系統負載。下面簡單介紹如何為Nginx添加TCMalloc庫支持。 要安裝TCMalloc庫,需要安裝libunwind(32位操作系統不需要安裝)和google-perftools兩個軟件包,libunwind庫為基於64位CPU和操作系統的程序提供了基本函數調用鏈和函數調用寄存器功能。下面介紹利用TCMalloc優化Nginx的具體操作過程: centos 》 nginx 》gperftools》libunwind 依賴順序, 先安裝libunwind
cd /usr/local/src
  
wget  -c http://download.savannah.gnu.org/releases/libunwind/libunwind-1.1.tar.gz >libunwind-1.1.tar.gz
tar zxf libunwind-1.1.tar.gz
cd libunwind-1.1
  
CFLAGS=-fPIC ./configure --prefix=/usr --enable-shared
make CFLAGS=-fPIC
make CFLAGS=-fPIC install

安裝google-perftools
cd /usr/local/src
  
wget -c ftp://ftp.tw.freebsd.org/pub/ports/distfiles/gperftools-2.1.tar.gz
#wget -c http://gperftools.googlecode.com/files/google-perftools-2.1.tar.gz(現在googlecode.com被封了)
  
tar -vxzf gperftools-2.1.tar.gz
cd gperftools-2.1
  
./configure \
--prefix=/usr/local/gperftools \
--disable-cpu-profiler \
--enable-shared \
--disable-heap-profiler \
--disable-heap-checker \
--disable-dependency-tracking \
--enable-frame-pointers
  
or
  
./configure --prefix=/usr/local/gperftools  --enable-frame-pointers
  
make && make install

到這裡安裝google-perftools完成了但未生效,接下來需要使google-perftools生效 /sbin/ldconfig echo "/usr/local/lib" > /etc/ld.so.conf.d/usr_local_lib.conf ldconfig or ln -s /usr/local/gperftools/lib/* /usr/local/lib ldconfig nginx配置文件修改 google_perftools_profiles /data/www/tmp/tcmalloc; 驗證運行狀態 [root@dev http]# lsof -n | grep tcmalloc nginx 18292 www 13w REG 8,2 0 660107 /data/www/tmp/tcmalloc.18292 nginx 18293 www 15w REG 8,2 0 660109 /data/www/tmp/tcmalloc.18293 nginx 18294 www 23w REG 8,2 0 660108 /data/www/tmp/tcmalloc.18294 nginx 18295 www 25w REG 8,2 0 660110 /data/www/tmp/tcmalloc.18295 nginx 18296 www 30w REG 8,2 0 660106 /data/www/tmp/tcmalloc.18296 4、配置文件優化 nginx 進程數,建議按照cpu 數目來指定,一般為它的倍數 (如,2個四核的cpu計為8) worker_processes 8; 為每個進程分配cpu,上例中將8 個進程分配到8 個cpu,當然可以寫多個,或者將一個進程分配到多個cpu worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;//8顆cpu worker_cpu_affinity 0001 0010 0100 1000; //4顆cpu 這個指令是指當一個nginx 進程打開的最多文件描述符數目,理論值應該是最多打開文件數(ulimit -n)與nginx 進程數相除,但是nginx 分配請求並不是那麼均勻,所以最好與ulimit -n 的值保持一致,可以限制為操作系統最大的限制65535 worker_rlimit_nofile 65535; 客戶端請求頭部的緩沖區大小,這個可以根據你的系統分頁大小來設置,一般一個請求頭的大小不會超過1k,不過由於一般系統分頁都要大於1k,所以這裡設置為分頁大小,但也有client_header_buffer_size超過4k的情況,但是client_header_buffer_size該值必須設置為“系統分頁大小”的整倍數 [root@dev http]# getconf PAGESIZE 4096 client_header_buffer_size 4k; 這個將為打開文件指定緩存,默認是沒有啟用的,max 指定緩存數量,建議和打開文件數一致,inactive 是指經過多長時間文件沒被請求後刪除緩存。 open_file_cache max=65535 inactive=60s; 這個是指多長時間檢查一次緩存的有效信息 open_file_cache_valid 80s; open_file_cache 指令中的inactive 參數時間內文件的最少使用次數,如果超過這個數字,文件描述符一直是在緩存中打開的,如上例,如果有一個文件在inactive 時間內一次沒被使用,它將被移除。 open_file_cache_min_uses 1; 開啟高效文件傳輸模式,sendfile指令指定nginx是否調用sendfile函數來輸出文件,減少用戶空間到內核空間的上下文切換。對於普通應用設為 on,如果用來進行下載等應用磁盤IO重負載應用,可設置為off,以平衡磁盤與網絡I/O處理速度,降低系統的負載 sendfile on tcp_nopush on //只有在sendfile開啟模式下有效 長連接超時時間,單位是秒,這個參數很敏感,涉及浏覽器的種類、後端服務器的超時設置、操作系統的設置,可以另外起一片文章了。長連接請求大量小文件的時候,可以減少重建連接的開銷,但假如有大文件上傳,65s內沒上傳完成會導致失敗。如果設置時間過長,用戶又多,長時間保持連接會占用大量資源。 keepalive_timeout 60;#設置客戶端連接保持會話的超時時間,超過這個時間,服務器會關閉該連接。 tcp_nodelay on;#打開tcp_nodelay,在包含了keepalive參數才有效 client_header_timeout 15;#設置客戶端請求頭讀取超時時間,如果超過這個時間,客戶端還沒有發送任何數據,Nginx將返回“Request time out(408)”錯誤 client_body_timeout 15;#設置客戶端請求主體讀取超時時間,如果超過這個時間,客戶端還沒有發送任何數據,Nginx將返回“Request time out(408)”錯誤 send_timeout 15;#指定響應客戶端的超時時間。這個超過僅限於兩個連接活動之間的時間,如果超過這個時間,客戶端沒有任何活動,Nginx將會關閉連接。 允許客戶端請求的最大單文件字節數。如果有上傳較大文件,請設置它的限制值 client_max_body_size 10m 緩沖區代理緩沖用戶端請求的最大字節數 client_body_buffer_size 128k 事件處理模型優化,根據系統類型不同選擇不同的事務處理模型,選擇有“use [ kqueue | rtsig |epool |dev/pool |select |pllo ]; events { use epoll; worker_connections 65536; } Max_client=worker_processes*worker_connections fastcgi配置 fastcgi_connect_timeout 300;#指定鏈接到後端FastCGI的超時時間。 fastcgi_send_timeout 300;#向FastCGI傳送請求的超時時間,這個值是指已經完成兩次握手後向FastCGI傳送請求的超時時間。 fastcgi_read_timeout 300;#指定接收FastCGI應答的超時時間,這個值是指已經完成兩次握手後接收FastCGI應答的超時時間。 fastcgi_buffer_size 64k;#指定讀取FastCGI應答第一部分需要用多大的緩沖區,這個值表示將使用1個64KB的緩沖區讀取應答的第一部分(應答頭),可以設置為gastcgi_buffers選項指定的緩沖區大小。 fastcgi_buffers 4 64k;#指定本地需要用多少和多大的緩沖區來緩沖FastCGI的應答請求,如果一個php腳本所產生的頁面大小為256KB,那麼會分配4個64KB的緩沖區來緩存,如果頁面大小大於256KB,那麼大於256KB的部分會緩存到fastcgi_temp指定的路徑中,但是這並不是好方法,因為內存中的數據處理速度要快於磁盤。一般這個值應該為站點中php腳本所產生的頁面大小的中間值,如果站點大部分腳本所產生的頁面大小為256KB,那麼可以把這個值設置為“8 16K”、“4 64k”等。 fastcgi_busy_buffers_size 128k;#建議設置為fastcgi_buffer的兩倍,繁忙時候的buffer fastcgi_temp_file_write_size 128k;#在寫入fastcgi_temp_path時將用多大的數據庫,默認值是fastcgi_buffers的兩倍,設置上述數值設置小時若負載上來時可能報502 Bad Gateway fastcgi_cache oldboy_ngnix;#表示開啟FastCGI緩存並為其指定一個名稱。開啟緩存非常有用,可以有效降低CPU的負載,並且防止502的錯誤放生,但是開啟緩存也可能會引起其他問題,要很據具體情況選擇 fastcgi_cache_valid 200 302 1h;#用來指定應答代碼的緩存時間,實例中的值表示將2000和302應答緩存一小時,要和fastcgi_cache配合使用 fastcgi_cache_valid 301 1d;#將301應答緩存一天 fastcgi_cache_valid any 1m;#將其他應答緩存為1分鐘 fastcgi_cache_min_uses 1;#請求的數量 fastcgi_cache_path /data/ngx_fcgi_cache levels=2:2 keys_zone=ngx_fcgi_cache:512m;#定義緩存的路徑 gzip配置 gzip on;#開啟壓縮功能 gzip_min_length 1k;#設置允許壓縮的頁面最小字節數,頁面字節數從header頭的Content-Length中獲取,默認值是0,不管頁面多大都進行壓縮,建議設置成大於1K,如果小與1K可能會越壓越大。 gzip_buffers 4 32k;#壓縮緩沖區大小,表示申請4個單位為32K的內存作為壓縮結果流緩存,默認值是申請與原始數據大小相同的內存空間來存儲gzip壓縮結果。 gzip_http_version 1.1;#壓縮版本(默認1.1,前端為squid2.5時使用1.0)用於設置識別HTTP協議版本,默認是1.1,目前大部分浏覽器已經支持GZIP解壓,使用默認即可 gzip_comp_level 9;#壓縮比例,用來指定GZIP壓縮比,1壓縮比最小,處理速度最快,9壓縮比最大,傳輸速度快,但是處理慢,也比較消耗CPU資源。 gzip_types text/css text/xml application/javascript;#用來指定壓縮的類型,‘text/html’類型總是會被壓縮。 gzip_vary on;#vary header支持,改選項可以讓前端的緩存服務器緩存經過GZIP壓縮的頁面,例如用Squid緩存經過nginx壓縮的數據。 expires配置 對於圖片,CSS,JS等元素更改的機會較少,特別是圖片,這時可以將圖片設置在浏覽器本地緩存365天或更長,CSS,JS,html等代碼緩存10天,這樣用戶第一次打開頁面後,會在本地緩存上述內容,提高了以後打開的頁面加載速度,節省服務端大量貸款,此功能同apache的expires。這裡通過location,將需要緩存的擴展名列出來,然後指定緩存時間
location ~* \.(ico|jpe?g|gif|png|bmp|swf|flv)(\?[0-9]+)?$ {
    expires 30d;
    log_not_found off;
    access_log off;
}

location ~* \.(js|css)$ {
    expires 7d;
    log_not_found off;
    access_log off;
}  

location = /(favicon.ico|roboots.txt) {
    access_log off;
    log_not_found off;
}

URL訪問控制 來就應該只是資源文件,禁止指定擴展名程序被執行,例如:.php,.sh,.pl,nginx下禁止訪問資源目錄下的php程序文件
location ~ ^/images/.*\.(php|php5|.sh|.pl|.py)$
{
    deny all;
}

if ($request_method !~ ^(GET|HEAD|POST)$ ) {
    return 444;
}

location ~ ^/static/.*\.(php|php5|.sh|.pl|.py)$
{
    deny all;
}

location ~* ^/data/(attachment|avatar)/.*\.(php|php5)$
{
    deny all;
}

限制使用網站ip訪問網站 server { listen 80 default_server; server_name _; return 444; } 圖片及目錄防盜鏈 location ~* \.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ { valid_referers none blocked *.etiantian.org etiantian.org; if ($invalid_referer) { return 302 http://www.explam.com/img/nolink.jpg; } } 優雅的錯誤提示 error_page 500 501 502 503 504 http://www.example.com/error2.html; error_page 400 403 404 405 408 410 411 412 413 414 415 http://www.example.com/error1.html; 爬蟲優化,可以進行適當限速 使用tmpfs文件系統給/tmp 提高效率,部分程序切圖片操作臨時放到/tmp下,可以把tmp設置成內存文件系統,占用內存空間的,就是從內存裡拿出一塊來當磁盤用 mount -t tmpfs -o size=16m tmpfs /tmp 防DOS攻擊 限制單個ip的 req/s , conn
map $remote_addr $rt_filtered_ip {
        default $binary_remote_addr;
        1.2.3.4 "";
        4.4.4.4 "";
}

or

geo $rt_filtered_ip {
    default        $binary_remote_addr;

    127.0.0.1      "";
    192.168.1.0/24 "";
    10.1.0.0/16    "";

    ::1            "";
    2001:0db8::/32 "";

    1.2.3.4        ""
}

limit_conn_zone $binary_remote_addr zone=perip:10m;
limit_conn_zone $server_name zone=perserver:10m;
limit_conn_zone $host$uri zone=peruri:10m;
limit_req_zone $rt_filtered_ip zone=qps:10m rate=1r/s;

server {


        location = /wp-login.php {
            limit_req zone=qps burst=5 nodelay;
            limit_conn perip 10;
            limit_conn perserver 100;
            limit_rate 500k;
            include fastcgi_params;
            fastcgi_pass 127.0.0.1:9000;
        }
}

ab -n 100 -c 10 example.com/wp-login.php

$binary_remote_addr是限制同一客戶端ip地址; $server_name是限制同一server最大並發數; limit_conn為限制並發連接數; limit_rate為限制下載速度; 訪問控制 allow/deny location /nginx-status { stub_status on; access_log off; auth_basic "NginxStatus"; auth_basic_user_file /usr/local/nginx/htpasswd; allow 192.168.10.100; allow 172.29.73.0/24; deny all; } //htpasswd -c htpasswd admin 5、一個標准的配置文件 nginx.conf配置
user  www  webgrp;

worker_processes  4;
worker_cpu_affinity  0001 0010 0100 1000;
worker_rlimit_nofile    65536;

pid     /var/run/nginx.pid;
#error_log  /data/logs/error/nginx_error.log  info;
google_perftools_profiles /data/www/tmp/tcmalloc;

events
{
    use epoll;
    worker_connections  65536;
}
     
http
{
    include mime.types;
    default_type    application/octet-stream;
    charset  utf-8;

    server_names_hash_bucket_size 128;
    client_header_buffer_size 4k;
    large_client_header_buffers 4 32k;
    client_max_body_size 32m;
     
    open_file_cache max=65536 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 1;
     
    sendfile on;
    tcp_nopush on;
    keepalive_timeout 60;
    tcp_nodelay on;
    server_tokens off;
    port_in_redirect off;
             
    fastcgi_connect_timeout 600;
    fastcgi_send_timeout 600;
    fastcgi_read_timeout 600;
    fastcgi_buffer_size 64k;
    fastcgi_buffers 4 64k;
    fastcgi_busy_buffers_size 128k;
    fastcgi_temp_file_write_size 128k;
    fastcgi_temp_path /dev/shm/nginx_tmp;
    fastcgi_intercept_errors on;   
    #fastcgi_cache_path /data/www/tmp/_fcgi_cache levels=2:2 keys_zone=ngx_fcgi_cache:512m inactive=1d max_size=10g;

    #open gzip
    gzip on;
    gzip_vary on;
    gzip_min_length 1k;
    gzip_buffers 4 16k;
    gzip_http_version 1.0;
    gzip_comp_level 4;
    gzip_proxied any;
    gzip_types  text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;   
    gzip_disable "MSIE [1-6]\.(?!.*SV1)";

    #Proxy
    proxy_connect_timeout   600;
    proxy_read_timeout  600;
    proxy_send_timeout  600;
    proxy_buffer_size   16k;
    proxy_buffers   4   32k;
    proxy_busy_buffers_size 64k;
    proxy_temp_file_write_size  64k;
    proxy_cache_path /data/www/tmp/cache levels=1:2 keys_zone=Z:100m inactive=7d max_size=30g;
     
    #Limit
    limit_req_zone $binary_remote_addr  zone=xxx:10m rate=5r/s;
    limit_req_zone $binary_remote_addr  zone=qps1:1m rate=1r/s;

     
    #Log format
     
    log_format  access  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
          '"$http_user_agent"  $http_x_forwarded_for  $request_body'
                  'upstream_response_time $upstream_response_time request_time $request_time';
     
    #502_next
        upstream php_fpm_sock{
            server unix:/dev/shm/php-fpm.socket;
            server unix:/dev/shm/php-fpm-b.socket;
            server unix:/dev/shm/php-fpm-c.socket;
        }

        fastcgi_next_upstream error timeout invalid_header http_503  http_500;
     
    #cros
    add_header Access-Control-Allow-Origin *; 
    #add_header X-Cache-CFC "$upstream_cache_status - $upstream_response_time";

    server
    {
        listen 80 default;
        server_name _;
        return 444;
    }
     
    include vhosts/*.conf;
}

vhost配置
server {
    listen 80;
    server_name www.example.com example.com;
    root /data/www/www.example.com/;
    index  index.php index.html index.htm;
    access_log /data/logs/access/www.example.com_access.log access;
    error_log /data/logs/error/www.example.com_error.log crit;

    location @fobidden{
        include fastcgi_params;
        fastcgi_pass unix:php_fpm_sock;
        fastcgi_param SCRIPT_FILENAME $fastcgi_script_name;
        allow 124.112.113.242;
        deny all;
    }
     
    location /nginx_status {
            stub_status on;
            access_log   off;
        allow 124.112.113.242;
            deny all;
        }

    location = /status {
        try_files $uri $uri/ @fobidden;
    }
     
    if ($host = example.com ) {
        return 301 $scheme://www.example.com$request_uri;
    }

    location ~ /bbs/ {
        if ($host = www.example.com ) {
            rewrite ^/bbs/(.*)$ $scheme://bbs.example.com/$1 permanent;
            break;
        }
    }

    location = /application/ {
        return 302 /application/uploads/other/404-3.jpg;
    }

    location / {
        try_files $uri $uri/ /application.php?s=$uri&$args;
    }
     
    location ~* \.php($|/){
        set $script     $uri;
        set $path_info  "";
        if ($uri ~ "^(.+?\.php)(/.+)$") {
            set $script     $1;
            set $path_info  $2;
        }
        fastcgi_pass unix:php_fpm_sock;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME $document_root$script;
        fastcgi_param  SCRIPT_NAME $script;
        fastcgi_param  PATH_INFO $path_info;
        include fastcgi.conf;
        include fastcgi_params;

        #fastcgi_cache ngx_fcgi_cache;
        #fastcgi_cache_valid 200 302 1h;
        #fastcgi_cache_valid 301 1d;
        #fastcgi_cache_valid any 1m;
        #fastcgi_cache_min_uses 1;
        #fastcgi_cache_use_stale error timeout invalid_header http_500;
        #fastcgi_cache_key $scheme://$host$request_uri;

    }

    location ~* \.(ico|jpe?g|gif|png|bmp|swf|flv)(\?[0-9]+)?$ {
         
        expires 30d;
        log_not_found off;
        access_log off;
    }

    location ~* \.(js|css)$ {
        expires 7d;
        log_not_found off;
        access_log off;
    }  

    location = /(favicon.ico|roboots.txt) {
        access_log off;
        log_not_found off;
    }

    location ~* \.(htacess|svn|tar.gz|tar|zip|sql) {
        return 404;
    }

     
    #location ~* \.(gif|jpg|png|swf|flv)$ {
    #   valid_referers none blocked www.example.com example.com
    #   if ($invalid_referer) {
    #       return 404;
    #   }
    #} 

    error_page 404 500 502 /Common/tpl/404.html;
} 

6、系統內核的優化 sysctl.conf 中一部分配置
net.ipv4.tcp_max_tw_buckets = 6000
net.ipv4.ip_local_port_range = 1024 65000
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_syncookies = 1
net.core.somaxconn = 262144
net.core.netdev_max_backlog = 262144
net.ipv4.tcp_max_orphans = 262144
net.ipv4.tcp_max_syn_backlog = 262144
net.ipv4.tcp_synack_retries = 1
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_fin_timeout = 1
net.ipv4.tcp_keepalive_time = 30

下面是對實例中選項的含義進行介紹: net.ipv4.tcp_max_tw_buckets參數用來設定timewait的數量,默認是180000,這裡設為6000。 net.ipv4.ip_local_port_range選項用來設定允許系統打開的端口范圍。 net.ipv4.tcp_tw_recycle選項用於設置啟用timewait快速回收。 net.ipv4.tcp_tw_reuse選項用於設置開啟重用,允許將TIME-WAIT sockets重新用於新的TCP連接。 net.ipv4.tcp_syncookies選項用於設置開啟SYN Cookies,當出現SYN等待隊列溢出時,啟用cookies進行處理。 net.core.somaxconn選項默認值是128, 這個參數用於調節系統同時發起的tcp連接數,在高並發的請求中,默認的值可能會導致鏈接超時或者重傳,因此,需要結合並發請求數來調節此值。 net.core.netdev_max_backlog選項表示當每個網絡接口接收數據包的速率比內核處理這些包的速率快時,允許發送到隊列的數據包的最大數目。 net.ipv4.tcp_max_orphans選項用於設定系統中最多有多少個TCP套接字不被關聯到任何一個用戶文件句柄上。如果超過這個數字,孤立連接將立即被復位並打印出警告信息。這個限制只是為了防止簡單的DoS攻擊。不能過分依靠這個限制甚至人為減小這個值,更多的情況是增加這個值。 net.ipv4.tcp_max_syn_backlog選項用於記錄那些尚未收到客戶端確認信息的連接請求的最大值。對於有128MB內存的系統而言,此參數的默認值是1024,對小內存的系統則是128。 net.ipv4.tcp_synack_retries參數的值決定了內核放棄連接之前發送SYN+ACK包的數量。 net.ipv4.tcp_syn_retries選項表示在內核放棄建立連接之前發送SYN包的數量。 net.ipv4.tcp_fin_timeout選項決定了套接字保持在FIN-WAIT-2狀態的時間。默認值是60秒。正確設置這個值非常重要,有時候即使一個負載很小的Web服務器,也會出現因為大量的死套接字而產生內存溢出的風險。 net.ipv4.tcp_keepalive_time選項表示當keepalive啟用的時候,TCP發送keepalive消息的頻度。默認值是2(單位是小時)。 一個標准的配置文件
net.ipv4.ip_forward = 0
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.default.accept_source_route = 0
kernel.sysrq = 0
kernel.core_uses_pid = 1
net.ipv4.tcp_syncookies = 1
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.shmmax = 68719476736
kernel.shmall = 4294967296
net.ipv4.tcp_max_tw_buckets = 6000
net.ipv4.tcp_sack = 1
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_rmem = 4096 87380 4194304
net.ipv4.tcp_wmem = 4096 16384 4194304
net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.core.netdev_max_backlog = 262144
net.core.somaxconn = 262144
net.ipv4.tcp_max_orphans = 3276800
net.ipv4.tcp_max_syn_backlog = 262144
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_synack_retries = 1
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_mem = 94500000 915000000 927000000
net.ipv4.tcp_fin_timeout = 1
net.ipv4.tcp_keepalive_time = 30
net.ipv4.ip_local_port_range = 1024 65000

修改系統最大連接數 /etc/security/limits.conf * soft nofile 65535 * hard nofile 65535 * soft nproc 65535 * hard nproc 65535 //ulimit -SHn 65535
Copyright © Linux教程網 All Rights Reserved