主页 > 运维运营 > Nginx >
发布时间:2016-01-01 作者:网络 阅读:254次

通常来说,一个优化良好的 Nginx Linux 服务器可以达到 500,000 – 600,000 次/秒 的请求处理性能,然而我的 Nginx 服务器可以稳定地达到 904,000 次/秒 的处理性能,并且我以此高负载测试超过 12 小时,服务器工作稳定。

这里需要特别说明的是,本文中所有列出来的配置都是在我的测试环境验证的,而你需要根据你服务器的情况进行配置:

从 EPEL 源安装 Nginx:

yum -y install nginx

备份配置文件,然后根据你的需要进行配置:

cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.orig
  vim /etc/nginx/nginx.conf
# This number should be, at maximum, the number of CPU cores on your system.
# (since nginx doesn't benefit from more than one worker per CPU.)
# 这里的数值不能超过 CPU 的总核数,因为在单个核上部署超过 1 个 Nginx 服务进程并不起到提高性能的作用。
worker_processes 24;
 
# Number of file descriptors used for Nginx. This is set in the OS with 'ulimit -n 200000'
# or using /etc/security/limits.conf
# Nginx 最大可用文件描述符数量,同时需要配置操作系统的 "ulimit -n 200000",或者在 /etc/security/limits.conf 中配置。 
worker_rlimit_nofile 200000;
 
# only log critical errors
# 只记录 critical 级别的错误日志
error_log /var/log/nginx/error.log crit
 
# Determines how many clients will be served by each worker process.
# (Max clients = worker_connections * worker_processes)
# "Max clients" is also limited by the number of socket connections available on the system (~64k)
# 配置单个 Nginx 单个进程可服务的客户端数量,(最大值客户端数 = 单进程连接数 * 进程数 )
# 最大客户端数同时也受操作系统 socket 连接数的影响(最大 64K )
worker_connections 4000;
 
# essential for linux, optmized to serve many clients with each thread
# Linux 关键配置,允许单个线程处理多个客户端请求。
use epoll;
 
# Accept as many connections as possible, after nginx gets notification about a new connection.
# May flood worker_connections, if that option is set too low.
# 允许尽可能地处理更多的连接数,如果 worker_connections 配置太低,会产生大量的无效连接请求。
multi_accept on;
 
# Caches information about open FDs, freqently accessed files.
# Changing this setting, in my environment, brought performance up from 560k req/sec, to 904k req/sec.
# I recommend using some varient of these options, though not the specific values listed below.
# 缓存高频操作文件的FDs(文件描述符/文件句柄)
# 在我的设备环境中,通过修改以下配置,性能从 560k 请求/秒 提升到 904k 请求/秒。
# 我建议你对以下配置尝试不同的组合,而不是直接使用这几个数据。
open_file_cache max=200000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
 
# Buffer log writes to speed up IO, or disable them altogether
# 将日志写入高速 IO 存储设备,或者直接关闭日志。
# access_log /var/log/nginx/access.log main buffer=16k;
access_log off;
 
# Sendfile copies data between one FD and other from within the kernel.
# More efficient than read() + write(), since the requires transferring data to and from the user space.
# 开启 sendfile 选项,使用内核的 FD 文件传输功能,这个比在用户态用 read() + write() 的方式更加高效。
sendfile on;
 
# Tcp_nopush causes nginx to attempt to send its HTTP response head in one packet,
# instead of using partial frames. This is useful for prepending headers before calling sendfile,
# or for throughput optimization.
# 打开 tcp_nopush 选项,Nginux 允许将 HTTP 应答首部与数据内容在同一个报文中发出。
# 这个选项使服务器在 sendfile 时可以提前准备 HTTP 首部,能够达到优化吞吐的效果。
tcp_nopush on;
 
# don't buffer data-sends (disable Nagle algorithm). Good for sending frequent small bursts of data in real time.
# 不要缓存 data-sends (关闭 Nagle 算法),这个能够提高高频发送小数据报文的实时性。
tcp_nodelay on;
 
# Timeout for keep-alive connections. Server will close connections after this time.
# 配置连接 keep-alive 超时时间,服务器将在超时之后关闭相应的连接。
keepalive_timeout 30;
 
# Number of requests a client can make over the keep-alive connection. This is set high for testing.
# 单个客户端在 keep-alive 连接上可以发送的请求数量,在测试环境中,需要配置个比较大的值。
keepalive_requests 100000;
 
# allow the server to close the connection after a client stops responding. Frees up socket-associated memory.
# 允许服务器在客户端停止发送应答之后关闭连接,以便释放连接相应的 socket 内存开销。
reset_timedout_connection on;
 
# send the client a "request timed out" if the body is not loaded by this time. Default 60.
# 配置客户端数据请求超时时间,默认是 60 秒。
client_body_timeout 10;
 
# If the client stops reading data, free up the stale client connection after this much time. Default 60.
# 客户端数据读超时配置,客户端停止读取数据,超时时间后断开相应连接,默认是 60 秒。
send_timeout 2;
 
# Compression. Reduces the amount of data that needs to be transferred over the network
# 压缩参数配置,减少在网络上所传输的数据量。
gzip on;
gzip_min_length 10240;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml;
gzip_disable "MSIE [1-6].";

启动 Nginx 并配置起机自动加载。

service nginx start
  chkconfig nginx on

配置 Tsung 并启动测试,测试差不多 10 分钟左右就能测试到服务器的峰值能力,具体的时间与你的 Tsung 配置相关。

[root@loadnode1 ~] vim ~/.tsung/tsung.xml


tsung start

你觉得测试结果已经够了的情况下,通过 ctrl+c 退出,之后使用我们之前配置的别名命令 treport 查看测试报告。

WEB 服务器调优,第二部分:TCP 协议栈调优

这个部分不只是对 Ngiinx 适用,还可以在任何 WEB 服务器上使用。通过对内核 TCP 配置的优化可以提高服务器网络带宽。

以下配置在我的 10-Gbase-T 服务器上工作得非常完美,服务器从默认配置下的 8Gbps 带宽提升到 9.3Gbps。

当然,你的服务器上的结论可能不尽相同。

下面的配置项,我建议每次只修订其中一项,之后用网络性能测试工具 netperf、iperf 或是用我类似的测试脚本 cluster-netbench.pl 对服务器进行多次测试。

yum -y install netperf iperf
vim /etc/sysctl.conf
# Increase system IP port limits to allow for more connections
# 调高系统的 IP 以及端口数据限制,从可以接受更多的连接
net.ipv4.ip_local_port_range = 2000 65000
 
net.ipv4.tcp_window_scaling = 1
 
# number of packets to keep in backlog before the kernel starts dropping them
# 设置协议栈可以缓存的报文数阀值,超过阀值的报文将被内核丢弃
net.ipv4.tcp_max_syn_backlog = 3240000
 
# increase socket listen backlog
# 调高 socket 侦听数阀值
net.core.somaxconn = 3240000
net.ipv4.tcp_max_tw_buckets = 1440000
 
# Increase TCP buffer sizes
# 调大 TCP 存储大小
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
net.ipv4.tcp_congestion_control = cubic

每次修订配置之后都需要执行以下命令使之生效.

sysctl -p /etc/sysctl.conf

别忘了在配置修订之后务必要进行网络 benchmark 测试,这样可以观测到具体是哪个配置修订的优化效果最明显。通过这种有效测试方法可以为你节省大量时间。

常见优化配置项

一般来说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 时间内一次没被使用,它将被移除。

关于内核参数的优化:

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 小时。


关键字词: