Nginx优化指南+LINUX内核优化+linux连接数优化+nginx连接数优化

标签: nginx 优化 linux | 发表时间:2014-04-19 23:08 | 作者:zqtsx
出处:http://blog.csdn.net

Most setup guides for Nginx tell you the basics - apt-get a package, modify a few lines here and there, and you’ve got a web server! And, in most cases, a vanilla nginx install will work just fine for serving your website. However, if you’re REALLY trying to squeeze performance out of nginx, you’ll have to go a few steps further. In this guide, I’ll explain which settings in nginx can be fine tuned in order to optimize performance for handling a large number of clients. As a note, this isn’t a comprehensive guide for fine-tuning. It’s a breif overview of some settings that can be tuned in order to improve performance. Your mileage may vary.

Basic (Optimized) Configuration

The only file we’ll be modifying is your nginx.conf, which holds all your settings for nginx in different modules. You should be able to find nginx.conf in the /etc/nginx directory on your server. First, we’ll talk about some of the global settings, then go through each module in the file and talk about which settings will get you the best performance for a large number of clients, and why they’ll increase your performance. A completed config file can be found at the end of this post.

译者信息

大多数的Nginx安装指南告诉你如下基础知识——通过apt-get安装,修改这里或那里的几行配置,好了,你已经有了一个Web服务器了!而且,在大多数情况下,一个常规安装的nginx对你的网站来说已经能很好地工作了。然而,如果你真的想挤压出nginx的性能,你必须更深入一些。在本指南中,我将解释Nginx的那些设置可以微调,以优化处理大量客户端时的性能。需要注意一点,这不是一个全面的微调指南。这是一个简单的预览——那些可以通过微调来提高性能设置的概述。你的情况可能不同。

基本的 (优化过的)配置

我们将修改的唯一文件是 nginx.conf,其中包含Nginx不同模块的所有设置。你应该能够在服务器的 /etc/nginx目录中找到nginx.conf。首先,我们将谈论一些全局设置,然后按文件中的模块挨个来,谈一下哪些设置能够让你在大量客户端访问时拥有良好的性能,为什么它们会提高性能。本文的结尾有一个完整的配置文件。

Top Level Configs

Nginx has a few top level configuration settings that sit outside the modules in your nginx.conf file.

1 user www-data;
2 pid /var/run/nginx.pid;
3  
4 worker_processes auto;
5  
6 worker_rlimit_nofile 100000;

user and pid should be set by default - we won’t modify this, since it won’t do anything for us

worker_processes defines the number of worker processes that nginx should use when serving your website. The optimal value depends on many factors including (but not limited to) the number of CPU cores, the number of hard drives that store data, and load pattern. When in doubt, setting it to the number of available CPU cores would be a good start (the value “auto” will try to autodetect it).

worker_rlimit_nofile changes the limit on the maximum number of open files for worker processes. If this isn’t set, your OS will limit. Chances are your OS and nginx can handle more than “ulimit -a” will report, so we’ll set this high so nginx will never have an issue with “too many open files”

译者信息

高层的配置

nginx.conf文件中,Nginx中有少数的几个高级配置在模块部分之上。

1 user www-data;
2 pid /var/run/nginx.pid;
3  
4 worker_processes auto;
5  
6 worker_rlimit_nofile 100000;

userpid应该按默认设置 - 我们不会更改这些内容,因为更改与否没有什么不同。

worker_processes 定义了nginx对外提供web服务时的worder进程数。最优值取决于许多因素,包括(但不限于)CPU核的数量、存储数据的硬盘数量及负载模式。不能确定的时候,将其设置为可用的CPU内核数将是一个好的开始(设置为“auto”将尝试自动检测它)。

worker_rlimit_nofile 更改worker进程的最大打开文件数限制。如果没设置的话,这个值为操作系统的限制。设置后你的操作系统和Nginx可以处理比“ulimit -a”更多的文件,所以把这个值设高,这样nginx就不会有“too many open files”问题了。

Events Module

The events module contains all the settings for processing connections in nginx.

1 events {
2      worker_connections 2048;
3      multi_accept on;
4      use epoll;
5 }

worker_connections sets the maximum number of simultaneous connections that can be opened by a worker process. Since we bumped up worker_rlimit_nofile, we can safely set this pretty high.

Keep in mind that the maximum number of clients is also limited by the number of socket connections available on your sytem (~64k), so setting this ridiculously high won’t benefit us.

multi_accept tells nginx to accept as many connections as possible after getting a notification about a new connection

use sets which polling method we should use for multiplexing clients on to threads. If you’re using Linux 2.6+, you should use epoll. If you’re using *BSD, you should use kqueue. Wanna know more about event polling? Let Wikipedia be your guide (warning, a neckbeard and an operating systems course might be needed to understand everything)

(it’s worth noting if you don’t which polling method nginx should use, it’ll chose the best one for your OS)

译者信息

Events模块

events模块中包含nginx中所有处理连接的设置。

1 events {
2      worker_connections 2048;
3      multi_accept on;
4      use epoll;
5 }

worker_connections设置可由一个worker进程同时打开的最大连接数。如果设置了上面提到的worker_rlimit_nofile,我们可以将这个值设得很高。

记住,最大客户数也由系统的可用socket连接数限制(~ 64K),所以设置不切实际的高没什么好处。

multi_accept 告诉nginx收到一个新连接通知后接受尽可能多的连接。

use 设置用于复用客户端线程的轮询方法。如果你使用Linux 2.6+,你应该使用epoll。如果你使用*BSD,你应该使用kqueue。想知道更多有关事件轮询?看下维基百科吧(注意,想了解一切的话可能需要neckbeard和操作系统的课程基础)

(值得注意的是如果你不知道Nginx该使用哪种轮询方法的话,它会选择一个最适合你操作系统的)

HTTP Module

The HTTP module controls all the core features of nginx’s http processing. Since there are quite a few settings in here, we’ll take this one in pieces. All these settings should be in the http module, even though it won’t be specifically noted as such in the snippets.

01 http {
02  
03      server_tokens off;
04  
05      sendfile on;
06  
07      tcp_nopush on;
08      tcp_nodelay on;
09  
10      ...
11 }

server_tokens doesn’t speed up our performance any, but it turns off nginx version numbers on error pages, which is a good idea for security.

sendfile enables the use of sendfile(). sendfile() copies data between the disk and a TCP socket (or any two file descriptors). Pre-sendfile, to transfer such data we would alloc a data buffer in the user space. We would then read() to copy the data from a file in to the buffer, and write() the content of the buffer to a network. sendfile() reads the data immediately from the disk into the OS cache. Because this copying is done within the kernel, sendfile() is more efficient than the combination of read() and write() and the context switching/cache trashing that comes along with it ( read more about sendfile)

译者信息

HTTP 模块

HTTP模块控制着nginx http处理的所有核心特性。因为这里只有很少的配置,所以我们只节选配置的一小部分。所有这些设置都应该在http模块中,甚至你不会特别的注意到这段设置。

01 http {
02  
03      server_tokens off;
04  
05      sendfile on;
06  
07      tcp_nopush on;
08      tcp_nodelay on;
09  
10      ...
11 }
server_tokens 并不会让nginx执行的速度更快,但它可以关闭在错误页面中的nginx版本数字,这样对于安全性是有好处的。

sendfile可以让sendfile()发挥作用。sendfile()可以在磁盘和TCP socket之间互相拷贝数据(或任意两个文件描述符)。Pre-sendfile是传送数据之前在用户空间申请数据缓冲区。之后用read()将数据从文件拷贝到这个缓冲区,write()将缓冲区数据写入网络。sendfile()是立即将数据从磁盘读到OS缓存。因为这种拷贝是在内核完成的,sendfile()要比组合read()和write()以及打开关闭丢弃缓冲更加有效(更多有关于sendfile)

tcp_nopush tells nginx to send all header files in one packet as opposed to one by one

tcp_nodelay tells nginx not to buffer data and send data in small, short bursts - it should only be set for applications that send frequent small bursts of information without getting an immediate response, where timely delivery of data is required

1 access_log off;
2 error_log /var/log/nginx/error.log crit;

access_log sets whether or not nginx will store access logs. Turning this off increases speed by reducing disk IO (aka, YOLO)

error_log tells nginx it should only log critical errors

1 keepalive_timeout 10;
2  
3 client_header_timeout 10;
4 client_body_timeout 10;
5  
6 reset_timedout_connection on;
7 send_timeout 10;

keepalive_timeout assigns the timeout for keep-alive connections with the client. The server will close connections after this time. We’ll set it low to keep our workers from being busy for too long.

client_header_timeout and client_body_timeout sets the timeout for the request header and request body (respectively). We’ll set this low too.

译者信息

tcp_nopush 告诉nginx在一个数据包里发送所有头文件,而不一个接一个的发送

tcp_nodelay 告诉nginx不要缓存数据,而是一段一段的发送--当需要及时发送数据时,就应该给应用设置这个属性,这样发送一小块数据信息时就不能立即得到返回值。

1 access_log off;
2 error_log /var/log/nginx/error.log crit;
access_log设置nginx是否将存储访问日志。关闭这个选项可以让读取磁盘IO操作更快(aka,YOLO)

error_log 告诉nginx只能记录严重的错误

1 keepalive_timeout 10 ;
2  
3 client_header_timeout 10 ;
4 client_body_timeout 10 ;
5  
6 reset_timedout_connection on;
7 send_timeout 10 ;
keepalive_timeout 给客户端分配keep-alive链接超时时间。服务器将在这个超时时间过后关闭链接。我们将它设置低些可以让ngnix持续工作的时间更长。

client_header_timeoutclient_body_timeout 设置请求头和请求体(各自)的超时时间。我们也可以把这个设置低些。

reset_timedout_connection tells nginx to close connection on non responding client. This will free up all memory associated with that client.

send_timeout specifies the response timeout to the client. This timeout does not apply to the entire transfer, but between two subsequent client-read operations. If the client has not read any data for this amount of time, then nginx shuts down the connection.

1 limit_conn_zone $binary_remote_addr zone=addr:5m;
2 limit_conn addr 100;

limit_conn_zone sets parameters for a shared memory zone that will keep states for various keys (such as current number of connections). 5m is 5 megabytes, and should be large enough to store (32k * 5) 32-byte states or (16k * 5) 64-byte states.

limit_conn sets the maximum allowed number of connections for a given key value. The key is addr, and our value is 100, so we’ll only allow 100 concurrent connections per IP address.

1 include /etc/nginx/mime.types;
2 default_type text/html;
3 charset UTF-8;

include is just a directive to include the contents of another file in the current file. Here, we use it to load in a list of MIME types to be used later.

default_type sets the default MIME-type to be used for files

charset sets the default charset to be included in our header

译者信息

reset_timeout_connection告诉nginx关闭不响应的客户端连接。这将会释放那个客户端所占有的内存空间。

send_timeout 指定客户端的响应超时时间。这个设置不会用于整个转发器,而是在两次客户端读取操作之间。如果在这段时间内,客户端没有读取任何数据,nginx就会关闭连接。

1 limit_conn_zone $binary_remote_addr zone=addr:5m;
2 limit_conn addr 100;
limit_conn_zone设置用于保存各种key(比如当前连接数)的共享内存的参数。5m就是5兆字节,这个值应该被设置的足够大以存储(32K*5)32byte状态或者(16K*5)64byte状态。

limit_conn为给定的key设置最大连接数。这里key是addr,我们设置的值是100,也就是说我们允许每一个IP地址最多同时打开有100个连接。

1 include /etc/nginx/mime.types;
2 default_type text/html;
3 charset UTF-8;
include只是一个在当前文件中包含另一个文件内容的指令。这里我们使用它来加载稍后会用到的一系列的MIME类型。

default_type设置文件使用的默认的MIME-type。

charset设置我们的头文件中的默认的字符集

The performance improvement these two options give is explained in this great WebMasters StackExchange question.

1 gzip on;
2 gzip_disable "msie6" ;
3  
4 # gzip_static on;
5 gzip_proxied any;
6 gzip_min_length 1000;
7 gzip_comp_level 4;
8  
9 gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
gzip tells nginx to gzip the data we’re sending. This will reduce the amount of data we need to send.

gzip_disable disables gzip for specific clients. We set it to be IE6 or less for compadibility issues.

gzip_static tells nginx to look for the pre-gzip’d asset with the same name before gzipping the asset itself. This is requires you to pre-zip your files (it’s commented out for this example), but allows you to use the highest compression possible and nginx no longer has to zip those files (read more about gzip_static here)

gzip_proxied allows or disallows compression of a response based on the request/response. We’ll set it to any, so we gzip all requests.

gzip_min_length sets the minimum number of bytes necessary for us to gzip data. If a request is under 1000 bytes, we won’t bother gzipping it, since gzipping does slow down the overall process of handling a request.

gzip_comp_level sets the compression level on our data. These levesls can be anywhere from 1-9, 9 being the slowest but most compressed. We’ll set it to 4, which is a good middle ground.

gzip_types sets the type of data to gzip. There are some above, but you can add more.

01 # cache informations about file descriptors, frequently accessed files
02 # can boost performance, but you need to test those values
03 open_file_cache max=100000 inactive=20s;
04 open_file_cache_valid 30s;
05 open_file_cache_min_uses 2;
06 open_file_cache_errors on;
07  
08 ##
09 # Virtual Host Configs
10 # aka our settings for specific servers
11 ##
12  
13 include /etc/nginx/conf.d/*.conf;
14 include /etc/nginx/sites-enabled/*;
译者信息

以下两点对于性能的提升在伟大的WebMasters StackExchange中有解释。

1 gzip on;
2 gzip_disable "msie6" ;
3  
4 # gzip_static on;
5 gzip_proxied any;
6 gzip_min_length 1000;
7 gzip_comp_level 4;
8  
9 gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

gzip是告诉nginx采用gzip压缩的形式发送数据。这将会减少我们发送的数据量。

gzip_disable为指定的客户端禁用gzip功能。我们设置成IE6或者更低版本以使我们的方案能够广泛兼容。

gzip_static告诉nginx在压缩资源之前,先查找是否有预先gzip处理过的资源。这要求你预先压缩你的文件(在这个例子中被注释掉了),从而允许你使用最高压缩比,这样nginx就不用再压缩这些文件了(想要更详尽的gzip_static的信息,请点击这里)。

gzip_proxied允许或者禁止压缩基于请求和响应的响应流。我们设置为any,意味着将会压缩所有的请求。

gzip_min_length设置对数据启用压缩的最少字节数。如果一个请求小于1000字节,我们最好不要压缩它,因为压缩这些小的数据会降低处理此请求的所有进程的速度。

gzip_comp_level设置数据的压缩等级。这个等级可以是1-9之间的任意数值,9是最慢但是压缩比最大的。我们设置为4,这是一个比较折中的设置。

gzip_type设置需要压缩的数据格式。上面例子中已经有一些了,你也可以再添加更多的格式。

01 # cache informations about file descriptors, frequently accessed files
02 # can boost performance, but you need to test those values
03 open_file_cache max=100000 inactive=20s;
04 open_file_cache_valid 30s;
05 open_file_cache_min_uses 2;
06 open_file_cache_errors on;
07  
08 ##
09 # Virtual Host Configs
10 # aka our settings for specific servers
11 ##
12  
13 include /etc/nginx/conf.d/*.conf;
14 include /etc/nginx/sites-enabled/*;
open_file_cache both turns on cache activity and specifies the maximum number of entries in the cache, along with how long to cache them. We’ll set our maximum to a relatively high number, and we’ll get rid of them from the cache if they’re inactive for 20 seconds.

open_file_cache_valid specifies interval for when to check the validity of the information about the item in open_file_cache

open_file_cache_min_uses defines the minimum use number of a file within the time specified in the directive parameter inactive in open_file_cache

open_file_cache_errors specifies whether or not to cache errors when searching for a file

Include is again used to add some files to our config. We’re including our server modules, defined in a different file. If your server modules aren’t at these locations, you should modify this line to point at the correct location.

译者信息

open_file_cache打开缓存的同时也指定了缓存最大数目,以及缓存的时间。我们可以设置一个相对高的最大时间,这样我们可以在它们不活动超过20秒后清除掉。

open_file_cache_valid 在open_file_cache中指定检测正确信息的间隔时间。

open_file_cache_min_uses 定义了open_file_cache中指令参数不活动时间期间里最小的文件数。

open_file_cache_errors指定了当搜索一个文件时是否缓存错误信息,也包括再次给配置中添加文件。我们也包括了服务器模块,这些是在不同文件中定义的。如果你的服务器模块不在这些位置,你就得修改这一行来指定正确的位置。

The full config file

01 user www-data;
02 pid /var/run/nginx.pid;
03 worker_processes auto;
04 worker_rlimit_nofile 100000;
05  
06 events {
07      worker_connections 2048;
08      multi_accept on;
09      use epoll;
10 }
11  
12 http {
13      server_tokens off;
14      sendfile on;
15      tcp_nopush on;
16      tcp_nodelay on;
17  
18      access_log off;
19      error_log /var/log/nginx/error.log crit;
20  
21      keepalive_timeout 10;
22      client_header_timeout 10;
23      client_body_timeout 10;
24      reset_timedout_connection on;
25      send_timeout 10;
26  
27      limit_conn_zone $binary_remote_addr zone=addr:5m;
28      limit_conn addr 100;
29  
30      include /etc/nginx/mime.types;
31      default_type text/html;
32      charset UTF-8;
33  
34      gzip on;
35      gzip_disable "msie6" ;
36      gzip_proxied any;
37      gzip_min_length 1000;
38      gzip_comp_level 6;
39      gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
40  
41      open_file_cache max=100000 inactive=20s;
42      open_file_cache_valid 30s;
43      open_file_cache_min_uses 2;
44      open_file_cache_errors on;
45  
46      include /etc/nginx/conf.d/*.conf;
47      include /etc/nginx/sites-enabled/*;
48 }
After editing your config, make sure to restart nginx in order to have it use our new configuration file

sudo service nginx restart

Takeaway

There we go! Your web server is now ready to do battle with the army of visitors that previously plagued you. This is by no means the only way you can go about speeding up your website. I’ll be writing more posts that explain other ways to speed up your website soon.

译者信息

一个完整的配置

01 user www-data;
02 pid /var/run/nginx.pid;
03 worker_processes auto;
04 worker_rlimit_nofile 100000;
05  
06 events {
07      worker_connections 2048;
08      multi_accept on;
09      use epoll;
10 }
11  
12 http {
13      server_tokens off;
14      sendfile on;
15      tcp_nopush on;
16      tcp_nodelay on;
17  
18      access_log off;
19      error_log /var/log/nginx/error.log crit;
20  
21      keepalive_timeout 10;
22      client_header_timeout 10;
23      client_body_timeout 10;
24      reset_timedout_connection on;
25      send_timeout 10;
26  
27      limit_conn_zone $binary_remote_addr zone=addr:5m;
28      limit_conn addr 100;
29  
30      include /etc/nginx/mime.types;
31      default_type text/html;
32      charset UTF-8;
33  
34      gzip on;
35      gzip_disable "msie6" ;
36      gzip_proxied any;
37      gzip_min_length 1000;
38      gzip_comp_level 6;
39      gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
40  
41      open_file_cache max=100000 inactive=20s;
42      open_file_cache_valid 30s;
43      open_file_cache_min_uses 2;
44      open_file_cache_errors on;
45  
46      include /etc/nginx/conf.d/*.conf;
47      include /etc/nginx/sites-enabled/*;
48 }

编辑完配置后,确认重启nginx使设置生效。

sudo service nginx restart

后记

就这样!你的Web服务器现在已经就绪,之前困扰你的众多访问者的问题来吧。这并不是加速网站的唯一途径,很快我会写更多介绍其他加速网站方法的文章的。




笔者对NGINX的理会:
一般来说nginx 配置文件中对优化比较有作用的为以下几项:

1.  worker_processes 8;

nginx 进程数,建议按照cpu 数目来指定,一般为它的倍数 (如,2个四核的cpu计为8)。

2.  worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;

为每个进程分配cpu,上例中将8 个进程分配到8 个cpu,当然可以写多个,或者将一
个进程分配到多个cpu。

3.  worker_rlimit_nofile 65535;

这个指令是指当一个nginx 进程打开的最多文件描述符数目,理论值应该是最多打开文
件数(ulimit -n)与nginx 进程数相除,但是nginx 分配请求并不是那么均匀,所以最好与ulimit -n 的值保持一致。

现在在linux 2.6内核下开启文件打开数为65535,worker_rlimit_nofile就相应应该填写65535。

这是因为nginx调度时分配请求到进程并不是那么的均衡,所以假如填写10240,总并发量达到3-4万时就有进程可能超过10240了,这时会返回502错误。

查看linux系统文件描述符的方法:

[root@web001 ~]# sysctl -a | grep fs.file

fs.file-max = 789972

fs.file-nr = 510 0 789972

4.  use epoll;

使用epoll 的I/O 模型

(

补充说明:

与apache相类,nginx针对不同的操作系统,有不同的事件模型

      A)标准事件模型
       Select、poll属于标准事件模型,如果当前系统不存在更有效的方法,nginx会选择select或poll
      B)高效事件模型   
Kqueue:使用于 FreeBSD 4.1+, OpenBSD 2.9+, NetBSD 2.0 和 MacOS X. 使用双处理器的MacOS X系统使用kqueue可能会造成内核崩溃。
Epoll: 使用于Linux内核2.6版本及以后的系统。

/dev/poll:使用于 Solaris 7 11/99+, HP/UX 11.22+ (eventport), IRIX 6.5.15+ 和 Tru64 UNIX 5.1A+。

        Eventport:使用于 Solaris 10. 为了防止出现内核崩溃的问题, 有必要安装安全补丁。

)

5.  worker_connections 65535;

每个进程允许的最多连接数, 理论上每台nginx 服务器的最大连接数为worker_processes*worker_connections。

6.  keepalive_timeout 60;

keepalive 超时时间。

7.  client_header_buffer_size 4k;

客户端请求头部的缓冲区大小,这个可以根据你的系统分页大小来设置,一般一个请求头的大小不会超过1k,不过由于一般系统分页都要大于1k,所以这里设置为分页大小。 

分页大小可以用命令 getconf PAGESIZE 取得。

[root@web001 ~]# getconf PAGESIZE 

4096

但也有client_header_buffer_size超过4k的情况,但是client_header_buffer_size该值必须设置为 “系统分页大小”的整倍数。

8.  open_file_cache max=65535 inactive=60s;

这个将为打开文件指定缓存,默认是没有启用的,max 指定缓存数量,建议和打开文件数一致,inactive 是指经过多长时间文件没被请求后删除缓存。

9.  open_file_cache_valid 80s;

这个是指多长时间检查一次缓存的有效信息。

10.  open_file_cache_min_uses 1;

open_file_cache 指令中的inactive 参数时间内文件的最少使用次数,如果超过这个数字,文件描述符一直是在缓存中打开的,如上例,如果有一个文件在inactive 时间内一次没被使用,它将被移除。


测试NGINX 是否支持 GZIP  命令行检测如下(替换成自己的地址,本地可直接输入本地IP即可):

curl -I -H "Accept-Encoding: gzip, deflate"  "http://www.baidu.com"  //测试页面

curl -I -H "Accept-Encoding: gzip, deflate"  "http://www.baidu.com/xxx.gif"  //测试图片

curl -I -H "Accept-Encoding: gzip, deflate"  "http://www.baidu.com/xxx.js"   //测试JS文件

curl -I -H "Accept-Encoding: gzip, deflate"  "http://www.baidu.com/xxx.css"  //测试CSS


关于内核参数的优化:

net.ipv4.tcp_max_tw_buckets = 6000

timewait 的数量,默认是180000。

net.ipv4.ip_local_port_range = 1024 65000

允许系统打开的端口范围。

net.ipv4.tcp_tw_recycle = 1

启用timewait 快速回收。

net.ipv4.tcp_tw_reuse = 1

开启重用。允许将TIME-WAIT sockets 重新用于新的TCP 连接。

net.ipv4.tcp_syncookies = 1

开启SYN Cookies,当出现SYN 等待队列溢出时,启用cookies 来处理。

net.core.somaxconn = 262144

web 应用中listen 函数的backlog 默认会给我们内核参数的net.core.somaxconn 限制到128,而nginx 定义的NGX_LISTEN_BACKLOG 默认为511,所以有必要调整这个值。

net.core.netdev_max_backlog = 262144

每个网络接口接收数据包的速率比内核处理这些包的速率快时,允许送到队列的数据包的最大数目。

net.ipv4.tcp_max_orphans = 262144

系统中最多有多少个TCP 套接字不被关联到任何一个用户文件句柄上。如果超过这个数字,孤儿连接将即刻被复位并打印出警告信息。这个限制仅仅是为了防止简单的DoS 攻击,不能过分依靠它或者人为地减小这个值,更应该增加这个值(如果增加了内存之后)。

net.ipv4.tcp_max_syn_backlog = 262144

记录的那些尚未收到客户端确认信息的连接请求的最大值。对于有128M 内存的系统而言,缺省值是1024,小内存的系统则是128。

net.ipv4.tcp_timestamps = 0

时间戳可以避免序列号的卷绕。一个1Gbps 的链路肯定会遇到以前用过的序列号。时间戳能够让内核接受这种“异常”的数据包。这里需要将其关掉。

net.ipv4.tcp_synack_retries = 1

为了打开对端的连接,内核需要发送一个SYN 并附带一个回应前面一个SYN 的ACK。也就是所谓三次握手中的第二次握手。这个设置决定了内核放弃连接之前发送SYN+ACK 包的数量。

net.ipv4.tcp_syn_retries = 1

在内核放弃建立连接之前发送SYN 包的数量。

net.ipv4.tcp_fin_timeout = 1

如果套接字由本端要求关闭,这个参数决定了它保持在FIN-WAIT-2 状态的时间。对端可以出错并永远不关闭连接,甚至意外当机。缺省值是60 秒。2.2 内核的通常值是180 秒,3你可以按这个设置,但要记住的是,即使你的机器是一个轻载的WEB 服务器,也有因为大量的死套接字而内存溢出的风险,FIN- WAIT-2 的危险性比FIN-WAIT-1 要小,因为它最多只能吃掉1.5K 内存,但是它们的生存期长些。

net.ipv4.tcp_keepalive_time = 30

当keepalive 起用的时候,TCP 发送keepalive 消息的频度。缺省是2 小时。

 

下面贴一个完整的内核优化设置:

vi /etc/sysctl.conf  CentOS5.5中可以将所有内容清空直接替换为如下内容:

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

使配置立即生效可使用如下命令:
/sbin/sysctl -p

关于系统连接数的优化

linux 默认值 open files 和 max user processes 为 1024

#ulimit -n

1024

#ulimit –u

1024

问题描述: 说明 server 只允许同时打开 1024 个文件,处理 1024 个用户进程

使用ulimit -a 可以查看当前系统的所有限制值,使用ulimit -n 可以查看当前的最大打开文件数。

新装的linux 默认只有1024 ,当作负载较大的服务器时,很容易遇到error: too many open files 。因此,需要将其改大。

 

解决方法:

使用 ulimit –n 65535 可即时修改,但重启后就无效了。(注ulimit -SHn 65535 等效 ulimit -n 65535 ,-S 指soft ,-H 指hard)

有如下三种修改方式:

1. 在/etc/rc.local 中增加一行 ulimit -SHn 65535
2. 在/etc/profile 中增加一行 ulimit -SHn 65535
3. 在 /etc/security/limits.conf 最后增加:

* soft nofile 65535
* hard nofile 65535
* soft nproc 65535
* hard nproc 65535

具体使用哪种, 在 CentOS 中使用第1 种方式无效果,使用第3 种方式有效果,而在Debian 中使用第2 种有效果

 # ulimit -n

65535

# ulimit -u

65535

备注:ulimit 命令本身就有分软硬设置,加-H 就是硬,加-S 就是软默认显示的是软限制

soft 限制指的是当前系统生效的设置值。 hard 限制值可以被普通用户降低。但是不能增加。 soft 限制不能设置的比 hard 限制更高。 只有 root 用户才能够增加 hard 限制值。

关于FastCGI 的几个指令:

fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2 keys_zone=TEST:10minactive=5m;

这个指令为FastCGI 缓存指定一个路径,目录结构等级,关键字区域存储时间和非活动删除时间。

fastcgi_connect_timeout 300;

指定连接到后端FastCGI 的超时时间。

fastcgi_send_timeout 300;

向FastCGI 传送请求的超时时间,这个值是指已经完成两次握手后向FastCGI 传送请求的超时时间。

fastcgi_read_timeout 300;

接收FastCGI 应答的超时时间,这个值是指已经完成两次握手后接收FastCGI 应答的超时时间。

fastcgi_buffer_size 4k;

指定读取FastCGI 应答第一部分需要用多大的缓冲区,一般第一部分应答不会超过1k,由于页面大小为4k,所以这里设置为4k。

fastcgi_buffers 8 4k;

指定本地需要用多少和多大的缓冲区来缓冲FastCGI 的应答。

fastcgi_busy_buffers_size 8k;

这个指令我也不知道是做什么用,只知道默认值是fastcgi_buffers 的两倍。

fastcgi_temp_file_write_size 8k;

在写入fastcgi_temp_path 时将用多大的数据块,默认值是fastcgi_buffers 的两倍。

fastcgi_cache TEST

开启FastCGI 缓存并且为其制定一个名称。个人感觉开启缓存非常有用,可以有效降低CPU 负载,并且防止502 错误。

fastcgi_cache_valid 200 302 1h;
fastcgi_cache_valid 301 1d;
fastcgi_cache_valid any 1m;

为指定的应答代码指定缓存时间,如上例中将200,302 应答缓存一小时,301 应答缓存1 天,其他为1 分钟。

fastcgi_cache_min_uses 1;

缓存在fastcgi_cache_path 指令inactive 参数值时间内的最少使用次数,如上例,如果在5 分钟内某文件1 次也没有被使用,那么这个文件将被移除。

fastcgi_cache_use_stale error timeout invalid_header http_500;

不知道这个参数的作用,猜想应该是让nginx 知道哪些类型的缓存是没用的。以上为nginx 中FastCGI 相关参数,另外,FastCGI 自身也有一些配置需要进行优化,如果你使用php-fpm 来管理FastCGI,可以修改配置文件中的以下值:

<value name="max_children">60</value>

同时处理的并发请求数,即它将开启最多60 个子线程来处理并发连接。

<value name="rlimit_files">102400</value>

最多打开文件数。

<value name="max_requests">204800</value>

每个进程在重置之前能够执行的最多请求数。



作者:zqtsx 发表于2014-4-19 15:08:09 原文链接
阅读:39 评论:0 查看评论

相关 [nginx 优化 linux] 推荐:

Nginx优化指南+LINUX内核优化+linux连接数优化+nginx连接数优化

- - CSDN博客系统运维推荐文章
Most setup guides for Nginx tell you the basics - apt-get a package, modify a few lines here and there, and you’ve got a web server. In this guide, I’ll explain which settings in nginx can be fine tuned in order to optimize performance for handling a large number of clients.

Nginx性能优化

- - 博客 - 伯乐在线
Nginx作为一个非常流行和成熟的Web Server和Reserve Proxy Server,网上有大量的性能优化教程,但是不同的业务场景千差万别,什么配置是最适合自己的,需要大量的测试和实践以及不断的优化改进. 最近用户调用量突破百万大关之后,就遇到了一些问题,虽然不算太复杂,但也折腾了挺长时间才搞定,积累了不少经验.

linux下安装nginx、pcre、zlib、openssl

- - CSDN博客推荐文章
1、安装nginx之前需要安装 PCRE库的安装. 最新下载地址   ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/. tar –zxvf pcre-8.21.tar.gz,解压目录为:pcre-8.21. 然后进入到 cd pcre-8.21,进行配置、编译、安装.

Linux & Nginx 性能参数调优

- - Linux - 操作系统 - ITeye博客
主要针对linux 文件句柄以及网卡参数调优. 修改linux最大文件句柄数. 查看open files  参数. vi /etc/security/limits.conf 添加. 修改以后保存,注销当前用户,重新登录,执行ulimit -a ,ok ,参数生效了. use epoll; 使用epoll的I/O模型 如:.

Nginx配置性能优化

- - CSDN博客互联网推荐文章
大多数的Nginx安装指南告诉你如下基础知识——通过apt-get安装,修改这里或那里的几行配置,好了,你已经有了一个Web服务器了. 而且,在大多数情况下,一个常规安装的nginx对你的网站来说已经能很好地工作了. 然而,如果你真的想挤压出Nginx的性能,你必须更深入一些. 在本指南中,我将解释Nginx的那些设置可以微调,以优化处理大量客户端时的性能.

Nginx并发访问优化

- - CSDN博客推荐文章
    Nginx反向代理并发能力的强弱,直接影响到系统的稳定性. 安装Nginx过程,默认配置并不涉及到过多的并发参数,作为产品运行,不得不考虑这些因素. Nginx作为产品运行,官方建议部署到Linux64位系统,基于该建议,本文中从系统线之上考虑Nginx的并发优化.     1、打开Linux系统epoll支持.

Linux 内核优化

- - CSDN博客系统运维推荐文章
声明:本文档来自互联网整理部份加自已实验部份所得:. TCP 服务器 <---> 客户端通信状态.           ACK--------------->                                          建立连接.                    <---------------未回复.

Linux 性能优化

- - Gsion&apos;s Blog
1) Linux Proc文件系统,通过对Proc文件系统进行调整,达到性能优化的目的. 2) Linux性能诊断工具,介绍如何使用Linux自带的诊断工具进行性能诊断. 加粗斜体表示可以直接运行的命令. 二、/proc/sys/kernel/优化. 该文件有一个二进制值,该值控制系统在接收到ctrl+alt+delete按键组合时如何反应.

Nginx使用Linux内存加速静态文件访问

- - IT技术博客大学习
标签:   Nginx. Nginx是一个非常出色的静态资源web服务器. 如果你嫌它还不够快,可以把放在磁盘中的文件,映射到内存中,减少高并发下的磁盘IO. nginx.conf中所配置站点的路径是/home/wwwroot/res,站点所对应文件原始存储路径:/opt/web/res. shell脚本非常简单,思路就是拷贝资源文件到内存中,然后在把网站的静态文件链接指向到内存中即可.

Linux中对MySQL优化

- - 数据库 - ITeye博客
要求: MySQL数据库管理与维护. 1、熟悉Linux上安装、配置和优化MySQL数据库,. 2、熟悉 Mysql的AB复制以及读写分离的实现,能完成添加从库,从库变主库等操作;. 3、精通mysql数据库的查询、子查询、插入、更新等操作,以及建数据库、表和索引;. 4、掌握表的连接、视图,以为存储过程和函数的使用;.