How to Configure Nginx for Optimized Performance
2016-09-19 02:18
459 查看
Features
Pricing
Add-ons
Resources
|
Log in
Sign up
Guides & Tutorials
Web Server Guides
Nginx
How to Configure Nginx for Optimized Performance
How to Configure Nginx for Optimized Performance
Updated Wednesday, September 9th, 2015 by LinodeContributed by Bob StrecanskyUse promo code DOCS10 for $10 Credit on a new account. Try this Guide
Contribute on GitHub
View Project | View File | Edit File
This is a Linode Community guide. Write for us and earn $250 per published guide.
Nginx is known for its use in both high performance load balancing, and caching static and dynamic web content. This guide aims to provide assistance in determining the best performance optimizations to make to an Nginx server in order to speed up delivery of content to your end users.
Worker Modifications
The easiest thing to set in your configuration is the right number of workers and connections.Worker Processes
In/etc/nginx/nginx.conf, set
worker_processes 1;if you have a lower traffic site where Nginx, a database, and a web application all run on the same server.
If you have a higher traffic site or a dedicated instance for Nginx, set one worker per CPU core:
worker_processes auto;
If you’d like to set this manually, you can utilize
grep ^processor /proc/cpuinfo | wc -lto find the number of processes that the server can handle.
Worker Connections
The optionworker_connectionssets the maximum number of connections that can be processed at one time by each worker process. By default, the worker connection limit is 512, but many systems can handle more.
The appropriate sizing can be discovered through testing, as it is variable based on the type of traffic Nginx is handling. The system’s core limitations can also be find through using
ulimit:
1 | ulimit -n |
1 | 65536 |
use epoll, a scalable I/O event notification mechanism to trigger on events and make sure that I/O is utilized to the best of its ability.
Lastly, you can utilize
multi_acceptin order for a worker to accept all new connections at one time.
The
eventsfunction should look something like this when configured:
/etc/nginx/nginx.conf
1 2 3 4 5 | events { worker_connections 66536; use epoll; multi_accept on; } |
HTTP and TCP Optimizations
Keep Alive
Keep alive allows for fewer reconnections from the browser.keepalive_timeoutand
keepalive_requestscontrol the keep alive settings.
sendfileoptimizes serving static files from the file system, like logos.
tcp_nodelayallows Nginx to make TCP send multiple buffers as individual packets.
tcp_nopushoptimizes the amount of data sent down the wire at once by activating theTCP_CORK option within the TCP stack. TCP_CORK blocks the data until the packet reaches the MSS, which is equal to the MTU minus the 40 or 60 bytes of the IP header.
/etc/nginx/nginx.conf
1 2 3 4 5 | keepalive_timeout 65; keepalive_requests 100000; sendfile on; tcp_nopush on; tcp_nodelay on; |
Buffer Size
Making tweaks to the buffer size can be advantageous. If the buffer sizes are too low, then Nginx will write to a temporary file. This will cause for excessive disk I/O.client_body_buffer_sizehandles the client buffer size. Most client buffers are coming from POST method form submissions. 128k is normally a good choice for this setting.
client_max_body_sizesets the max body buffer size. If the size in a request exceeds the configured value, the 413 (Request Entity Too Large) error is returned to the client. For reference, browsers cannot correctly display 413 errors. Setting size to 0 disables checking of client request body size.
client_header_buffer_sizehandles the client header size. 1k is usually a sane choice for this by default.
large_client_header_buffersshows the maximum number and size of buffers for large client headers. 4 headers with 4k buffers should be sufficient here.
output_bufferssets the number and size of the buffers used for reading a response from a disk. If possible, the transmission of client data will be postponed until Nginx has at least the set size of bytes of data to send. The zero value disables postponing data transmission.
/etc/nginx/nginx.conf
1 2 3 4 5 | client_body_buffer_size 128k; client_max_body_size 10m; client_header_buffer_size 1k; large_client_header_buffers 4 4k; output_buffers 1 32k; postpone_output 1460; |
Connection Queue
Some directives in the in the/etc/sysctl.conffile can be changed in order to set the size of a Linux queue for connections and buckets. Updating the
net.core.somaxconnand
net.ipv4.tcp_max_tw_bucketschanges the size of the queue for connections waiting for acceptance by Nginx. If there are error messages in the kernel log, increase the value until errors stop.
/etc/sysctl.conf
1 2 | net.core.somaxconn = 65536net.ipv4.tcp_max_tw_buckets = 1440000 |
net.core.netdev_max_backlogtag. Consult the network card documentation for advice on changing this value.
Timeouts
Timeouts can also drastically improve performance.client_body_timeoutsends directives for the time a server will wait for a body to be sent.
client_header_timeoutsends directives for the time a server will wait for a header body to be sent. These directives are responsible for the time a server will wait for a client body or client header to be sent after request. If neither a body or header is sent, the server will issue a 408 error or Request time out.
sent_timeoutspecifies the response timeout to the client. This timeout does not apply to the entire transfer but, rather, only between two subsequent client-read operations. Thus, if the client has not read any data for this amount of time, then Nginx shuts down the connection.
/etc/nginx/nginx.conf
1 2 | client_header_timeout 3m; client_body_timeout 3m; send_timeout 3m; |
Static Asset Serving
If your site serves static assets (such as CSS/JavaScript/images), Nginx can cache these files for a short period of time. Adding this within your configuration block tells Nginx to cache 1000 files for 30 seconds, excluding any files that haven’t been accessed in 20 seconds, and only files that have 5 times or more. If you aren’t deploying frequently you can safely bump up these numbers higher./etc/nginx/nginx.conf
1 2 | open_file_cache max=1000 inactive=20s; open_file_cache_valid 30s; open_file_cache_min_uses 5; open_file_cache_errors off; |
/etc/nginx/nginx.conf
1 2 | location ~* .(woff|eot|ttf|svg|mp4|webm|jpg|jpeg|png|gif|ico|css|js)$ { expires 365d; } |
Gzipping Content
For content that is plain text, Nginx can use gzip compression to serve back these assets compressed to the client. Modern web browsers will accept gzip compression and this will shave bytes off of each request that comes in for plain text assets. The list below is a “safe” list of compressible content types; however, you only want to enable the content types that you are utilizing within your web application./etc/nginx/nginx.conf
1 2 | gzip on; gzip_min_length 1000; gzip_types: text/html application/x-javascript text/css application/javascript text/javascript text/plain text/xml application/json application/vnd.ms-fontobject application/x-font-opentype application/x-font-truetype application/x-font-ttf application/xml font/eot font/opentype font/otf image/svg+xml image/vnd.microsoft.icon; gzip_disable "MSIE [1-6]\."; |
Filesystem Optimizations
These file system operations improve system memory management, and can be added in/etc/sysctl.conf.
Ephemeral Ports
When Nginx is acting as a proxy, each connection to an upstream server uses a temporary, or ephemeral, port.The IPv4 local port range defines a port range value. A common setting is
net.ipv4.ip_local_port_range 1024 65000.
The TCP FIN timeout belays the amount of time a port must be inactive before it can reused for another connection. The default is often 60 seconds, but can normally be safely reduced to 30 or even 15 seconds:
/etc/sysctl.conf
1 | net.ipv4.tcp_fin_timeout 15 |
Scale TCP Window
The TCP window scale option is an option to increase the receive window size allowed in Transmission Control Protocol above its former maximum value of 65,535 bytes. This TCP option, along with several others, is defined in IETF RFC 1323 which deals with long fat networks. It can be defined with thenet.ipv4.tcp_window_scaling = 1tag.
Backlog Packets Before Drop
Thenet.ipv4.tcp_max_syn_backlogdetermines a number of packets to keep in the backlog before the kernel starts dropping them. A sane value is
net.ipv4.tcp_max_syn_backlog = 3240000.
Close connection on Missing Client Response
reset_timedout_connection on;allows the server to close the connection after a client stops responding. This frees up socket-associated memory.
File Descriptors
File descriptors are operating system resources used to handle things such as connections and open files. Nginx can use up to two file descriptors per connection. For example, if it is proxying, there is generally one file descriptor for the client connection and another for the connection to the proxied server, though this ratio is much lower if HTTP keep alives are used. For a system serving a large number of connections, these settings may need to be adjusted.sys.fs.file_maxdefines the system wide limit for file descriptors.
nofiledefines the user file descriptor limit, set in the
/etc/security/limits.conffile.
/etc/security/limits.conf
1 2 | soft nofile 4096 hard nofile 4096 |
Error Logs
error_log logs/error.log warn;defines the location and the different severity levels written to the error log. Setting a certain log level will cause all messages from that log level and higher to be logged. For example, the
defaultlevel error will cause
error,
crit,
alert, and
emergmessages to be logged. If this parameter is omitted, then
erroris used by default.
emerg: Emergency situations where the system is in an unusable state.
alert: Severe situation where action is needed promptly.
crit: Important problems that need to be addressed.
error: An Error has occurred. Something was unsuccessful.
warn: Something out of the ordinary happened, but not a cause for concern.
notice: Something normal, but worth noting has happened.
info: An informational message that might be nice to know.
debug: Debugging information that can be useful to pinpoint where a problem is occurring.
Access logs with the
log_formatdirective to configure a format of logged messages, as well as the
access_logdirective to specify the location of the log and the format.
/etc/nginx/nginx.conf
1 2 3 4 5 | http { log_format compression '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" "$gzip_ratio"'; server { gzip on; access_log /spool/logs/nginx-access.log compression; } } |
Conditional Logging
Conditional logging can be completed if the system administrator only wants to log certain requests. The example below excludes logging for both 2XX and 3XX HTTP status codes:/etc/nginx/nginx.conf
1 2 | map $status $loggable { ~^[23] 0; default 1; } |
Turning off Logging Completely
Logging can be turned off completely if you have an alternative logging methodology or if you don’t care about logging any of the requests to the server. Turning off logging can be performed with the following server directives/etc/nginx/nginx.conf
1 2 3 4 5 | server { listen 80; server_name example.com; access_log off; error_log off; } |
Activity Monitoring
One can also set up activity monitoring to see JSON responses in real-time. With the following configuration, the webpagestatus.htmllocated at
/usr/share/nginx/htmlcan be requested by the URL
http://127.0.0.1/status.html.
You could also utilize Linode Longview in order to view these collections. Longview is a system level statistics collection and graphing service, powered by the Longview open source software agent that can be installed onto any Linux system. The Longview agent collects system statistics and sends them to Linode, where the data is stored and presented it in beautiful and meaningful ways.
Example Files
Several tweaks have now been made across three files to improve Nginx performance on your system. Full snippets of the files are included below.sysctl.conf
/etc/sysctl.conf1 2 3 4 5 | net.core.somaxconn = 65536net.ipv4.tcp_max_tw_buckets = 1440000 |
limits.conf
/etc/security/limits.conf1 2 | soft nofile 4096 hard nofile 4096 |
nginx.conf
nginx.conf1 2 3 4 5 | pid /var/run/nginx.pid; |
Search guides and tutorials
In This Guide:
Worker ModificationsWorker Processes
Worker Connections
HTTP and TCP Optimizations
Keep Alive
Buffer Size
Connection Queue
Timeouts
Static Asset Serving
Gzipping Content
Filesystem Optimizations
Ephemeral Ports
Scale TCP Window
Backlog Packets Before Drop
Close connection on Missing Client Response
File Descriptors
Error Logs
Conditional Logging
Turning off Logging Completely
Activity Monitoring
Example Files
sysctl.conf
limits.conf
nginx.conf
RSS feed
Monthly Guides Update
Sign Up
Get paid to write for Linode.
We're always expanding our docs. If you like to help people, can write, and want to earn some cash, learn how you can earn $250 for every guide you write and we publish.Get started in the Linode Cloud today.
Create an Account
Overview
Plans & Pricing
Features
Add-Ons
Managed
Professional Services
Resources
Guides & Tutorials
Speed Test
Forum
Chat
System Status
Company
About Us
Blog
Press
Referral System
Careers
Contact Us
855-4-LINODE
(855-454-6633)
Intl.: +1 609-380-7100
Email us
© 2016 Linode, LLC
Terms of Service
Privacy Policy
Security
Standards & Compliance
相关文章推荐
- How to Configure Tomcat/JBoss and Apache HTTPD for Load Balancing and Failover
- How To Collect 10046 Trace (SQL_TRACE) Diagnostics for Performance Issues
- C++--How to configure Visual Studio for compiling drivers
- Linux: How to Configure the DNS Server for 11gR2 SCAN (Doc ID 1107295.1)
- How to Configure a Relay Connector for Exchange Server 2010
- HOWTO Configure JBoss for HTTPS
- C++--How to configure Visual Studio for compiling drivers
- Linux: How to Configure the DNS Server for 11gR2 SCAN [ID 1107295.1]
- Howto Install and Configure Doxygen for QtCreator on Ubuntu
- How to Configure Javadoc for RoboLibrary
- How to Configure Eclipse for Python
- How to Install and Configure Nginx from Source on centos--转
- How to Maximise CPU Performance for the Oracle Database on Linux
- How to Configure Eclipse for Python
- How to setup and configure Sonar for Groovy projects
- How to Configure Eclipse for Python --- 在eclipse中如何配置pydev
- How to Configure Eclipse for Python --- 在eclipse中如何配置pydev
- How to configure Nginx Gzip compression
- How to configure a Windows RADIUS server for 802.1X Wireless or Wired Connections
- How to configure OpenFiler v2.3 iSCSI Storage for use with VMware ESX.