worker_processes与worker_connections 设置好合适大小,可以提示nginx处理性能,非常重要
原作者的话:
As a general rule you need the only worker with large number of worker_connections, say 10,000 or 20,000.
However, if nginx does CPU-intensive work as SSL or gzipping and you have 2 or more CPU, then you may
set worker_processes to be equal to CPU number.
Besides, if you serve many static files and the total size of the files is bigger than memory, then you may
increase worker_processes to utilize a full disk bandwidth.
Igor Sysoev
翻译:
一般一个进程足够了,你可以把连接数设得很大。(worker_processes: 1,worker_connections: 10,000)
如果有SSL、gzip
这些比较消耗CPU
的工作,而且是多核CPU
的话,可以设为和CPU的数量一样。(worker_processes: CPU核心数)
或者要处理很多很多的小文件,而且文件总大小比内存大很多的时候,也可以把进程数增加,以充分利用IO
带宽(主要似乎是IO操作有block)
worker_processes,工作进程数
- 默认:worker_processes: 1
- 上调:worker_connections: 100000,(调大到10万连接)
worker_connections解析
-
connections不是随便设置的,而是与两个指标有重要关联,一是内存,二是操作系统级别的“进程最大可打开文件数”。
-
内存:每个连接数分别对应一个
read_event
、一个write_event
事件,一个连接数大概占用232
字节,2
个事件总占用96
字节,那么一个连接总共占用328
字节,通过数学公式可以算出100000
个连接数大概会占用31M = 100000 * 328 / 1024 / 1024
,当然这只是nginx
启动时,connections
连接数所占用的nginx
。 -
进程最大可打开文件数:进程最大可打开文件数受限于操作系统,可通过
ulimit -n
命令查询,以前是1024
,现在是65535
,
nginx
提供了worker_rlimit_nofile
指令,这是除了ulimit
的一种设置可用的描述符的方式。 该指令与使用ulimit
对用户的设置是同样的效果。此指令的值将覆盖ulimit
的值,如:worker_rlimit_nofile 20960
;
设置ulimits:ulimit -SHn 65535
worker_processes 2;
worker_rlimit_nofile 65535;
#pid logs/nginx.pid;
events {
worker_connections 65535;
}
通过ps
命令查看Nginx
进程
# ps -ef|grep nginx
root 1525 1 0 16:41 ? 00:00:00 nginx: master process openresty
nobody 1526 1525 0 16:41 ? 00:00:00 nginx: worker process
root 1528 1443 0 16:41 pts/0 00:00:00 grep --color=auto nginx
通过cat /proc/1526/limits
查看,其中1526是worker
进程ID
,请注意其中的Max open files
# cat /proc/1526/limits
Limit Soft Limit Hard Limit Units
Max cpu time unlimited unlimited seconds
Max file size unlimited unlimited bytes
Max data size unlimited unlimited bytes
Max stack size 8388608 unlimited bytes
Max core file size 0 unlimited bytes
Max resident set unlimited unlimited bytes
Max processes 7270 7270 processes
Max open files 65535 65535 files
Max locked memory 65536 65536 bytes
Max address space unlimited unlimited bytes
Max file locks unlimited unlimited locks
Max pending signals 7270 7270 signals
Max msgqueue size 819200 819200 bytes
Max nice priority 0 0
Max realtime priority 0 0
Max realtime timeout unlimited unlimited us
从上面的分析可以看出nginx占用内存小,处理性能高,通过提高服务器的配置,Nginx可以应对更大的连接数