nginx优化

Introduction
Nginx is an open-source, high-performance HTTP server and reverse proxy, and an IMAP/POP3 proxy server. Nginx was built with optimization in mind, but there is really no way to optimize Nginx itself. Rather, you can modify some of the default configuration options to help handle high traffic loads.
Besides Nginx, the often overlooked main component of any running site is the server it runs on. Rather than focusing only on the software in this case, this article will discuss some system changes that can help as well; our system being a GNU/Linux distribution.
Common Tools
When you are ready to make changes, there are a few common tools that you can use to understand what is currently happening in the system and the effects of your changes to the system.
vmstat
Use the vmstat
command to run a report of system activity:
[root@ks4001893 ~]# vmstat 3 10procs -----------memory---------- ---swap-- -----io---- --system-- -----cpu----- r b swpd free buff cache si so bi bo in cs us sy id wa st 0 0 188 1735960 470580 5069636 0 0 4 9 3 1 0 0 100 0 0 0 0 188 1736040 470580 5069660 0 0 0 105 72 100 0 0 100 0 0 0 0 188 1736212 470580 5069664 0 0 0 5 49 104 0 0 100 0 0 0 0 188 1736244 470580 5069664 0 0 0 4 50 109 0 0 100 0 0 0 0 188 1736384 470580 5069668 0 0 0 0 40 83 0 0 100 0 0 0 0 188 1736384 470580 5069668 0 0 0 4 51 114 0 0 100 0 0 0 0 188 1736260 470580 5069672 0 0 0 1 47 109 0 0 100 0 0 0 0 188 1736260 470580 5069676 0 0 0 4 46 95 0 0 100 0 0 0 0 188 1736136 470580 5069676 0 0 0 8 44 86 0 0 100 0 0 0 0 188 1736136 470580 5069680 0 0 0 12 53 110 0 0 100 0 0[root@ks4001893 ~]#

When you use this tool, you should use a different tool to analyze the Nginx server to leave what is happening with the system during Nginx load. Specifically, pay attention to the CPU and I/O sections. Under CPU, a good standard is to have an 80/20 system to user utilization ratio during Nginx high load. Additionally if the wa (wait) column begins to increase substantially, you will want to look into optimizing disk read/write of other tools coupled with Nginx (an RDBMS, for example).
strace
Use strace
to debug or monitor system calls used by running programs and processes:
[root@ks4001893 ~]# strace -vvv -p 21422 -rProcess 21422 attached - interrupt to quit 0.000000 epoll_wait(27, {{EPOLLIN, {u32=27129504, u64=27129504}}}, 512, 4294967295) = 1 3.620656 accept4(18, {sa_family=AF_INET, sin_port=htons(64009), sin_addr=inet_addr("72.32.146.52")}, [16], SOCK_NONBLOCK) = 17 0.000052 epoll_ctl(27, EPOLL_CTL_ADD, 17, {EPOLLIN|EPOLLET, {u32=27130464, u64=27130464}}) = 0 0.000028 epoll_wait(27, {{EPOLLIN, {u32=27130464, u64=27130464}}}, 512, 60000) = 1 0.024942 recvfrom(17, "GET / HTTP/1.1\r\nHost: rackspace.com\r\n"..., 1024, 0, NULL, NULL) = 423

The preceding response shows part of an strace
of Nginx. The line 3.620656 accept4
shows the address initiating the connection and the file descriptor (17) provided to this connection. Later at the line beginning with 0.024942 recvfrom
, you see the file descriptor again and a HTTP GET request.
Although cryptic, strace
is a very powerful debugging tool for when you want to really understand the user-to-kernel space activity.
tcpdump/wireshark
Use tcpdump/wireshark
to grad snapshots of network traffic.
Browser Development Tools
System Log [/var/log/messages, /var/log/syslog, and dmesg -c]
Tuning the operating system
When you perform tuning, the best practice is to make the changeand then measure the result. It is important to be remember that changes in one area affect another area most of the time. If the change does not make a difference in what you are analyzing for tuning, undo the change. It is important to remember this because of the optimizations of modern kernels and software.
Configuring Tunable Options
/proc
: When you use/proc
virtual filesystem to configure tunable options, the changes are not persistent. Using /proc
to see the effects of a change prior to making it permanent and allows for quick recovery should any issues arise from the change.
[root@ks4001893 ~]# cat /proc/sys/net/ipv4/tcp_syncookies1[root@ks4001893 ~]# echo 0 > /proc/sys/net/ipv4/tcp_syncookies[root@ks4001893 ~]# cat /proc/sys/net/ipv4/tcp_syncookies0[root@ks4001893 ~]#

sysctl.conf
: After you confirm that the change will help the system run efficiently, make the change persistent. This is done by adding the setting to the /etc/sysctl.conf
file. After you make the change, run sysctl -p
to load the new changes immediately.
[root@ks4001893 ~]# cat /proc/sys/net/ipv4/tcp_syncookies0[root@ks4001893 ~]# vim /etc/sysctl.conf[root@ks4001893 ~]# sysctl -pnet.ipv4.ip_forward = 1net.ipv4.conf.default.rp_filter = 1net.ipv4.conf.default.accept_source_route = 0kernel.sysrq = 0kernel.core_uses_pid = 1net.ipv4.tcp_syncookies = 1...[root@ks4001893 ~]# cat /proc/sys/net/ipv4/tcp_syncookies1[root@ks4001893 ~]#

Basic Tuning Vectors
Backlog queue: Limits number of pending connections; tune for high rate of incoming connections
HTTP Connection: SYN/SYNACK/ACK
SYN/SYNACK [syn_backlog queue] or syncookie
ACK [listen backlog queue] Nginx: accept()
net.ipv4.tcp_max_syn_backlog
net.ipv4.tcp_syncookies
net.core.somaxconn
Nginx: listen backlog = 1024;
net.core.netdev_max_backlog
File descriptors: Limits number of active connections; tune for many simultaneous connections
fs.file_max
/etc/security/limits.conf
worker_rlimit_nofile 40960;
Ephemeral ports: Limits number of upstream connections; tune when proxying, especially without keepalives
Each TCP connection requires a 4-tuple: [src_ip:src_port, dst_ip:dst_port]
net.ipv4.ip_local_port_range
net.ipv4.tcp_fin_timeout
Tuning Nginx
Workers, Connections, Clients
[root@ks4001893 ~]# grep processor /proc/cpuinfo | wc -l4[root@ks4001893 ~]#[root@ks4001893 ~]# vim /etc/nginx/nginx.confworker_processes 4;worker_connections 1024;

Note: We reccommend using the auto value for <code>worker_processes</code> as this will cause Nginx to use one worker per CPU core automagicaly.
Buffers
client_body_buffer_size 10k;client_header_buffer_size 1k;client_max_body_size 8m;large_client_header_buffers 2 1k;

client_body_buffer_size
:Sets buffer size for reading the client request body. In case the request body is larger than the buffer, the whole body or only its part is written to a temporary file.
client_header_buffer_size
: Sets the buffer size for reading the client request header. For most requests, a buffer of 1 kilobyte bytes is enough. However, if a request includes long cookies, or comes from a WAP client, it may not fit into 1 kilobyte. If a request line or a request header field does not fit into this buffer then larger buffers, configured by thelarge_client_header_buffers
parameter, are allocated.
client_max_body_size
: Sets the maximum allowed size of the client request body, specified in the content-Length
request header field.
large_client_header_buffers
: Sets the maximum number and size of buffers used for reading large client request headers. A request line cannot exceed the size of one buffer, or the 414 (Request-URI Too Large)
error is returned to the client. Buffers are allocated only on demand. By default, the buffer size is equal to 8 kilobytes bytes. If after the end of request processing a connection is transitioned into the keep-alive state, these buffers are released.
Timeouts
client_body_timeout 12;client_header_timeout 12;keepalive_timeout 15;send_timeout 10;

client_body_timeout
: Defines a timeout for reading the client request body. The timeout is set only for a period between two successive read operations, not for the transmission of the whole request body.
client_header_timeout
: Defines a timeout for reading client request header.
keepalive_timeout
: The first parameter sets a timeout during which a keep-alive client connection will stay open on the server side. A value of 0 disables keep-alive client connections. The optional second parameter sets a value in the keep-Alive: timeout=time
response header field.
send_timeout
: Sets a timeout for transmitting a response to the client. The timeout is set only between two successive write operations, not for the transmission of the whole response.
Gzip and Expires Header
Enabling gzip reduces the amount of data transferred over the network, which improves speed. The expires
header assists in avoiding unnecessary requests for static content, caching it for a set amount of time. The expires
header can be set inside of the http, server, or location blocks.
gzip on;gzip_min_length 1100;gzip_buffers 4 32k;gzip_types text/plain application/x-javascript text/xml text/css;location ~* .(jpg|jpeg|png|gif|ico|css|js)$ { expires 365d;}

Open File Cache
Enabling the open_file_cache
parameter enables you to cache open file descriptors, frequently accessed files, and file information with their size and modification time, among other things.
open_file_cache max=1000 inactive=20s;open_file_cache_valid 30s;open_file_cache_min_uses 2;open_file_cache_errors on;

Miscellaneous
accept_mutex off;
accept mutex
is a configurable parameter used to help distribute incoming traffic evenly across the worker_processes, but it carries a small amount of CPU overhead. Disabling this parameter for busy services may result in a speed increase.
When proxying, use keep-alives. As Nginx proxies traffic to an upstream server, it doesn't use HTTP keep-alives connections but rather one-shot TCP connections which can be inefficient in terms of the use of ephemeral ports and latency in establishing the TCP connection(s) with the upstream server(s).
Additional Resources

https://community.rackspace.com/products/f/25/t/7377
http://www.linuxmanpages.com/man8/sysctl.8.php
https://www.kernel.org/doc/Documentation/kernel-parameters.txt
http://cr.yp.to/syncookies.html
http://nginx.org/en/docs/
http://wiki.nginx.org/Configuration
https://deviceatlas.com/blog/image-optimization-using-deviceatlas-nginx-module
https://gist.github.com/denji/8359866

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,921评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,635评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,393评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,836评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,833评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,685评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,043评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,694评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,671评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,670评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,779评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,424评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,027评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,984评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,214评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,108评论 2 351
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,517评论 2 343

推荐阅读更多精彩内容

  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 2,806评论 0 0
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,598评论 18 139
  • =========================================================...
    lavor阅读 3,484评论 0 5
  • “拌凉菜要不要放一点花椒油?” “不要放,那个花椒油苦味太重,影响口味。” 抬起花椒油瓶往里倒了好几滴。 “...
    普普Echo阅读 208评论 0 0
  • fdlso阅读 97评论 0 0