upstream nginx что это

Балансировка нагрузки с помощью NGINX

В данной инструкции мы рассмотрим процесс настройки балансировки, в основном, http-запросов с помощью веб-сервера NGINX. По большей части, инструкция подойдет для любого дистрибутива Linux, и даже, Windows (за исключением путей расположения конфигурационных файлов). Таким образом настроенный NGINX сможет обеспечить распределение нагрузки и отказоустойчивость нашим сетевым сервисам.

Обратите внимание, что NGINX умеет распределять не только http-запросы. Его можно использовать для балансировки запросов на 4-м уровне модели OSI (TCP и UDP), например, подключения к СУБД, DNS и так далее — по сути, любой сетевой запрос может быть обработан и распределен с помощью данного программного продукта.

Постепенно рассмотрим разные варианты настройки распределения нагрузки в NGINX. Начнем с простого понимания, как работает данная функция и закончим некоторыми примерами настройки балансировки.

Основы

Чтобы наш сервер мог распределять нагрузку, создадим группу веб-серверов, на которые будут переводиться запросы:

* в данном примере мы создаем файл upstreams.conf, в котором можем хранить все наши апстримы. NGINX автоматически читает все конфигурационные файлы в каталоге conf.d.

upstream dmosk_backend <
server 192.168.10.10;
server 192.168.10.11;
server 192.168.10.12;
>

* предполагается, что в нашей внутренней сети есть кластер из трех веб-серверов — 192.168.10.10, 192.168.10.11 и 192.168.10.12. Мы создали апстрим с названием dmosk_backend. Позже, мы настроим веб-сервер, чтобы он умел обращаться к данному бэкенду.

В настройках сайта (виртуального домена) нам необходимо теперь проксировать запросы на созданный upstream. Данная настройка будет такой:

server <
.
location / <
proxy_pass http://dmosk_backend;
>
.
>

* данная настройка для нашего сайта укажет, что все запросы мы должны переводить на апстрим dmosk_backend (который, в свою очередь, будет отправлять запросы на три сервера).

Проверяем корректность нашего конфигурационного файла:

Если ошибок нет, перезапускаем сервис:

systemctl restart nginx

Приоритеты

При настройке бэкендов мы можем указать, кому наш веб-сервер будет отдавать больше предпочтение, а кому меньше.

Синтаксис при указании веса:

По умолчанию приоритет равен 1.

Также мы можем указать опции:

Давайте немного преобразуем нашу настройку upstreams:

upstream dmosk_backend <
server 192.168.10.10 weight=100 ;
server 192.168.10.11 weight=10 ;
server 192.168.10.12;
server 192.168.10.13 backup ;
>

* итак, мы указали нашему серверу:

Задержки, лимиты и таймауты

По умолчанию, NGINX будет считать сервер недоступным после 1-й неудачной попытки отправить на него запрос и в течение 10 секунд не будут продолжаться попытки работы с ним. Также каждый сервер не имеет ограничений по количеству к нему подключений.

Изменить поведение лимитов и ограничений при балансировке можно с помощью опций:

server max_fails= fail_timeout= ;

В нашем примере мы преобразуем настройку так:

upstream dmosk_backend <
server 192.168.10.10 weight=100 max_conns=1000 ;
server 192.168.10.11 weight=10 max_fails=2 fail_timeout=90s ;
server 192.168.10.12 max_fails=3 fail_timeout=2m ;
server 192.168.10.13 backup;
>

Метод балансировки

Рассмотрим способы балансировки, которые можно использовать в NGINX:

Настройка метода балансировки выполняется в директиве upstream. Синтаксис:

Round Robin

Веб-сервер будет передавать запросы бэкендам по очереди с учетом их весов. Данный метод является методом по умолчанию и его указывать в конфигурационном файле не нужно.

Данный метод определяет контрольную сумму на основе переменных веб-сервера и ассоциирует каждый полученный результат с конкретным бэкендом. Пример настройки:

* это самый распространенный пример настройки hash — с использованием переменных $scheme (http или https) и $request_uri. При данной настройке каждый конкретный URL будет ассоциирован с конкретным сервером.

IP Hash

Ассоциация выполняется исходя из IP-адреса клиента и только для HTTP-запросов. Таким образом, для каждого посетителя устанавливается связь с одним и тем же сервером. Это, так называемый, Sticky Session метод.

Для адресов IPv4 учитываются только первые 3 октета — это позволяет поддерживать одинаковые соединения с клиентами, чьи адреса меняются (получение динамических адресов от DHCP провайдера). Для адресов IPv6 учитывается адрес целиком.

upstream dmosk_backend <
ip_hash;
server 192.168.10.10;
server 192.168.10.11;
server 192.168.10.12;
>

Least Connections

NGINX определяет, с каким бэкендом меньше всего соединений в данный момент и перенаправляет запрос на него (с учетом весов).

Настройка выполняется с помощью опции least_conn:

upstream dmosk_backend <
least_conn;
server 192.168.10.10;
server 192.168.10.11;
server 192.168.10.12;
>

Random

Запросы передаются случайным образом (но с учетом весов). Дополнительно можно указать опцию two — если она задана, то NGINX сначала выберет 2 сервера случайным образом, затем на основе дополнительных параметров отдаст предпочтение одному из них. Это следующие параметры:

upstream dmosk_backend <
random two least_conn;
server 192.168.10.10;
server 192.168.10.11;
server 192.168.10.12;
>

Least Time

Данная опция будет работать только в NGINX Plus. Балансировка выполняется исходя из времени ответа сервера. Предпочтение отдается тому, кто отвечает быстрее.

Опция для указания данного метода — least_time. Также необходимо указать, что мы считаем ответом — получение заголовка (header) или когда страница возвращается целиком (last_byte).

upstream dmosk_backend <
least_time header;
server 192.168.10.10;
server 192.168.10.11;
server 192.168.10.12;
>

* в данном примере мы будем делать расчет исходя из того, как быстро мы получаем в ответ заголовки.

upstream dmosk_backend <
least_time last_byte;
server 192.168.10.10;
server 192.168.10.11;
server 192.168.10.12;
>

* в данном примере мы будем делать расчет исходя из того, как быстро мы получаем в ответ целую страницу.

Сценарии настройки

В реальной жизни настройки могут быть несколько сложнее, чем приведенные здесь или в официальной документации. Рассмотрим несколько примеров, что может понадобиться настроить при балансировке.

1. Backend на https

Предположим, что наши внутренние серверы отвечают по SSL-каналу. Таким образом, нам нужно отправлять запрос по порту 443. Также схема проксирования должна быть https.

Настройка сайта:

* обратите внимание на 2 момента:

Настройка upstream:

upstream dmosk_backend <
server 192.168.10.10:443;
server 192.168.10.11:443;
server 192.168.10.12:443;
>

* в данном примере мы указали конкретный порт, по которому должно выполняться соединение с бэкендом. Для упрощения конфига дополнительные опции упущены.

2. Разные бэкенды для разных страниц

Нам может понадобиться разные страницы сайта переводить на разные группы внутренних серверов.

Настройка сайта:

server <
.
location /page1 <
proxy_pass http://backend1;
>

location /page2 <
proxy_pass http://backend2;
>
.
>

* при такой настройке мы будем передавать запросы к странице page1 на группу backend1, а к page2backend2.

Настройка upstream:

upstream backend1 <
server 192.168.10.10;
server 192.168.10.11;
>

upstream backend2 <
server 192.168.10.12;
server 192.168.10.13;
>

* в данном примере у нас есть 2 апстрима, каждый со своим набором серверов.

3. На другой хост

Может быть необходимым делать обращение к внутреннему ресурсу по другому hostname, нежели чем будет обращение к внешнему. Для этого в заголовках проксирования мы должны указать опцию Host.

Настройка сайта:

* в данном примере мы будем проксировать запросы на бэкенды, передавая им имя хоста internal.domain.com.

4. TCP-запрос

Рассмотрим, в качестве исключения, TCP-запрос на порт 5432 — подключение к базе PostgreSQL.

Настройка сайта:

server <
listen 5432;
proxy_pass tcp_postgresql;
>

* в данном примере мы слушаем TCP-порт 5432 и проксируем все запросы на апстрим tcp_postgresql.

Настройка upstream:

upstream tcp_postgresql <
server 192.168.10.14:5432;
server 192.168.10.15:5432;
>

* запросы будут случайным образом передаваться на серверы 192.168.10.14 и 192.168.10.15.

5. UDP-запрос

Рассмотрим также и возможность балансировки UDP-запросов — подключение к DNS по порту 53.

Настройка сайта:

server <
listen 53 udp;
proxy_pass udp_dns;
proxy_responses 1;
>

* в данном примере мы слушаем UDP-порт 53 и проксируем все запросы на апстрим udp_dns. Опция proxy_responses говорит о том, что на один запрос нужно давать один ответ.

Настройка upstream:

upstream udp_dns <
server 192.168.10.16:53;
server 192.168.10.17:53;
>

* запросы будут случайным образом передаваться на серверы 192.168.10.16 и 192.168.10.17.

Читайте также

Возможно, данные инструкции также будут полезны:

Источник

Upstream nginx что это

Модуль ngx_http_upstream_module позволяет описывать группы серверов, которые могут использоваться в директивах proxy_pass, fastcgi_pass и memcached_pass.

Пример конфигурации

Директивы

Описывает группу серверов. Серверы могут слушать на разных портах. Кроме того, можно одновременно использовать серверы, слушающие на TCP- и UNIX-сокетах.

По умолчанию запросы распределяются по серверам циклически (в режиме round-robin) с учётом весов серверов. В вышеприведённом примере каждые 7 запросов будут распределены так: 5 запросов на backend1.example.com и по одному запросу на второй и третий серверы. Если при попытке работы с сервером произошла ошибка, то запрос будет передан следующему серверу, и так до тех пор, пока не будут опробованы все работающие серверы. Если не удастся получить успешный ответ ни от одного из серверов, то клиенту будет возвращён результат работы с последним сервером.

синтаксис:server адрес [ параметры ];
умолчание:
контекст:upstream

Задаёт адрес и другие параметры сервера. Адрес может быть указан в виде доменного имени или IP-адреса, и необязательного порта, или в виде пути UNIX-сокета, который указывается после префикса “ unix: ”. Если порт не указан, используется порт 80. Доменное имя, которому соответствует несколько IP-адресов, задаёт сразу несколько серверов.

Могут быть заданы следующие параметры:

Задаёт для группы метод балансировки нагрузки, при котором запросы распределяются по серверам на основе IP-адресов клиентов. В качестве ключа для хэширования используются первые три октета IPv4-адреса клиента или IPv6-адрес клиента целиком. Метод гарантирует, что запросы одного и того же клиента будут всегда передаваться на один и тот же сервер. Если же этот сервер будет считаться неработающим, то запросы этого клиента будут передаваться на другой сервер. С большой долей вероятности это также будет один и тот же сервер.

IPv6-адреса поддерживаются начиная с версий 1.3.2 и 1.2.2.

синтаксис:keepalive соединения ;
умолчание:
контекст:upstream

Эта директива появилась в версии 1.1.4.

Задействует кэш соединений для группы серверов.

Параметр соединения устанавливает максимальное число неактивных постоянных соединений с серверами группы, которые будут сохраняться в кэше каждого рабочего процесса. При превышении этого числа наиболее давно не используемые соединения закрываются.

Следует особо отметить, что директива keepalive не ограничивает общее число соединений с серверами группы, которые рабочие процессы nginx могут открыть. Параметр соединения следует устанавливать достаточно консервативно для обеспечения возможности обработки серверами группы новых входящих соединений.

Пример конфигурации группы серверов memcached с постоянными соединениями:

Для HTTP директиву proxy_http_version следует установить в “ 1.1 ”, а поле заголовка “Connection” — очистить:

Хоть это и не рекомендуется, но также возможно использование постоянных соединений в HTTP/1.0, путём передачи поля заголовка “Connection: Keep-Alive” серверу группы.

Для работы постоянных соединений с FastCGI-серверами потребуется включить директиву fastcgi_keep_conn:

Протоколы SCGI и uwsgi не определяют семантику постоянных соединений.

синтаксис:least_conn;
умолчание:
контекст:upstream

Эта директива появилась в версиях 1.3.1 и 1.2.2.

Задаёт для группы метод балансировки нагрузки, при котором запрос передаётся серверу с наименьшим числом активных соединений, с учётом весов серверов. Если подходит сразу несколько серверов, они выбираются циклически (в режиме round-robin) с учётом их весов.

Встроенные переменные

Модуль ngx_http_upstream_module поддерживает следующие встроенные переменные:

Источник

upstream nginx что это. Смотреть фото upstream nginx что это. Смотреть картинку upstream nginx что это. Картинка про upstream nginx что это. Фото upstream nginx что это

Модуль ngx_stream_upstream_module

Модуль ngx_stream_upstream_module (1.9.0) позволяет описывать группы серверов, которые могут использоваться в директиве proxy_pass.

Пример конфигурации

Динамически настраиваемая группа с периодическими проверками работоспособности доступна как часть коммерческой подписки:

Директивы

Описывает группу серверов. Серверы могут слушать на разных портах. Кроме того, можно одновременно использовать серверы, слушающие на TCP- и UNIX-сокетах.

По умолчанию соединения распределяются по серверам циклически (в режиме round-robin) с учётом весов серверов. В вышеприведённом примере каждые 7 соединений будут распределены так: 5 соединений на backend1.example.com:12345 и по одному соединению на второй и третий серверы. Если при попытке работы с сервером происходит ошибка, то соединение передаётся следующему серверу, и так далее до тех пор, пока не будут опробованы все работающие серверы. Если связь с серверами не удалась, соединение будет закрыто.

Синтаксис:server адрес [ параметры ];
Умолчание:
Контекст:upstream

Задаёт адрес и другие параметры сервера. Адрес может быть указан в виде доменного имени или IP-адреса, и обязательного порта, или в виде пути UNIX-сокета, который указывается после префикса “ unix: ”. Доменное имя, которому соответствует несколько IP-адресов, задаёт сразу несколько серверов.

Могут быть заданы следующие параметры:

weight = число задаёт вес сервера, по умолчанию 1. max_conns = число ограничивает максимальное число одновременных соединений к проксируемому серверу (1.11.5). Значение по умолчанию равно 0 и означает, что ограничения нет. Если группа не находится в зоне разделяемой памяти, то ограничение работает отдельно для каждого рабочего процесса.

До версии 1.11.5 этот параметр был доступен как часть коммерческой подписки.

Параметр нельзя использовать совместно с методами балансировки нагрузки hash и random.

Кроме того, следующие параметры доступны как часть коммерческой подписки:

resolve отслеживает изменения IP-адресов, соответствующих доменному имени сервера, и автоматически изменяет конфигурацию группы без необходимости перезапуска nginx. Группа должна находиться в зоне разделяемой памяти.

Для работы этого параметра директива resolver должна быть задана в блоке stream или в соответствующем блоке upstream.

service = имя включает преобразование SRV-записей DNS и задаёт имя сервиса (1.9.13). Для работы параметра необходимо указать параметр resolve для сервера и не указывать порт сервера.

Если имя сервиса содержит одну и более точек, то имя составляется при помощи соединения префикса службы и имени сервера. Например, для получения SRV-записей _http._tcp.backend.example.com и server1.backend.example.com необходимо указать директивы:

SRV-записи с наивысшим приоритетом (записи с одинаковым наименьшим значением приоритета) преобразуются в основные серверы, остальные SRV-записи преобразуются в запасные серверы. Если в конфигурации сервера указан параметр backup, высокоприоритетные SRV-записи преобразуются в запасные серверы, остальные SRV-записи игнорируются.

Параметр нельзя использовать совместно с методами балансировки нагрузки hash и random.

Синтаксис:zone имя [ размер ];
Умолчание:
Контекст:upstream

Задаёт имя и размер зоны разделяемой памяти, в которой хранятся конфигурация группы и её рабочее состояние, разделяемые между рабочими процессами. В одной и той же зоне могут быть сразу несколько групп. В этом случае достаточно указать размер только один раз.

Дополнительно, как часть коммерческой подписки, в таких группах для изменения состава группы или настроек отдельных серверов нет необходимости перезапускать nginx. Конфигурация доступна через модуль API (1.13.3).

До версии 1.13.3 конфигурация была доступна только через специальный location, в котором указана директива upstream_conf.

Синтаксис:state файл ;
Умолчание:
Контекст:upstream

Эта директива появилась в версии 1.9.7.

В данный момент состояние ограничено списком серверов с их параметрами. Файл читается при парсинге конфигурации и обновляется каждый раз при изменении конфигурации группы. Изменение содержимого файла напрямую не рекомендуется. Директиву нельзя использовать совместно с директивой server.

Синтаксис:hash ключ [ consistent ];
Умолчание:
Контекст:upstream

Следует отметить, что любое добавление или удаление серверов в группе может привести к перераспределению большинства ключей на другие серверы. Метод совместим с библиотекой Perl Cache::Memcached.

Синтаксис:least_conn;
Умолчание:
Контекст:upstream

Задаёт для группы метод балансировки нагрузки, при котором соединение передаётся серверу с наименьшим числом активных соединений, с учётом весов серверов. Если подходит сразу несколько серверов, они выбираются циклически (в режиме round-robin) с учётом их весов.

Синтаксис:least_time connect | first_byte | last_byte [ inflight ];
Умолчание:
Контекст:upstream

Задаёт для группы метод балансировки нагрузки, при котором соединение передаётся серверу с наименьшими средним временем ответа и числом активных соединений с учётом весов серверов. Если подходит сразу несколько серверов, то они выбираются циклически (в режиме round-robin) с учётом их весов.

До версии 1.11.6 незавершённые соединения учитывались по умолчанию.

Синтаксис:random [ two [ метод ]];
Умолчание:
Контекст:upstream

Эта директива появилась в версии 1.15.1.

Задаёт для группы метод балансировки нагрузки, при котором соединение передаётся случайно выбранному серверу, с учётом весов серверов.

Эта директива появилась в версии 1.17.5.

Задаёт серверы DNS, используемые для преобразования имён вышестоящих серверов в адреса, например:

Адрес может быть указан в виде доменного имени или IP-адреса, и необязательного порта. Если порт не указан, используется порт 53. Серверы DNS опрашиваются циклически.

По умолчанию nginx кэширует ответы, используя значение TTL из ответа. Необязательный параметр valid позволяет это переопределить:

Для предотвращения DNS-спуфинга рекомендуется использовать DNS-серверы в защищённой доверенной локальной сети.

Синтаксис:resolver_timeout время ;
Умолчание:
Контекст:upstream

Эта директива появилась в версии 1.17.5.

Задаёт таймаут для преобразования имени в адрес, например:

Встроенные переменные

Модуль ngx_stream_upstream_module поддерживает следующие встроенные переменные:

Источник

upstream nginx что это. Смотреть фото upstream nginx что это. Смотреть картинку upstream nginx что это. Картинка про upstream nginx что это. Фото upstream nginx что это

Module ngx_http_upstream_module

The ngx_http_upstream_module module is used to define groups of servers that can be referenced by the proxy_pass, fastcgi_pass, uwsgi_pass, scgi_pass, memcached_pass, and grpc_pass directives.

Example Configuration

Dynamically configurable group with periodic health checks is available as part of our commercial subscription:

Directives

Defines a group of servers. Servers can listen on different ports. In addition, servers listening on TCP and UNIX-domain sockets can be mixed.

By default, requests are distributed between the servers using a weighted round-robin balancing method. In the above example, each 7 requests will be distributed as follows: 5 requests go to backend1.example.com and one request to each of the second and third servers. If an error occurs during communication with a server, the request will be passed to the next server, and so on until all of the functioning servers will be tried. If a successful response could not be obtained from any of the servers, the client will receive the result of the communication with the last server.

Syntax:server address [ parameters ];
Default:
Context:upstream

Defines the address and other parameters of a server. The address can be specified as a domain name or IP address, with an optional port, or as a UNIX-domain socket path specified after the “ unix: ” prefix. If a port is not specified, the port 80 is used. A domain name that resolves to several IP addresses defines multiple servers at once.

The following parameters can be defined:

weight = number sets the weight of the server, by default, 1. max_conns = number limits the maximum number of simultaneous active connections to the proxied server (1.11.5). Default value is zero, meaning there is no limit. If the server group does not reside in the shared memory, the limitation works per each worker process.

If idle keepalive connections, multiple workers, and the shared memory are enabled, the total number of active and idle connections to the proxied server may exceed the max_conns value.

Since version 1.5.9 and prior to version 1.11.5, this parameter was available as part of our commercial subscription.

The parameter cannot be used along with the hash, ip_hash, and random load balancing methods.

Additionally, the following parameters are available as part of our commercial subscription:

resolve monitors changes of the IP addresses that correspond to a domain name of the server, and automatically modifies the upstream configuration without the need of restarting nginx (1.5.12). The server group must reside in the shared memory.

In order for this parameter to work, the resolver directive must be specified in the http block or in the corresponding upstream block.

route = string sets the server route name. service = name enables resolving of DNS SRV records and sets the service name (1.9.13). In order for this parameter to work, it is necessary to specify the resolve parameter for the server and specify a hostname without a port number.

If the service name contains one or more dots, then the name is constructed by joining the service prefix and the server name. For example, to look up the _http._tcp.backend.example.com and server1.backend.example.com SRV records, it is necessary to specify the directives:

Highest-priority SRV records (records with the same lowest-number priority value) are resolved as primary servers, the rest of SRV records are resolved as backup servers. If the backup parameter is specified for the server, high-priority SRV records are resolved as backup servers, the rest of SRV records are ignored.

slow_start = time sets the time during which the server will recover its weight from zero to a nominal value, when unhealthy server becomes healthy, or when the server becomes available after a period of time it was considered unavailable. Default value is zero, i.e. slow start is disabled.

The parameter cannot be used along with the hash, ip_hash, and random load balancing methods.

Prior to version 1.13.6, the parameter could be changed only with the API module.

Syntax:zone name [ size ];
Default:
Context:upstream

This directive appeared in version 1.9.0.

Defines the name and size of the shared memory zone that keeps the group’s configuration and run-time state that are shared between worker processes. Several groups may share the same zone. In this case, it is enough to specify the size only once.

Additionally, as part of our commercial subscription, such groups allow changing the group membership or modifying the settings of a particular server without the need of restarting nginx. The configuration is accessible via the API module (1.13.3).

Prior to version 1.13.3, the configuration was accessible only via a special location handled by upstream_conf.

This directive appeared in version 1.9.7.

Specifies a file that keeps the state of the dynamically configurable group.

The state is currently limited to the list of servers with their parameters. The file is read when parsing the configuration and is updated each time the upstream configuration is changed. Changing the file content directly should be avoided. The directive cannot be used along with the server directive.

Syntax:hash key [ consistent ];
Default:
Context:upstream

This directive appeared in version 1.7.2.

Specifies a load balancing method for a server group where the client-server mapping is based on the hashed key value. The key can contain text, variables, and their combinations. Note that adding or removing a server from the group may result in remapping most of the keys to different servers. The method is compatible with the Cache::Memcached Perl library.

If the consistent parameter is specified, the ketama consistent hashing method will be used instead. The method ensures that only a few keys will be remapped to different servers when a server is added to or removed from the group. This helps to achieve a higher cache hit ratio for caching servers. The method is compatible with the Cache::Memcached::Fast Perl library with the ketama_points parameter set to 160.

Specifies that a group should use a load balancing method where requests are distributed between servers based on client IP addresses. The first three octets of the client IPv4 address, or the entire IPv6 address, are used as a hashing key. The method ensures that requests from the same client will always be passed to the same server except when this server is unavailable. In the latter case client requests will be passed to another server. Most probably, it will always be the same server as well.

IPv6 addresses are supported starting from versions 1.3.2 and 1.2.2.

If one of the servers needs to be temporarily removed, it should be marked with the down parameter in order to preserve the current hashing of client IP addresses.

Until versions 1.3.1 and 1.2.2, it was not possible to specify a weight for servers using the ip_hash load balancing method.

Syntax:keepalive connections ;
Default:
Context:upstream

This directive appeared in version 1.1.4.

Activates the cache for connections to upstream servers.

The connections parameter sets the maximum number of idle keepalive connections to upstream servers that are preserved in the cache of each worker process. When this number is exceeded, the least recently used connections are closed.

It should be particularly noted that the keepalive directive does not limit the total number of connections to upstream servers that an nginx worker process can open. The connections parameter should be set to a number small enough to let upstream servers process new incoming connections as well.

When using load balancing methods other than the default round-robin method, it is necessary to activate them before the keepalive directive.

Example configuration of memcached upstream with keepalive connections:

For HTTP, the proxy_http_version directive should be set to “ 1.1 ” and the “Connection” header field should be cleared:

Alternatively, HTTP/1.0 persistent connections can be used by passing the “Connection: Keep-Alive” header field to an upstream server, though this method is not recommended.

For FastCGI servers, it is required to set fastcgi_keep_conn for keepalive connections to work:

SCGI and uwsgi protocols do not have a notion of keepalive connections.

Syntax:keepalive_requests number ;
Default:
Context:upstream

This directive appeared in version 1.15.3.

Sets the maximum number of requests that can be served through one keepalive connection. After the maximum number of requests is made, the connection is closed.

Closing connections periodically is necessary to free per-connection memory allocations. Therefore, using too high maximum number of requests could result in excessive memory usage and not recommended.

Prior to version 1.19.10, the default value was 100.

Syntax:keepalive_time time ;
Default:
Context:upstream

This directive appeared in version 1.19.10.

Limits the maximum time during which requests can be processed through one keepalive connection. After this time is reached, the connection is closed following the subsequent request processing.

Syntax:keepalive_timeout timeout ;
Default:
Context:upstream

This directive appeared in version 1.15.3.

Sets a timeout during which an idle keepalive connection to an upstream server will stay open.

This directive appeared in version 1.9.2.

Allows proxying requests with NTLM Authentication. The upstream connection is bound to the client connection once the client sends a request with the “Authorization” header field value starting with “ Negotiate ” or “ NTLM ”. Further client requests will be proxied through the same upstream connection, keeping the authentication context.

In order for NTLM authentication to work, it is necessary to enable keepalive connections to upstream servers. The proxy_http_version directive should be set to “ 1.1 ” and the “Connection” header field should be cleared:

When using load balancer methods other than the default round-robin method, it is necessary to activate them before the ntlm directive.

This directive appeared in versions 1.3.1 and 1.2.2.

Specifies that a group should use a load balancing method where a request is passed to the server with the least number of active connections, taking into account weights of servers. If there are several such servers, they are tried in turn using a weighted round-robin balancing method.

Syntax:least_time header | last_byte [ inflight ];
Default:
Context:upstream

This directive appeared in version 1.7.10.

Specifies that a group should use a load balancing method where a request is passed to the server with the least average response time and least number of active connections, taking into account weights of servers. If there are several such servers, they are tried in turn using a weighted round-robin balancing method.

If the header parameter is specified, time to receive the response header is used. If the last_byte parameter is specified, time to receive the full response is used. If the inflight parameter is specified (1.11.6), incomplete requests are also taken into account.

Prior to version 1.11.6, incomplete requests were taken into account by default.

Syntax:queue number [ timeout = time ];
Default:
Context:upstream

This directive appeared in version 1.5.12.

If an upstream server cannot be selected immediately while processing a request, the request will be placed into the queue. The directive specifies the maximum number of requests that can be in the queue at the same time. If the queue is filled up, or the server to pass the request to cannot be selected within the time period specified in the timeout parameter, the 502 (Bad Gateway) error will be returned to the client.

The default value of the timeout parameter is 60 seconds.

When using load balancer methods other than the default round-robin method, it is necessary to activate them before the queue directive.

Syntax:random [ two [ method ]];
Default:
Context:upstream

This directive appeared in version 1.15.1.

Specifies that a group should use a load balancing method where a request is passed to a randomly selected server, taking into account weights of servers.

The least_time method passes a request to a server with the least average response time and least number of active connections. If least_time=header is specified, the time to receive the response header is used. If least_time=last_byte is specified, the time to receive the full response is used.

The least_time method is available as a part of our commercial subscription.

This directive appeared in version 1.17.5.

Configures name servers used to resolve names of upstream servers into addresses, for example:

The address can be specified as a domain name or IP address, with an optional port. If port is not specified, the port 53 is used. Name servers are queried in a round-robin fashion.

By default, nginx will look up both IPv4 and IPv6 addresses while resolving. If looking up of IPv6 addresses is not desired, the ipv6=off parameter can be specified.

By default, nginx caches answers using the TTL value of a response. An optional valid parameter allows overriding it:

To prevent DNS spoofing, it is recommended configuring DNS servers in a properly secured trusted local network.

Syntax:resolver_timeout time ;
Default:
Context:upstream

This directive appeared in version 1.17.5.

Sets a timeout for name resolution, for example:

This directive appeared in version 1.5.7.

Enables session affinity, which causes requests from the same client to be passed to the same server in a group of servers. Three methods are available:

When the cookie method is used, information about the designated server is passed in an HTTP cookie generated by nginx:

A request that comes from a client not yet bound to a particular server is passed to the server selected by the configured balancing method. Further requests with this cookie will be passed to the designated server. If the designated server cannot process a request, the new server is selected as if the client has not been bound yet.

The first parameter sets the name of the cookie to be set or inspected. The cookie value is a hexadecimal representation of the MD5 hash of the IP address and port, or of the UNIX-domain socket path. However, if the “ route ” parameter of the server directive is specified, the cookie value will be the value of the “ route ” parameter:

Additional parameters may be as follows:

If any parameters are omitted, the corresponding cookie fields are not set.

When the route method is used, proxied server assigns client a route on receipt of the first request. All subsequent requests from this client will carry routing information in a cookie or URI. This information is compared with the “ route ” parameter of the server directive to identify the server to which the request should be proxied. If the “ route ” parameter is not specified, the route name will be a hexadecimal representation of the MD5 hash of the IP address and port, or of the UNIX-domain socket path. If the designated server cannot process a request, the new server is selected by the configured balancing method as if there is no routing information in the request.

The parameters of the route method specify variables that may contain routing information. The first non-empty variable is used to find the matching server.

Here, the route is taken from the “ JSESSIONID ” cookie if present in a request. Otherwise, the route from the URI is used.

When the learn method (1.7.1) is used, nginx analyzes upstream server responses and learns server-initiated sessions usually passed in an HTTP cookie.

In the example, the upstream server creates a session by setting the cookie “ EXAMPLECOOKIE ” in the response. Further requests with this cookie will be passed to the same server. If the server cannot process the request, the new server is selected as if the client has not been bound yet.

The parameters create and lookup specify variables that indicate how new sessions are created and existing sessions are searched, respectively. Both parameters may be specified more than once, in which case the first non-empty variable is used.

Sessions are stored in a shared memory zone, whose name and size are configured by the zone parameter. One megabyte zone can store about 4000 sessions on the 64-bit platform. The sessions that are not accessed during the time specified by the timeout parameter get removed from the zone. By default, timeout is set to 10 minutes.

The header parameter (1.13.1) allows creating a session right after receiving response headers from the upstream server.

The sync parameter (1.13.8) enables synchronization of the shared memory zone.

Syntax:sticky_cookie_insert name [ expires= time ] [ domain= domain ] [ path= path ];
Default:
Context:upstream

This directive is obsolete since version 1.5.7. An equivalent sticky directive with a new syntax should be used instead:

sticky cookie name [ expires= time ] [ domain= domain ] [ path= path ];

Embedded Variables

The ngx_http_upstream_module module supports the following embedded variables:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *