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

Nginx配置及linux系统内存高并发多方面优化 基于网上的技术文章思路,自己加以整理,有常用的和不常用的策略,供参考。nginx的优化1. gzip压缩优化 2. expires缓存有还 3. 网络IO事件模型优化 4. 隐藏软件名称和版本号 5. 防盗链优化 6. 禁止恶意域名解析 7. 禁止通过IP地址访问网站 8. HTTP请求方法优化 9. 防DOS攻击单IP并发连接的控制,与连接速... 阅读详情

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

标签:  nginx 优化 linux | 发表时间:2014-04-19 15:08 | 作者:zqtsx
分享到:
出处:http://blog.youkuaiyun.com

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.

1user www-data;
2pid /var/run/nginx.pid;
3 
4worker_processes auto;
5 
6worker_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中有少数的几个高级配置在模块部分之上。

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

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

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.

1events {
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中所有处理连接的设置。

1events {
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.

01http {
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模块中,甚至你不会特别的注意到这段设置。

01http {
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

1access_log off;
2error_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

1keepalive_timeout 10;
2 
3client_header_timeout 10;
4client_body_timeout 10;
5 
6reset_timedout_connection on;
7send_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不要缓存数据,而是一段一段的发送--当需要及时发送数据时,就应该给应用设置这个属性,这样发送一小块数据信息时就不能立即得到返回值。

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

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

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

client_header_timeout 和 client_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.

1limit_conn_zone $binary_remote_addr zone=addr:5m;
2limit_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.

1include /etc/nginx/mime.types;
2default_type text/html;
3charset 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就会关闭连接。

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

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

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

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

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

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

1gzip on;
2gzip_disable "msie6" ;
3 
4# gzip_static on;
5gzip_proxied any;
6gzip_min_length 1000;
7gzip_comp_level 4;
8 
9gzip_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
03open_file_cache max=100000 inactive=20s;
04open_file_cache_valid 30s;
05open_file_cache_min_uses 2;
06open_file_cache_errors on;
07 
08##
09# Virtual Host Configs
10# aka our settings for specific servers
11##
12 
13include /etc/nginx/conf.d/*.conf;
14include /etc/nginx/sites-enabled/*;
译者信息 

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

1gzip on;
2gzip_disable "msie6" ;
3 
4# gzip_static on;
5gzip_proxied any;
6gzip_min_length 1000;
7gzip_comp_level 4;
8 
9gzip_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
03open_file_cache max=100000 inactive=20s;
04open_file_cache_valid 30s;
05open_file_cache_min_uses 2;
06open_file_cache_errors on;
07 
08##
09# Virtual Host Configs
10# aka our settings for specific servers
11##
12 
13include /etc/nginx/conf.d/*.conf;
14include /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

01user www-data;
02pid /var/run/nginx.pid;
03worker_processes auto;
04worker_rlimit_nofile 100000;
05 
06events {
07     worker_connections 2048;
08     multi_accept on;
09     use epoll;
10}
11 
12http {
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.

译者信息 

一个完整的配置

01user www-data;
02pid /var/run/nginx.pid;
03worker_processes auto;
04worker_rlimit_nofile 100000;
05 
06events {
07     worker_connections 2048;
08     multi_accept on;
09     use epoll;
10}
11 
12http {
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>

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

相关 [nginx 优化 linux

Nginx 高性能优化配置 轻松实现10万+并发访问 nginx的连接处理机制在于不同的操作系统会采用不同的I/O模型,Linux下,nginx使用epoll的I/O多路复用模型,在freebsd使用kqueue的IO多路复用模型,在solaris使用/dev/pool方式的IO多路复用模型,在windows使用的icop等等。要根据系统类型不同选择不同的事务处理模型,我们使用的是Centos,因此将nginx的事件处理模型调整为epoll模型。Nginx要达到最好的性能,出了要优化Nginx服务本身之外,还需要在nginx的服务器上的内核参数。 阅读详情

相关推荐

socketconnetion连接池

socketconnection用delphi midas里面pooler程序改写的三层缓冲池。创建连接池类时delphi注册信息未写全故要重加.我的三层在此基础上修改,自带的只连了一个数据库。还要自已添加代码实现多个数据库的共享。

Nginx代理连接Redis失败

遇到了一个客户端连接Redis总是失败的问题,由于是通过nginx代理连接的,又尝试不通过nginx代理连接直接连接redis地址,不过连接很不稳定,不时就断了。 因为这部分配置跑了一年多了,也没想到是nginx的问题,各种排查网络情况,弄了半天也没有个结论。 顺手看了一眼nginx的error日志,发现了新大陆。。。看来正式环境的nginx的error日志加上的必要性还是非常非常的大的。 ngi...

xo19882011的专栏 5335

使用VS Code创建第一个Flutter工程

你可以使用任意文本编辑器结合命令行工具来开发Flutter应用。然而,我们推荐使用本文介绍的编辑器插件以获取更好的开发体验。这些插件提供了代码补全、代码高亮、widget辅助编辑等功能,以及为项目的运行和调试提供支持。推荐的开发工具有VS Code、Android Studio、IntelliJ。本文将重点介绍如何使用VS Code进行Flutter应用开发。

2501_91373349的博客 2129

nginx负载均衡配置(无脑版)

nginx.conf配置文件如下 #user nobody; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events { w...

Super的专栏 772

FPGA以太网接口设计避坑指南:GMII与RGMII时序转换的三种实现方案对比

本文深入解析FPGA以太网接口设计中GMII与RGMII时序转换的三种实现方案,包括Xilinx官方IP核、手工原语逻辑和开源方案gmii_to_rgmii。通过对比分析各方案的优缺点和适用场景,为工程师提供技术选型指南,帮助避免常见设计陷阱,提升高速网络设备开发的效率和可靠性。

weixin_42570484的博客 386

解密UFS Explorer:Drobo BeyondRAID数据恢复实战指南

本文详细介绍了使用UFS Explorer Professional Recovery软件中的Drobo BeyondRAID助手进行数据恢复的完整实战流程。当Drobo设备因BeyondRAID配置信息丢失而无法访问时,该工具能安全、只读地扫描硬盘,虚拟重建存储池,帮助用户找回宝贵数据。指南涵盖了从前期准备、硬盘选择、配置扫描到数据安全导出的每一步关键操作与常见问题解决方案。

weixin_29219539的博客 270

socket连接错误及原因

Socket 错误指的是在使用 Socket 进行网络通信时,由于各种原因而导致的错误。Socket 是一种网络编程接口,它允许应用程序通过 TCP/IP 协议或 UDP 协议进行网络通信。在进行网络通信时,可能会出现各种各样的错误,例如连接超时、连接被重置、无法连接等等,这些错误都被称为 Socket 错误。当出现 Socket 错误时,通常需要根据具体的错误信息进行调试和处理,例如修改网络配置、增加连接超时时间、检查网络连接等等。正确地处理 Socket 错误可以有效提高网络通信的稳定性和可靠性。

关注我!带你一路 "狂飙" 到底! 2万+

SHAP图全解析:从理论到实践,教你如何读懂和优化模型特征

本文全面解析SHAP图,从博弈论基础到实战应用,指导读者如何解读和利用SHAP值优化机器学习模型。通过详解特征重要性条形图、小提琴图、依赖图及决策图等关键可视化工具,帮助数据科学家精准诊断模型、识别特征交互,并将洞见转化为特征工程与模型调试的实际行动,有效提升模型可解释性与性能。

svm4gardener的博客 189

socket connect的问题

非阻塞Connect对于select时应注意问题 对于面向连接的socket类型(SOCK_STREAM,SOCK_SEQPACKET)在读写数据之前必须建立连接,首先服务器端socket必须在一个客户端知道的地址进行监听,也就是创建socket之后必须调用bind绑定到一个指定的地址,然后调用int listen(int sockfd, int backlog);进行监听。此时服务

flymachine的专栏 3万+

Verilog十大基本功2(testbench的设计 文件读取和写入操作 源代码)

需求说明:Verilog设计基础 内容       :testbench的设计 读取文件 写入文件 来自       :时间的诗 十大基本功之 testbench 1. 激励的产生 对于 testbench 而言,端口应当和被测试的 module 一一对应。 端口分为 input,output 和 inout 类型产生激励信号的时候, input  对

时间的诗 5万+

SAP-ABAP:SAP Open SQL 分页技术深度解析:语法、性能陷阱与最佳实践

SAP Open SQL 分页技术深度解析:语法、性能陷阱与最佳实践

baidu_35680696的博客 634

如何控制Nginx并发连接数,Linux 内核优化

模块说明 模块:nginx_http_limit_conn_module 模块作用:限制每个key值的连接数,特别是单个IP连接数。 不是所有的连接数都会被计算,一个符合要求的连接是整个请求已经被读取的连接。 Nginx并发连接数参数说明 limit_conn_zone参数: 语法:limit_conn_zone key zone=name:size; 上下文:http 用于设置共享内存区域,key可以是字符串,nginx自有变量或前两个组合,如server_name。name为内存区域的名称,siz

qq_40907977的博客 767

AFSim2.9.0学习笔记 —— 2、AFSim的Wizard软件概述(ArkSIM集成开发环境 (IDE))

AFSim2.9.0学习笔记 —— 2、AFSim的Wizard软件详述(ArkSIM集成开发环境 (IDE))

922

Linux部署Nginx、Nginx性能优化+Linux内核优化

一、使用yum安装Nginx服务 1、添加源 sudo rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm 2、安装nginx (1)使用命令,看看是否已经添加源成功 yum search nginx (2)安装Nginx sudo yum install -y nginx 3、设置开机启动 systemctl enable ng

猴子_net的博客 1275

SAP BSIS:总账未清项表(Open Items)总账未清项 包含哪些业务 请给以举例说明

SAP总账未清项是指需要未来核销的会计行项目,仅适用于勾选"未清项管理"的总账科目。典型业务场景包括:供应商预付款(借方未清项)、员工备用金(借方未清项)、客户预收款(贷方未清项)和保险理赔(借方未清项)。系统通过表BSIS/BSAS跟踪未清项,支持明细追踪和账实核对。核心价值在于提供总账级别的明细管理能力,确保往来款项完整清账,简化对账流程,满足特殊业务管理需求。可通过FBL3N事务码查询和管理所有总账未清项。

金牌架构师 724

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

Nginx 服务器的Linux 内核优化

由于默认的Linux内核参数考虑的是最通用场景,这明显不符合用于支持高并发访问的Web服务器的定义,所以需要修改Linux内核参数,是的Nginx可以拥有更高的性能; 在优化内核时,可以做的事情很多,不过,我们通常会根据业务特点来进行调整,当Nginx作为静态web内容服务器、反向代理或者提供压缩服务器的服务器时,期内核参数的调整都是不同的,这里针对最通用的、使Nginx支持更多并发请求的TCP网络参数做简单的配置; 首先,你需要修改/etc/sysctl.conf来更改内核参数。 fs.file-

勿念勿扰,相安静好 347

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

后端面试必备:如何调整Linux操作系统的内核参数来优化Nginx性能

Nginx作为一款高性能的Web服务器和反向代理服务器,其性能很大程度上依赖于底层Linux操作系统的内核参数配置。合理调整这些参数可以显著提升Nginx的并发处理能力、网络吞吐量和整体稳定性。本文将详细介绍如何通过优化Linux内核参数来最大化Nginx的性能表现。

qq_58299462的博客 746

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

nginx内核参数优化

内核参数的优化,主要是在Linux系统中针对Nginx应用而进行的系统内核参数优化,常见的优化参数值如下。 下面给出一个优化实例以供参考: 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_

freedomai的专栏 543

linux nginx 启动参数,Nginx内核参数的优化

内核参数的优化,主要是在linux系统中针对Nginx应用而进行的系统内核参数的优化。下面给出的一个优化实例以供参考。net.ipv4.tcp_max_tw_buckets = 6000net.ipv4.ip_local_port_range = 1024 65000net.ipv4.tcp_tw_recycle = 1net.ipv4.tcp_tw_reuse = 1net.ipv4.tcp_s...

weixin_39707693的博客 220

nginx配置参数优化/linux内核网络模块优化

文章目录Nginx配置参数优化1.针对worker进程的优化2.针对http和tcp的优化3.针对buffer和cache的优化4.针对数据压缩的优化5.针对日志的优化6.针对SSL的优化Linux内核参数优化(网络模块) Nginx配置参数优化 Nginx作为高性能web服务器,即使不特意调整配置参数也可以处理大量的并发请求 1.针对worker进程的优化 worker_processes:该参...

FUYY'S BLOG 1856

nginx linux内核优化,nginx+linux优化,提高并发性能

优化内核:vi /etc/sysctl.conf添加以下内容net.ipv4.tcp_max_tw_buckets = 6000net.ipv4.tcp_sack = 1net.ipv4.tcp_window_scaling = 1net.ipv4.tcp_rmem = 4096 87380 4194304net.ipv4.tcp_wmem = 4096 16384...

weixin_31953691的博客 138
上一篇: 优化Linux下的内核TCP参数来提高服务器负载能力
下一篇: linux 系统优化tcp连接
BlueSy2008
博客等级 码龄20年 26粉丝 26原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值