Ускоряем Nginx за 5 минут
Как правило, настроенный должным образом сервер Nginx на Linux, может обрабатывать 500,000 — 600,000 запросов в секунду. Но этот показатель можно весьма ощутимо увеличить. Хотел бы обратить внимание на тот факт, что настройки описанные ниже, применялись в тестовой среде и, возможно, для ваших боевых серверов они не подойдут.
На всякий пожарный, создадим бэкап исходного конфига.
А теперь можно и похимичить!
Начнём с директивы worker_processes. Если Nginx выполняет работу нагружающую процессор (например SSL или gzipping), то оптимально установить эту директиву в значение, равное количеству ядер процессора. Выигрыш при большем значении вы получите только в случае обработки очень большого количества статики.
Также, директива worker_processes, умноженная на worker_connections из секции event, даст максимально возможное количество клиентов.
Последняя пролетарская директива, которую я хочу затронуть — это worker_rlimit_nofile. Данная директива указывает сколько файловых дескрипторов будет использовать Nginx. На каждое соединение надо выделять по два дексриптора, даже для статических файлов (картинки/JS/CSS): один для соединения с клиентом, а второй — для открытия статического файла. Таким образом, значение worker_rlimit_nofile должно быть равным удвоенному значению Max Clients. В системе это значение можно установить из командной строки ulimit -n 200000 или используя /etc/security/limits.conf.
Теперь разберёмся с логированием. Во-первых, оставим логирование только критических ошибок.
Если вы совсем бесстрашны и хотите отключить логирование ошибок целиком, то помните, что error_log off вам не поможет. Вы просто получите весь лог в файле off. Для отключения логирования ошибок надо делать так:
А вот логи доступа не так страшно отключить полностью.
Или, хотя бы, включить буфер чтения / записи.
Для обработки подключений Nginx поддерживает ряд методов. Наиболее эффективным для Linux является метод epoll.
Для того, чтобы Nginx пытался принять максимальное количество подключений, необходимо включить директиву multi_accept. Однако при слишком маленьком значении worker_connections, их лимит может быть очень быстро исчерпан.
- дескрипторах недавно открытых файлов: их размера и даты модификации;
- существовании директорий;
- ошибках при поиске файлов: отсутствие самого файла, отсутствие прав на чтение и т.д.
Директива sendfile активирует копирование данных между файловыми дескрипторами средствами ядра, что намного эффективнее связки read() + write(), которая требует обмена данными с пользовательским пространством.
После включения sendfile, можно заставить Nginx отправлять заголовки HTTP-ответов одним пакетом, а не отдельным частями.
Для keep-alive подключений можно выключить буферизацию (алгоритм Нейгла). Это будет полезно при частом запросе маленьких объёмов данных в режиме реального времени, без получения немедленного ответа, когда важна своевременная доставка данных. Классический пример — события наведения мышкой.
Стоит обратить внимание на ещё две директивы для keep-alive подключений. Их назначение выглядит очевидным.
Чтобы высвободить дополнительную память, выделенную под сокеты, включите директиву reset_timedout_connection. Она разрешит серверу закрывать подключение тех клиентов, которые перестали отвечать.
Ещё можно существенно уменьшить тайм-ауты для директив client_body_timeout и send_timeout (дефолтное значение обеих — 60 секунд). Первая — ограничивает время на чтение тела запроса от клиента. Вторая — время ответа клиенту. Таким образом, если клиент не начнёт читать данные в указанный промежуток времени, то Nginx закроет подключение.
И, конечно же, сжатие данных. Плюс — единственный и очевидный: уменьшение размера пересылаемого трафика. Минус — единственный и очевидный: не работает для MSIE 6 и ниже. Отключить сжатие для этих браузеров можно директивой gzip_disable, указав в качестве значения специальную маску “msie6”, которая соответствует регулярному выражению “MSIE [4-6]\.”, но работает быстрее (спасибо hell0w0rd за комментарий).
Пожалуй, это всё, о чём я хотел рассказать. Скажу лишь ещё раз, что не стоит копировать приведенные настройки один в один. Я советую применять их по одной, каждый раз запуская какую-нибудь утилиту для нагрузочного тестирования (например, Tsung). Это весьма важно для понимания, какие настройки реально ускоряют ваш веб-сервер. Методичность в тестировании сэкономит вам уйму времени.
What is keepalive in Nginx
Creating new TCP connections can consume a lot of resources such as memory and CPU usage. However, keeping your connection alive in Nginx can reduce this usage. That’s another reason why keepalive for HTTPS connections is highly recommended. Enabling the keepalive can assist you in improving the user experience and performance of your website. It permits the browser to load page content with a single TCP connection. Another benefit that I would like to mention here is that it also improves the web page speed due to its ability to deliver several files over the same connection, reducing latency and speeding up the loading of the web pages.
How to use keepalive in Nginx
Now, let’s check how we can utilize keepalive connection in Nginx. For this, open up the Nginx configuration file in your nano editor by writing out the below-given in the terminal:

The Nginx configuration file will look like this:

Keepalive connections can improve speed by lowering the network and CPU overhead associated with closing and opening the connections. Keepalives are supported by Nginx for both upstream servers and clients. All client connections are terminated, and after that, Nginx establishes independent connections to the upstream servers.
What is keepalive_timeout in Nginx
The keepalive_timeout value in the Nginx configuration file indicates how long the server has to wait to get requests from a client. In another way, we can say that it indicates the number of seconds an idle keepalive connection will stay open. It is best to leave the idle connection open for about six to ten seconds. If the keepalive_timeout value is set too high, the server will be overloaded, and RAM resources will be wasted. Syntax of keepalive_timeout in Nginx is mentioned below:
Context of keepalive_timeout in Nginx: server, http, and location
Now, in the Nginx configuration file, we are setting the keepalive_timeout value to 10 seconds:

What is keepalive_disable in Nginx
The keepalive_disable option permits you to disable the keepalive feature for specific browser families. The syntax of keepalive_disable in Nginx is:
Context of keepalive_disable in Nginx: server, http, and location
Now, we will only disable the “msie6” browser to utilize the keepalive feature:

What is keepalive_requests in Nginx
Over a single keepalive connection, the keepalive_requests value indicates the maximum number of requests it can handle. The default value for keepalive_requests is 100. However, higher values can be set, which tends to be useful in testing with a load generation utility that sends many requests from a single client. The syntax of keepalive_requests in Nginx is:
Context of keepalive_requests in Nginx: server, http, and location
Now, we will set “100000” as a maximum number of requests that can be served over a single connection:

Keepalive connections in upstream servers
You can enable the keepalive connections for upstream servers, limiting the number of idle keepalive connections stored in each worker process cache. When the upstream server reaches the keepalive value, the connections used the least are closed.
Add the below-given lines in your Nginx configuration file for setting the value for your upstream server:
Here, we have added “16” as the number of idle keepalive connections to an upstream server that remains open. There is no such thing as a default value of keepalive for upstream servers:

To save any of the changes you have made in the Nginx configuration file, press “CTRL+O”:

After that, restart the Nginx service on your system:

Conclusion
Nginx is an efficient HTTP load balancer that can be utilized in various deployment situations, and the feature that assists Nginx in performing this functionality is keepalive. Both upstream servers and clients support keepalive connections. In this post, you have learned about what is keepalive in Nginx. Moreover, we have also explained the keepalive_requests, keepalive_timeout, keepalive_disable directives and their usage in Nginx.
About the author

Sharqa Hameed
I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.
Оптимизация настроек Nginx
Nginx – это быстрый и легкий веб-сервер, альтернатива Apache 2. Конечно же, как и любой сервер, для оптимальной производительности Nginx нуждается в тонкой настройке.
Требования
Для выполнения данного руководства понадобятся:
- новый сервер Debian 7. Чтобы получить инструкции по начальной настройке такого сервера, читайте данную статью.
- установленный и настроенный Nginx. Необходимые инструкции можно найти в статьях “
Директивы worker processes и worker connections
Первые переменные, которые нужно отладить, – worker processes и worker connections.
Директива worker_processes – основа работы Nginx. Она сообщает виртуальному серверу о запущенных рабочих процессах при подключении к правильному IP-адресу или порту. Как правило, на ядро запускается 1 рабочий процесс. Большее количество таких процессов не повредит систему, но может стать причиной простаивания процессов.
Чтобы определить необходимое количество процессов, которое нужно установить в worker_processes, просто посмотрите на количество ядер. Изменив размер сервера, не забудьте проверить количество ядер и соответствующим образом отредактировать значение директивы worker_processes. Чтобы узнать количество ядер, выполните команду grep на cpuinfo:
grep processor /proc/cpuinfo | wc -l
К примеру, если данная команда вернула значение 1, то это значение нужно внести в worker_processes.
Директива worker_connections сообщает директиве worker_processes, сколько пользователей могут одновременно обслуживаться Nginx. Значение по умолчанию – 768. Однако, учитывая, что каждый браузер обычно открывает, по крайней мере, 2 соединения, этого может быть недостаточно. Именно поэтому нужно настроить worker_connections на полную силу. Чтобы проверить ограничения ядра, используйте команду ulimit:
На небольшом сервере (512 Мб) данное значение ограничивается 1024, чего вполне достаточно для начала.
Теперь нужно обновить конфигурационный файл:
sudo nano /etc/nginx/nginx.conf
worker_processes 1;
worker_connections 1024;
Запомните: количество клиентов, которые могут быть обслужены, можно умножить на количество ядер. В этом случае можно обслуживать1024 клиентов в секунду. В дальнейшем это значение уменьшает директива keepalive_timeout.
Буферы
Размер буфера – следующий невероятно важный аспект, который требует тонкой настройки. Если размер буфера слишком мал, то Nginx придется писать во временный файл, из-за чего диску придется постоянно считывать и записывать. Прежде чем принимать какое-либо решение, нужно учесть некоторые директивы.
client_body_buffer_size: данная директива обрабатывает размер буфера клиента, то есть любые POST-запросы, отправленные на Nginx.
client_header_buffer_size: эта директива подобна предыдущей, только вместо размера буфера она обрабатывает размер заголовка клиента. Для всех целей 1K, как правило, достаточно.
client_max_body_size: максимально допустимый размер запроса клиента. Если максимальный размер превышен, то Nginx выведет ошибку 413 (Request Entity Too Large).
large_client_header_buffers: максимальное количество и размер буферов больших заголовков клиентов.
client_body_buffer_size 10K;
client_header_buffer_size 1k;
client_max_body_size 8m;
large_client_header_buffers 2 1k;
Время ожидания
Лимит времени ожидания может также резко повысить производительность.
Директивы client_body_timeout и client_header_timeout отвечают за интервал времени, на протяжении которого сервер будет ждать тело запроса или заголовок запроса от клиента. Если ни тело или заголовок не были получены, сервер выдаст ошибку 408 (Request time out).
Директива keepalive_timeout устанавливает лимит времени ожидания Keep-Alive соединения с клиентом. Проще говоря, Nginx закроет соединения с клиентом по истечении этого периода времени.
Директива send_timeout ограничивает время ответа клиенту. Она устанавливается не на всю передачу ответа, а только на две операции чтения; если по истечении этого времени клиент ничего не примет, то Nginx прервет соединение.
client_body_timeout 12;
client_header_timeout 12;
keepalive_timeout 15;
send_timeout 10;
Сжатие Gzip
Gzip поможет уменьшить количество передач, выполняемых Nginx. Однако, будьте осторожны: установив слишком большое значение gzip_comp_level, сервер начнет расходовать циклы процессора.
gzip on;
gzip_comp_level 2;
gzip_min_length 1000;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain application/x-javascript text/xml text/css application/xml;
Кэширование статических файлов
Можно также настроить выдачу заголовков Expires для файлов, которые не меняются и обслуживаются регулярно. Эту директиву можно добавить к существующему блоку server Nginx.
* .(jpg|jpeg|png|gif|ico|css|js)$ <
expires 365d;
>
Не забудьте добавить необходимые типы файлов в вышеприведенную строку (и удалить ненужные).
Журналирование
Nginx вносит в лог каждый поступивший запрос. При использовании аналитики для мониторинга этого поведения, возможно, потребуется отключить эту функцию. Для этого просто измените директиву access_log:
Сохраните и закройте файл, а затем запустите:
sudo service nginx restart
Итоги
По большому счёту, правильная настройка сервера требует постоянного мониторинга и отладки. Ни одна из выше установленных переменных не закреплена навечно. Запомните: настройки сервера нужно адаптировать согласно каждому уникальному случаю. В дальнейшем может понадобиться увеличить производительность сервера при помощи балансировки нагрузки и горизонтального масштабирования.
Tuning NGINX for Performance

NGINX is well known as a high‑performance load balancer, cache, and web server, powering over 40% of the busiest websites in the world. For most use cases, default NGINX and Linux settings work well, but achieving optimal performance sometimes requires a bit of tuning. This blog post discusses some of the NGINX and Linux settings to consider when tuning a system.
You can tune almost any setting, but this post concentrates on the few settings for which tuning benefits the most users. There are settings that we recommend you change only if you have a deep understanding of NGINX and Linux, or as directed by our Support or Professional Services teams, and we don’t cover those here. The Professional Services team has worked with some of the world’s busiest websites to tune NGINX for the maximum level of performance, and is available to work with you on getting the most out of your NGINX or NGINX Plus deployment.
Introduction
A basic understanding of the NGINX architecture and configuration concepts is assumed. This post does not attempt to duplicate the NGINX documentation, but provides an overview of the various options and links to the relevant documentation.
A good rule to follow when tuning is to change one setting at a time, and set it back to the default value if the change does not improve performance.
We start with a discussion of Linux tuning, because the value of some operating system settings determines how you tune your NGINX configuration.
Tuning Your Linux Configuration
The settings in modern Linux kernels (2.6+) are suitable for most purposes, but changing some of them can be beneficial. Check the kernel log for error messages indicating that a setting is too low, and adjust it as advised. Here we cover only those settings that are most likely to benefit from tuning under normal workloads. For details on adjusting these settings, please refer to your Linux documentation.
The Backlog Queue
The following settings relate to connections and how they are queued. If you have a high rate of incoming connections and you are getting uneven levels of performance (for example some connections appear to be stalling), then changing these settings can help.
net.core.somaxconn – The maximum number of connections that can be queued for acceptance by NGINX. The default is often very low and that’s usually acceptable because NGINX accepts connections very quickly, but it can be worth increasing it if your website experiences heavy traffic. If error messages in the kernel log indicate that the value is too small, increase it until the errors stop.
Note: If you set this to a value greater than 512, change the backlog parameter to the NGINX listen directive to match.
File Descriptors
File descriptors are operating system resources used to represent connections and open files, among other things. NGINX can use up to two file descriptors per connection. For example, if NGINX is proxying, it generally uses one file descriptor for the client connection and another for the connection to the proxied server, though this ratio is much lower if HTTP keepalives are used. For a system serving a large number of connections, the following settings might need to be adjusted:
- sys.fs.file-max – The system‑wide limit for file descriptors
- nofile – The user file descriptor limit, set in the /etc/security/limits.conf file
Ephemeral Ports
When NGINX is acting as a proxy, each connection to an upstream server uses a temporary, or ephemeral, port. You might want to change this setting:
-
net.ipv4.ip_local_port_range – The start and end of the range of port values. If you see that you are running out of ports, increase the range. A common setting is ports 1024 to 65000.
Tuning Your NGINX Configuration
The following are some NGINX directives that can impact performance. As stated above, we only discuss directives that are safe for you to adjust on your own. We recommend that you not change the settings of other directives without direction from the NGINX team.
Worker Processes
NGINX can run multiple worker processes, each capable of processing a large number of simultaneous connections. You can control the number of worker processes and how they handle connections with the following directives:
-
– The number of NGINX worker processes (the default is 1). In most cases, running one worker process per CPU core works well, and we recommend setting this directive to auto to achieve that. There are times when you may want to increase this number, such as when the worker processes have to do a lot of disk I/O. – The maximum number of connections that each worker process can handle simultaneously. The default is 512, but most systems have enough resources to support a larger number. The appropriate setting depends on the size of the server and the nature of the traffic, and can be discovered through testing.
Keepalive Connections
Keepalive connections can have a major impact on performance by reducing the CPU and network overhead needed to open and close connections. NGINX terminates all client connections and creates separate and independent connections to the upstream servers. NGINX supports keepalives for both clients and upstream servers. The following directives relate to client keepalives:
-
– The number of requests a client can make over a single keepalive connection. The default is 100, but a much higher value can be especially useful for testing with a load‑generation tool, which generally sends a large number of requests from a single client. – How long an idle keepalive connection remains open.
The following directive relates to upstream keepalives:
-
– The number of idle keepalive connections to an upstream server that remain open for each worker process. There is no default value.
To enable keepalive connections to upstream servers you must also include the following directives in the configuration:
Access Logging
Logging every request consumes both CPU and I/O cycles, and one way to reduce the impact is to enable access‑log buffering. With buffering, instead of performing a separate write operation for each log entry, NGINX buffers a series of entries and writes them to the file together in a single operation.
To enable access‑log buffering, include the buffer=size parameter to the access_log directive; NGINX writes the buffer contents to the log when the buffer reaches the size value. To have NGINX write the buffer after a specified amount of time, include the flush=time parameter. When both parameters are set, NGINX writes entries to the log file when the next log entry will not fit into the buffer or the entries in the buffer are older than the specified time, respectively. Log entries are also written when a worker process is reopening its log files or shutting down. To disable access logging completely, include the off parameter to the access_log directive.
Sendfile
The operating system’s sendfile() system call copies data from one file descriptor to another, often achieving zero‑copy, which can speed up TCP data transfers. To enable NGINX to use it, include the sendfile directive in the http context or a server or location context. NGINX can then write cached or on‑disk content down a socket without any context switching to user space, making the write extremely fast and consuming fewer CPU cycles. Note, however, that because data copied with sendfile() bypasses user space, it is not subject to the regular NGINX processing chain and filters that change content, such as gzip . When a configuration context includes both the sendfile directive and directives that activate a content‑changing filter, NGINX automatically disables sendfile for that context.
Limits
You can set various limits that help prevent clients from consuming too many resources, which can adversely the performance of your system as well as security and the user experience. The following are some of the relevant directives:
-
and limit_conn_zone – Limit the number of client connections NGINX accepts, for example from a single IP address. Setting them can help prevent individual clients from opening too many connections and consuming more than their share of resources. – Limits the rate at which responses are transmitted to a client, per connection (so clients that open multiple connections can consume this amount of bandwidth for each connection). Setting a limit can prevent the system from being overloaded by certain clients, ensuring more even quality of service for all clients. and limit_req_zone – Limit the rate of requests being processed by NGINX, which has the same benefits as setting limit_rate . They can also improve security, especially for login pages, by limiting the request rate to a value reasonable for human users but too slow for programs trying to overwhelm your application with requests (such as bots in a DDoS attack). parameter to the server directive in an upstream configuration block – Sets the maximum number of simultaneous connections accepted by a server in an upstream group. Imposing a limit can help prevent the upstream servers from being overloaded. Setting the value to 0 (zero, the default) means there is no limit. (NGINX Plus) – Creates a queue in which requests are placed when all the available servers in the upstream group have reached their max_conns limit. This directive sets the maximum number of requests in the queue and, optionally, the maximum time they wait (60 seconds by default) before an error is returned. Requests are not queued if you omit this directive.
Caching and Compression Can Improve Performance
Some additional features of NGINX that can be used to increase the performance of a web application don’t really fall under the heading of tuning, but are worth mentioning because their impact can be considerable. They include caching and compression.
Caching
By enabling caching on an NGINX instance that is load balancing a set of web or application servers, you can dramatically improve the response time to clients while at the same time dramatically reducing the load on the backend servers. Caching is a topic in its own right and we won’t try to cover it here. See the NGINX Plus Admin Guide.
Compression
Compressing responses sent to clients can greatly reduce their size, so they use less network bandwidth. Because compressing data consumes CPU resources, however, it is most useful when it’s really worthwhile to reduce bandwidth usage. It is important to note that you should not enable compression for objects that are already compressed, such as JPEG files. For more information, see the NGINX Plus Admin Guide.
For more information, see:
-
(on‑demand webinar) at nginx.org
To try NGINX Plus, start your free 30-day trial today or contact us for a demo.