# HG changeset patch # User Ruslan Ermilov # Date 1428596334 -10800 # Node ID f5b5eefc43cb67e82e40fa27cdf0d68a3ff23294 # Parent c79501e16e26c7a6b2a99606ca4da3b54461b722 Updated commercial docs for the upcoming release. diff --git a/xml/en/GNUmakefile b/xml/en/GNUmakefile --- a/xml/en/GNUmakefile +++ b/xml/en/GNUmakefile @@ -80,6 +80,7 @@ REFS = \ http/ngx_http_stub_status_module \ http/ngx_http_sub_module \ http/ngx_http_upstream_module \ + http/ngx_http_upstream_conf_module \ http/ngx_http_userid_module \ http/ngx_http_uwsgi_module \ http/ngx_http_xslt_module \ @@ -92,6 +93,7 @@ REFS = \ mail/ngx_mail_ssl_module \ stream/ngx_stream_core_module \ stream/ngx_stream_proxy_module \ + stream/ngx_stream_ssl_module \ stream/ngx_stream_upstream_module \ TOP = \ diff --git a/xml/en/docs/http/ngx_http_status_module.xml b/xml/en/docs/http/ngx_http_status_module.xml --- a/xml/en/docs/http/ngx_http_status_module.xml +++ b/xml/en/docs/http/ngx_http_status_module.xml @@ -9,7 +9,7 @@ + rev="6">
@@ -32,40 +32,58 @@ This module is available as part of our -upstream backend { - zone upstream_backend 64k; +http { + upstream backend { + zone http_backend 64k; + + server backend1.example.com weight=5; + server backend2.example.com; + } + + proxy_cache_path /data/nginx/cache_backend keys_zone=cache_backend:10m; + + server { + server_name backend.example.com; + + location / { + proxy_pass http://backend; + proxy_cache cache_backend; - server backend1.example.com weight=5; - server backend2.example.com; + health_check; + } + + status_zone server_backend; + } + + server { + listen 127.0.0.1; + + location /upstream_conf { + upstream_conf; + } + + location /status { + status; + } + + location = /status.html { + } + } } -proxy_cache_path /data/nginx/cache_backend keys_zone=cache_backend:10m; - -server { - server_name backend.example.com; +stream { + upstream backend { + zone stream_backend 64k; - location / { - proxy_pass http://backend; - proxy_cache cache_backend; - - health_check; + server backend1.example.com:12345 weight=5; + server backend2.example.com:12345; } - status_zone server_backend; -} - -server { - listen 127.0.0.1; - - location /upstream_conf { - upstream_conf; - } - - location /status { - status; - } - - location = /status.html { + server { + listen 127.0.0.1:12345; + proxy_pass backend; + status_zone server_backend; + health_check; } } @@ -81,6 +99,11 @@ http://127.0.0.1/status/upstreams http://127.0.0.1/status/upstreams/backend http://127.0.0.1/status/upstreams/backend/1 http://127.0.0.1/status/upstreams/backend/1/weight +http://127.0.0.1/status/stream +http://127.0.0.1/status/stream/upstreams +http://127.0.0.1/status/stream/upstreams/backend +http://127.0.0.1/status/stream/upstreams/backend/1 +http://127.0.0.1/status/stream/upstreams/backend/1/weight @@ -138,9 +161,11 @@ then “ngx_status_jsonp_callback” is used. Enables collection of virtual - -status information in the specified zone. -Several virtual servers may share the same zone. +http +or +stream +(1.7.11) server status information in the specified zone. +Several servers may share the same zone. @@ -157,7 +182,7 @@ The following status information is prov version Version of the provided data set. -The current version is 4. +The current version is 5. nginx_version @@ -170,6 +195,12 @@ Version of nginx. The address of the server that accepted status request. +generation + +The total number of configuration +reloads. + + load_timestamp Time of the last reload of configuration, in milliseconds since Epoch. @@ -180,6 +211,19 @@ Time of the last reload of configuration Current time in milliseconds since Epoch. +processes + + + +respawned + +The total number of abnormally terminated and respawned +child processes. + + + + + connections @@ -330,11 +374,13 @@ or The current number of active connections. + max_conns @@ -451,6 +497,26 @@ The time (in milliseconds since Epoch) when the server was last selected to process a request (1.7.5). +header_time + +The average time to get the +response +header from the server (1.7.10). +The field is available when using the + +load balancing method. + + +response_time + +The average time to get the +full +response from the server (1.7.10). +The field is available when using the + +load balancing method. + + @@ -537,6 +603,206 @@ The total number of bytes written to the +stream + + + +server_zones + +For each : + + +processing + +The number of +client connections that are currently being processed. + + +connections + +The total number of +connections accepted from clients. + + +received + +The total number of bytes received from clients. + + +sent + +The total number of bytes sent to clients. + + + + + +upstreams + +For each + +in the +dynamically +configurable +group, +the following data are provided: + + +id + +The ID of the server. + + +server + +An +address +of the server. + + +backup + +A boolean value indicating whether the server is a + +server. + + +weight + +Weight +of the server. + + +state + +Current state, which may be one of +“up”, +“down”, +“unavail”, +or +“unhealthy”. + + +active + +The current number of connections. + + +connections + +The total number of +client connections forwarded to this server. + + +connect_time + +The average time to connect to the upstream server. +The field is available when using the + +load balancing method. + + +first_byte_time + +The average time to receive the first byte of data. +The field is available when using the + +load balancing method. + + +response_time + +The average time to receive the last byte of data. +The field is available when using the + +load balancing method. + + +sent + +The total number of bytes sent to this server. + + +received + +The total number of bytes received from this server. + + +fails + +The total number of +unsuccessful attempts to communicate with the server. + + +unavail + +How many times +the server became unavailable for client connections +(state “unavail”) +due to the number of unsuccessful attempts reaching the + +threshold. + + +health_checks + + + +checks + +The total number of +health check +requests made. + + +fails + +The number of failed health checks. + + +unhealthy + +How many times +the server became unhealthy (state “unhealthy”). + + +last_passed + +Boolean indicating +if the last health check request was successful and passed +tests. + + + + + +downtime + +Total time +the server was in the “unavail” +and “unhealthy” states. + + +downstart + +The time (in milliseconds since Epoch) +when the server became +“unavail” +or “unhealthy”. + + +selected + +The time (in milliseconds since Epoch) +when the server was last selected to process a connection. + + + + + + + + @@ -548,6 +814,36 @@ The total number of bytes written to the +The keepalive field of an upstream server +was removed in 5. + + + +The stream status data +were added in 5. + + + +The + field +was added in 5. + + + +The + field in + +was added in 5. + + + +The + and fields in + +were added in 5. + + + The field in diff --git a/xml/en/docs/http/ngx_http_upstream_module.xml b/xml/en/docs/http/ngx_http_upstream_conf_module.xml copy from xml/en/docs/http/ngx_http_upstream_module.xml copy to xml/en/docs/http/ngx_http_upstream_conf_module.xml --- a/xml/en/docs/http/ngx_http_upstream_module.xml +++ b/xml/en/docs/http/ngx_http_upstream_conf_module.xml @@ -1,27 +1,27 @@ - + rev="1">
-The ngx_http_upstream_module module -is used to define groups of servers that can be referenced -by the , -, -, -, and - directives. +The ngx_http_upstream_conf_module module +allows configuring upstream server groups on-the-fly +via a simple HTTP interface without the need of restarting nginx. +The +http +or +stream +server group must reside in the shared memory.
@@ -31,47 +31,15 @@ by the - -name - -http - - -Defines a group of servers. -Servers can listen on different ports. -In addition, servers listening on TCP and UNIX-domain sockets -can be mixed. - - - -Example: - -upstream backend { - server backend1.example.com weight=5; - server 127.0.0.1:8080 max_fails=3 fail_timeout=30s; - server unix:/tmp/backend3; - - server backup1.example.com backup; -} - - - - -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. - - - - - - -address [parameters] - -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_fails=number - - -sets the number of unsuccessful attempts to communicate with the server -that should happen in the duration set by the fail_timeout -parameter to consider the server unavailable for a duration also set by the -fail_timeout parameter. -By default, the number of unsuccessful attempts is set to 1. -The zero value disables the accounting of attempts. -What is considered an unsuccessful attempt is defined by the -, -, -, -, and - -directives. - - - -fail_timeout=time - - -sets - - - -the time during which the specified number of unsuccessful attempts to -communicate with the server should happen to consider the server unavailable; - - - -and the period of time the server will be considered unavailable. - - - -By default, the parameter is set to 10 seconds. - - - -backup - - -marks the server as a backup server. -It will be passed requests when the primary servers are unavailable. - - - -down - - -marks the server as permanently unavailable. - - - - - - -Additionally, -the following parameters are available as part of our -commercial subscription: - - - -max_conns=number - - -limits the maximum number of simultaneous connections to the -proxied server (1.5.9). -Default value is zero, meaning there is no limit. - - - -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). - -In order for this parameter to work, -the directive -must be specified in the - block. -Example: - -http { - resolver 10.0.0.1; - - upstream u { - zone ...; - ... - server example.com resolve; - } -} - - - - - -route=string - - -sets the server route name. - - - -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. - - - - - - - -If there is only a single server in a group, max_fails, -fail_timeout and slow_start parameters -are ignored, and such a server will never be considered unavailable. - - - - - - - -name size - -upstream - - -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. -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 a special location -handled by . - - - - -This directive is available as part of our -commercial subscription. - - - - - - - -key [consistent] - -upstream -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. - - - - - - - - -upstream - - -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. - - - -Example: - -upstream backend { - ip_hash; - - server backend1.example.com; - server backend2.example.com; - server backend3.example.com down; - server backend4.example.com; -} - - - - - -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. - - - - - - - -connections - -upstream -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. - - - - -Example configuration of memcached upstream with keepalive connections: - -upstream memcached_backend { - server 127.0.0.1:11211; - server 10.0.0.2:11211; - - keepalive 32; -} - -server { - ... - - location /memcached/ { - set $memcached_key $uri; - memcached_pass memcached_backend; - } - -} - - - - -For HTTP, the -directive should be set to “1.1” -and the
Connection
header field should be cleared: - -upstream http_backend { - server 127.0.0.1:8080; - - keepalive 16; -} - -server { - ... - - location /http/ { - proxy_pass http://http_backend; - proxy_http_version 1.1; - proxy_set_header Connection ""; - ... - } -} - -
- - - -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 - -for keepalive connections to work: - -upstream fastcgi_backend { - server 127.0.0.1:9000; - - keepalive 8; -} - -server { - ... - - location /fastcgi/ { - fastcgi_pass fastcgi_backend; - fastcgi_keep_conn on; - ... - } -} - - - - - -When using load balancer methods other than the default -round-robin method, it is necessary to activate them before -the keepalive directive. - - - -SCGI and uwsgi protocols do not have a notion of keepalive connections. - - - -
- - - - - -upstream -1.3.1 -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. - - - - - - -[parameters] - -location - - -Enables periodic health checks of the servers in a -group referenced in the surrounding location. - - - -The following optional parameters are supported: - - - -interval=time - - -sets the interval between two consecutive health checks, -by default, 5 seconds; - - - -fails=number - - -sets the number of consecutive failed health checks of a particular server -after which this server will be considered unhealthy, -by default, 1; - - - -passes=number - - -sets the number of consecutive passed health checks of a particular server -after which the server will be considered healthy, -by default, 1; - - - -uri=uri - - -defines the URI used in health check requests, -by default, “/”; - - - -match=name - - -specifies the match block configuring the tests that a -response should pass in order for a health check to pass; -by default, the response should have status code 2xx or 3xx. - - - - - - -For example, - -location / { - proxy_pass http://backend; - health_check; -} - -will send “/” requests to each -server in the backend group every five seconds. -If any communication error or timeout occurs, or a -proxied server responds with the status code other than -2xx or 3xx, the health check will fail, and the server will -be considered unhealthy. -Client requests are not passed to unhealthy servers. - - - -Health checks can be configured to test the status code of a response, -presence of certain header fields and their values, -and the body contents. -Tests are configured separately using the directive -and referenced in the match parameter. -For example: - -http { - server { - ... - location / { - proxy_pass http://backend; - health_check match=welcome; - } - } - - match welcome { - status 200; - header Content-Type = text/html; - body ~ "Welcome to nginx!"; - } -} - -This configuration tells that for a health check to pass, the response to a -health check request should succeed, -have status 200, content type “text/html”, -and contain “Welcome to nginx!” in the body. - - - -The server group must reside in the shared memory. - - - -If several health checks are defined for the same group of servers, -a single failure of any check will make the corresponding server be -considered unhealthy. - - - - -Please note that most of the variables will have empty values -when used with health checks. - - - - - -This directive is available as part of our -commercial subscription. - - - - - - - -name - -http - - -Defines the named test set used to verify responses to health check requests. - - - -The following items can be tested in a response: - - -status 200; -status is 200 - -status ! 500; -status is not 500 - -status 200 204; -status is 200 or 204 - -status ! 301 302; -status is neither 301 nor 302 - -status 200-399; -status is in the range from 200 to 399 - -status ! 400-599; -status is not in the range from 400 to 599 - -status 301-303 307; -status is either 301, 302, 303, or 307 - - - - - -header Content-Type = text/html; - -header contains
Content-Type
-with value text/html -
- -header Content-Type != text/html; - -header contains
Content-Type
-with value other than text/html -
- -header Connection ~ close; - -header contains
Connection
-with value matching regular expression close -
- -header Connection !~ close; - -header contains
Connection
-with value not matching regular expression close -
- -header Host; -header contains
Host
- -header ! X-Accel-Redirect; -header lacks
X-Accel-Redirect
- -
- - - -body ~ "Welcome to nginx!"; - -body matches regular expression “Welcome to nginx!” - - -body !~ "Welcome to nginx!"; - -body does not match regular expression “Welcome to nginx!” - - - -
- - -If several tests are specified, -the response matches only if it matches all tests. - -Only the first 256k of the response body are examined. - - - - -Examples: - -# status is 200, content type is "text/html", -# and body contains "Welcome to nginx!" -match welcome { - status 200; - header Content-Type = text/html; - body ~ "Welcome to nginx!"; -} - - - -# status is not one of 301, 302, 303, or 307, and header does not have "Refresh:" -match not_redirect { - status ! 301-303 307; - header ! Refresh; -} - - - -# status ok and not in maintenance mode -match server_ok { - status 200-399; - body !~ "maintenance mode"; -} - - - - - - -This directive is available as part of our -commercial subscription. - - - -
- - - - -number -[timeout=time] - -upstream -1.5.12 - - -If an upstream server cannot be selected immediately -while processing a request, -and there are the servers in the group that have reached the - limit, -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 been selected within -the time period specified in the timeout parameter, -an error will be returned to the client. - - - -The default value of the timeout parameter is 60 seconds. - - - - -This directive is available as part of our -commercial subscription. - - - - - - - - - cookie name - [expires=time] - [domain=domain] - [path=path] - - route $variable ... - - learn - create=$variable - lookup=$variable - zone=name:size - [timeout=time] - -upstream -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: - -cookie - - - -When the cookie method is used, information about the -designated server is passed in an HTTP cookie generated by nginx: - -upstream backend { - server backend1.example.com; - server backend2.example.com; - - sticky cookie srv_id expires=1h domain=.example.com path=/; -} - - - - -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. -Additional parameters may be as follows: - - -expires - -Sets the time for which a browser should keep the cookie. -The special value max will cause the cookie to expire on -“31 Dec 2037 23:55:55 GMT”. -If the parameter is not specified, it will cause the cookie to expire at -the end of a browser session. - - -domain - -Defines the domain for which the cookie is set. - - -path - -Defines the path for which the cookie is set. - - - -If any parameters are omitted, the corresponding cookie fields are not set. - - - -route - - - -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 directive to identify the server to which the -request should be proxied. -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. - - - -Example: - -map $cookie_jsessionid $route_cookie { - ~.+\.(?P<route>\w+)$ $route; -} - -map $request_uri $route_uri { - ~jsessionid=.+\.(?P<route>\w+)$ $route; -} - -upstream backend { - server backend1.example.com route=a; - server backend2.example.com route=b; - - sticky route $route_cookie $route_uri; -} - -Here, the route is taken from the “JSESSIONID” cookie -if present in a request. -Otherwise, the route from the URI is used. - - - - -learn - - -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. - -upstream backend { - server backend1.example.com:8080; - server backend2.example.com:8081; - - sticky learn - create=$upstream_cookie_sessionid - lookup=$cookie_sessionid - zone=client_sessions:1m; -} - - -In the example, the upstream server creates a session by setting the -cookie “SESSIONID” 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 8000 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. - - - - - - - - -This directive is available as part of our -commercial subscription. - - - - - - - -name -[expires=time] -[domain=domain] -[path=path] - -upstream - - -This directive is obsolete since version 1.5.7. -An equivalent - directive with a new syntax should be used instead: - -sticky cookie name -[expires=time] -[domain=domain] -[path=path]; - - - - - - @@ -1068,7 +87,7 @@ or viewing the group configuration. A configuration command consists of parameters passed as request arguments, for example: -http://127.0.0.1/upstream_conf?upstream=dynamic +http://127.0.0.1/upstream_conf?upstream=backend @@ -1078,6 +97,17 @@ The following parameters are supported: +stream= + +Selects a +stream +upstream server group. +Without this parameter, selects an +http +upstream server group. + + + upstream=name Selects a group to work with. @@ -1116,17 +146,27 @@ was also required to view, modify, or re server=address Same as the “address” parameter -of the directive. +of the +http +or +stream +upstream server. When adding a server, it is possible to specify it as a domain name. In this case, changes of the IP addresses that correspond to a domain name will be monitored and automatically applied to the upstream configuration without the need of restarting nginx (1.7.2). -This requires the - directive in the - block. -See also -the parameter of the directive. +This requires the “resolver” directive in the +http +or +stream +block. +See also the “resolve” parameter +of the +http +or +stream +upstream server. @@ -1134,48 +174,75 @@ the parameter of th weight=number Same as the “weight” parameter -of the directive. +of the +http +or +stream +upstream server. max_conns=number Same as the “max_conns” parameter -of the directive. +of the +http +or +stream +upstream server. max_fails=number Same as the “max_fails” parameter -of the directive. +of the +http +or +stream +upstream server. fail_timeout=time Same as the “fail_timeout” parameter -of the directive. +of the +http +or +stream +upstream server. slow_start=time Same as the “slow_start” parameter -of the directive. +of the +http +or +stream +upstream server. down= Same as the “down” parameter -of the directive. +of the +http +or +stream +upstream server. drain= -Puts the upstream server in the “draining” mode (1.7.5). -In this mode, only requests bound to the server +Puts the +http +upstream server in the “draining” mode (1.7.5). +In this mode, only requests of the +bound to the server will be proxied to it. @@ -1183,20 +250,26 @@ will be proxied to it. up= The opposite of the “down” parameter -of the directive. +of the +http +or +stream +upstream server. route=string -Same as the “route” parameter -of the directive. +Same as the “route” parameter of the +http +upstream server. -The first two parameters select an object. -This can be either the whole group or a specific server. +The first three parameters select an object. +This can be either the whole http or stream upstream server group, +or a specific server. Without other parameters, the configuration of the selected group or server is shown. @@ -1204,12 +277,12 @@ group or server is shown. For example, to view the configuration of the whole group, send: -http://127.0.0.1/upstream_conf?upstream=dynamic +http://127.0.0.1/upstream_conf?upstream=backend To view the configuration of a specific server, also specify its ID: -http://127.0.0.1/upstream_conf?upstream=dynamic&id=42 +http://127.0.0.1/upstream_conf?upstream=backend&id=42 @@ -1217,158 +290,61 @@ http://127.0.0.1/upstream_conf?upstream= To add a new server, specify its address in the “server=” parameter. Without other parameters specified, a server will be added with other -parameters set to their default values (see the directive). +parameters set to their default values (see the +http +or +stream +“server” directive). For example, to add a new primary server, send: -http://127.0.0.1/upstream_conf?add=&upstream=dynamic&server=127.0.0.1:8080 +http://127.0.0.1/upstream_conf?add=&upstream=backend&server=127.0.0.1:8080 To add a new backup server, send: -http://127.0.0.1/upstream_conf?add=&upstream=dynamic&backup=&server=127.0.0.1:8080 +http://127.0.0.1/upstream_conf?add=&upstream=backend&backup=&server=127.0.0.1:8080 To add a new primary server, set its parameters to non-default values and mark it as “down”, send: -http://127.0.0.1/upstream_conf?add=&upstream=dynamic&server=127.0.0.1:8080&weight=2&down= +http://127.0.0.1/upstream_conf?add=&upstream=backend&server=127.0.0.1:8080&weight=2&down= - - To remove a server, specify its ID: -http://127.0.0.1/upstream_conf?remove=&upstream=dynamic&id=42 +http://127.0.0.1/upstream_conf?remove=&upstream=backend&id=42 - - To mark an existing server as “down”, send: -http://127.0.0.1/upstream_conf?upstream=dynamic&id=42&down= +http://127.0.0.1/upstream_conf?upstream=backend&id=42&down= To modify the address of an existing server, send: -http://127.0.0.1/upstream_conf?upstream=dynamic&id=42&server=192.0.2.3:8123 +http://127.0.0.1/upstream_conf?upstream=backend&id=42&server=192.0.2.3:8123 To modify other parameters of an existing server, send: -http://127.0.0.1/upstream_conf?upstream=dynamic&id=42&max_fails=3&weight=4 +http://127.0.0.1/upstream_conf?upstream=backend&id=42&max_fails=3&weight=4 - - - - -This directive is available as part of our -commercial subscription. - +The above examples are for an +http +upstream server group. +Similar examples for a +stream +upstream server group require the “stream=” parameter.
- -
- - -The ngx_http_upstream_module module -supports the following embedded variables: - - -$upstream_addr - -keeps the IP address and port, -or the path to the UNIX-domain socket of the upstream server. -If several servers were contacted during request processing, -their addresses are separated by commas, e.g. -“192.168.1.1:80, 192.168.1.2:80, unix:/tmp/sock”. -If an internal redirect from one server group to another happens, -initiated by -
X-Accel-Redirect
or -, -then the server addresses from different groups are separated by colons, e.g. -“192.168.1.1:80, 192.168.1.2:80, unix:/tmp/sock : 192.168.10.1:80, 192.168.10.2:80”. -
- -$upstream_cache_status - - -keeps the status of accessing a response cache (0.8.3). -The status can be either “MISS”, -“BYPASS”, “EXPIRED”, -“STALE”, “UPDATING”, -“REVALIDATED”, or “HIT”. - - -$upstream_cookie_name - - -cookie with the specified name sent by the upstream server -in the
Set-Cookie
response header field (1.7.1). -Only the cookies from the response of the last server are saved. -
- -$upstream_header_time - - -keeps time -spent on receiving the response header from the upstream server (1.7.10); -the time is kept in seconds with millisecond resolution. -Times of several responses -are separated by commas and colons like addresses in the -$upstream_addr variable. - - -$upstream_http_name - -keep server response header fields. -For example, the
Server
response header field -is available through the $upstream_http_server variable. -The rules of converting header field names to variable names are the same -as for the variables that start with the -“$http_” prefix. -Only the header fields from the response of the last server are saved. -
- -$upstream_response_length - - -keeps the length of the response obtained from the upstream server (0.7.27); -the length is kept in bytes. -Lengths of several responses -are separated by commas and colons like addresses in the -$upstream_addr variable. - - -$upstream_response_time - - -keeps time spent on receiving the response from the upstream server; -the time is kept in seconds with millisecond resolution. -Times of several responses -are separated by commas and colons like addresses in the -$upstream_addr variable. - - -$upstream_status - -keeps status code of the response obtained from the upstream server. -Status codes of several responses -are separated by commas and colons like addresses in the -$upstream_addr variable. - - -
-
- -
-
diff --git a/xml/en/docs/http/ngx_http_upstream_module.xml b/xml/en/docs/http/ngx_http_upstream_module.xml --- a/xml/en/docs/http/ngx_http_upstream_module.xml +++ b/xml/en/docs/http/ngx_http_upstream_module.xml @@ -10,7 +10,7 @@ + rev="36">
@@ -53,12 +53,15 @@ Dynamically configurable group, available as part of our commercial subscription: +resolver 10.0.0.1; + upstream dynamic { zone upstream_dynamic 64k; server backend1.example.com weight=5; server backend2.example.com:8080 fail_timeout=5s slow_start=30s; server 192.0.2.1 max_fails=3; + server backend3.example.com resolve; server backup1.example.com:8080 backup; server backup2.example.com:8080 backup; @@ -69,12 +72,6 @@ server { proxy_pass http://dynamic; health_check; } - - location /upstream_conf { - upstream_conf; - allow 127.0.0.1; - deny all; - } } @@ -298,7 +295,8 @@ Such groups allow changing the group mem or modifying the settings of a particular server without the need of restarting nginx. The configuration is accessible via a special location -handled by . +handled by +. @@ -528,6 +526,39 @@ weighted round-robin balancing method. + +header | last_byte + +upstream +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. + + + + +This directive is available as part of our +commercial subscription. + + + + + + [parameters] @@ -836,6 +867,8 @@ This directive is available as part of o cookie name [expires=time] [domain=domain] + [httponly] + [secure] [path=path] route $variable ... @@ -883,23 +916,34 @@ The first parameter sets the name of the Additional parameters may be as follows: -expires +expires=time -Sets the time for which a browser should keep the cookie. +Sets the time for which a browser should keep the cookie. The special value max will cause the cookie to expire on “31 Dec 2037 23:55:55 GMT”. If the parameter is not specified, it will cause the cookie to expire at the end of a browser session. -domain +domain=domain -Defines the domain for which the cookie is set. +Defines the domain for which the cookie is set. + + +httponly + +Adds the HttpOnly attribute to the cookie (1.7.11). -path +secure -Defines the path for which the cookie is set. +Adds the Secure attribute to the cookie (1.7.11). + + + +path=path + +Defines the path for which the cookie is set. @@ -1032,247 +1076,6 @@ An equivalent - - - - -location - - -Turns on the HTTP interface of upstream configuration in the surrounding -location. -Access to this location should be -limited. - - - -Configuration commands can be used to: - - -view the group configuration; - -view, modify, or remove a server; - -add a new server. - - - -Since addresses in a group are not required to be unique, specific -servers in a group are referenced by their IDs. -IDs are assigned automatically and shown when adding a new server -or viewing the group configuration. - - - - -A configuration command consists of parameters passed as request arguments, -for example: - -http://127.0.0.1/upstream_conf?upstream=dynamic - - - - -The following parameters are supported: - - - - -upstream=name - -Selects a group to work with. -This parameter is mandatory. - - - -id=number - -Selects a server for viewing, modifying, or removing. - - - -remove= - -Removes a server from the group. - - - -add= - -Adds a new server to the group. - - - -backup= - -Required to add a backup server. - -Before version 1.7.2, backup= -was also required to view, modify, or remove existing backup servers. - - - - -server=address - -Same as the “address” parameter -of the directive. - -When adding a server, it is possible to specify it as a domain name. -In this case, changes of the IP addresses that correspond to a domain name -will be monitored and automatically applied to the upstream -configuration without the need of restarting nginx (1.7.2). -This requires the - directive in the - block. -See also -the parameter of the directive. - - - - -weight=number - -Same as the “weight” parameter -of the directive. - - - -max_conns=number - -Same as the “max_conns” parameter -of the directive. - - - -max_fails=number - -Same as the “max_fails” parameter -of the directive. - - - -fail_timeout=time - -Same as the “fail_timeout” parameter -of the directive. - - - -slow_start=time - -Same as the “slow_start” parameter -of the directive. - - - -down= - -Same as the “down” parameter -of the directive. - - -drain= - -Puts the upstream server in the “draining” mode (1.7.5). -In this mode, only requests bound to the server -will be proxied to it. - - - -up= - -The opposite of the “down” parameter -of the directive. - - - -route=string - -Same as the “route” parameter -of the directive. - - - - -The first two parameters select an object. -This can be either the whole group or a specific server. -Without other parameters, the configuration of the selected -group or server is shown. - - - -For example, to view the configuration of the whole group, send: - -http://127.0.0.1/upstream_conf?upstream=dynamic - - -To view the configuration of a specific server, also specify its ID: - -http://127.0.0.1/upstream_conf?upstream=dynamic&id=42 - - - - -To add a new server, -specify its address in the “server=” parameter. -Without other parameters specified, a server will be added with other -parameters set to their default values (see the directive). - - - -For example, to add a new primary server, send: - -http://127.0.0.1/upstream_conf?add=&upstream=dynamic&server=127.0.0.1:8080 - - -To add a new backup server, send: - -http://127.0.0.1/upstream_conf?add=&upstream=dynamic&backup=&server=127.0.0.1:8080 - - -To add a new primary server, -set its parameters to non-default values -and mark it as “down”, send: - -http://127.0.0.1/upstream_conf?add=&upstream=dynamic&server=127.0.0.1:8080&weight=2&down= - - - - -To remove a server, specify its ID: - -http://127.0.0.1/upstream_conf?remove=&upstream=dynamic&id=42 - - - - -To mark an existing server as “down”, send: - -http://127.0.0.1/upstream_conf?upstream=dynamic&id=42&down= - - -To modify the address of an existing server, send: - -http://127.0.0.1/upstream_conf?upstream=dynamic&id=42&server=192.0.2.3:8123 - - -To modify other parameters of an existing server, send: - -http://127.0.0.1/upstream_conf?upstream=dynamic&id=42&max_fails=3&weight=4 - - - - - - -This directive is available as part of our -commercial subscription. - - - - -
diff --git a/xml/en/docs/index.xml b/xml/en/docs/index.xml --- a/xml/en/docs/index.xml +++ b/xml/en/docs/index.xml @@ -8,7 +8,7 @@
@@ -405,6 +405,11 @@ ngx_http_upstream_module + +ngx_http_upstream_conf_module + + + ngx_http_userid_module @@ -477,6 +482,11 @@ ngx_stream_proxy_module + +ngx_stream_ssl_module + + + ngx_stream_upstream_module diff --git a/xml/en/docs/ngx_core_module.xml b/xml/en/docs/ngx_core_module.xml --- a/xml/en/docs/ngx_core_module.xml +++ b/xml/en/docs/ngx_core_module.xml @@ -10,7 +10,7 @@ + rev="13">
@@ -158,6 +158,7 @@ analysis using a system debugger. logs/error.log error main http +stream server location @@ -195,6 +196,12 @@ For debug logging to be built with --with-debug, see “”. + + +The directive can be specified on the +stream level +starting from version 1.7.11. + diff --git a/xml/en/docs/stream/ngx_stream_core_module.xml b/xml/en/docs/stream/ngx_stream_core_module.xml --- a/xml/en/docs/stream/ngx_stream_core_module.xml +++ b/xml/en/docs/stream/ngx_stream_core_module.xml @@ -9,7 +9,7 @@ + rev="2">
@@ -63,6 +63,7 @@ stream { address:port + [ssl] [bind] [ipv6only=on|off] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]] @@ -94,11 +95,16 @@ listen unix:/var/run/nginx.sock; -The directive supports the following parameters: +The ssl parameter (1.7.10) allows specifying that all +connections accepted on this port should work in SSL mode. + + +The listen directive +can have several additional parameters specific to socket-related system calls. - + bind @@ -118,7 +124,7 @@ are used then for a given a separate bind call will always be made. - + ipv6only=on|off @@ -130,7 +136,7 @@ This parameter is turned on by default. It can only be set once on start. - + so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt] @@ -157,6 +163,7 @@ will set the idle timeout (TCP_KE leave the probe interval (TCP_KEEPINTVL) at its system default, and set the probes count (TCP_KEEPCNT) to 10 probes. + @@ -168,6 +175,62 @@ Different servers must listen on differe + + + address ... + [valid=time] + [ipv6=on|off] + +stream +server +1.7.10 + + +Configures name servers used to resolve names of upstream servers +into addresses, for example: + +resolver 127.0.0.1 [::1]:5353; + +An address can be specified as a domain name or IP address, +and 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. +The optional valid parameter allows overriding it: + +resolver 127.0.0.1 [::1]:5353 valid=30s; + + + + + + + +time +30s +stream +server +1.7.10 + + +Sets a timeout for name resolution, for example: + +resolver_timeout 5s; + + + + + + diff --git a/xml/en/docs/stream/ngx_stream_proxy_module.xml b/xml/en/docs/stream/ngx_stream_proxy_module.xml --- a/xml/en/docs/stream/ngx_stream_proxy_module.xml +++ b/xml/en/docs/stream/ngx_stream_proxy_module.xml @@ -9,7 +9,7 @@ + rev="3">
@@ -83,6 +83,59 @@ buffer used for reading data from the cl + +on | off +on +stream +server +1.7.10 + + +When a connection to the proxied server cannot be established, determines +whether a client connection will be passed to the next server. + + + +Passing a connection to the next server can be limited by +the number of tries +and by time. + + + + + + +time +0 +stream +server +1.7.10 + + +Limits the time allowed to pass a connection to the +next server. +The 0 value turns off this limitation. + + + + + + +number +0 +stream +server +1.7.10 + + +Limits the number of possible tries for passing a connection to the +next server. +The 0 value turns off this limitation. + + + + + address @@ -111,6 +164,223 @@ In addition, an address can be specified + +on | off +off +stream +server +1.7.10 + + +Enables the SSL/TLS protocol for connections to a proxied server. + + + + + + +file + +stream +server +1.7.10 + + +Specifies a file with the certificate in the PEM format +used for authentication to a proxied server. + + + + + + +file + +stream +server +1.7.10 + + +Specifies a file with the secret key in the PEM format +used for authentication to a proxied server. + + + + + + +ciphers +DEFAULT +stream +server +1.7.10 + + +Specifies the enabled ciphers for connections to a proxied server. +The ciphers are specified in the format understood by the OpenSSL library. + + + +The full list can be viewed using the +“openssl ciphers” command. + + + + + + +file + +stream +server +1.7.10 + + +Specifies a file with revoked certificates (CRL) +in the PEM format used to verify +the certificate of the proxied server. + + + + + + +name +host from proxy_pass +stream +server +1.7.10 + + +Allows to override the server name used to +verify +the certificate of the proxied server and to be +passed through SNI +when establishing a connection with the proxied server. + + + +By default, the host part of the address is used. + + + + + + +file + +stream +server +1.7.10 + + +Specifies a file with passphrases for +secret keys +where each passphrase is specified on a separate line. +Passphrases are tried in turn when loading the key. + + + + + + +on | off +off +stream +server +1.7.10 + + +Enables or disables passing of the server name through +TLS +Server Name Indication extension (SNI, RFC 6066) +when establishing a connection with the proxied server. + + + + + + +on | off +on +stream +server +1.7.10 + + +Determines whether SSL sessions can be reused when working with +the proxied server. +If the errors +“SSL3_GET_FINISHED:digest check failed” +appear in the logs, try disabling session reuse. + + + + + + + + [SSLv2] + [SSLv3] + [TLSv1] + [TLSv1.1] + [TLSv1.2] +SSLv3 TLSv1 TLSv1.1 TLSv1.2 +stream +server +1.7.10 + + +Enables the specified protocols for connections to a proxied server. + + + + + + +file + +stream +server +1.7.10 + + +Specifies a file with trusted CA certificates in the PEM format +used to verify +the certificate of the proxied server. + + + + + + +on | off +off +stream +server +1.7.10 + + +Enables or disables verification of the proxied server certificate. + + + + + + +number +1 +stream +server +1.7.10 + + +Sets the verification depth in the proxied server certificates chain. + + + + + timeout 10m diff --git a/xml/en/docs/stream/ngx_stream_ssl_module.xml b/xml/en/docs/stream/ngx_stream_ssl_module.xml new file mode 100644 --- /dev/null +++ b/xml/en/docs/stream/ngx_stream_ssl_module.xml @@ -0,0 +1,326 @@ + + + + + + + + +
+ + +The ngx_stream_ssl_module module (1.7.10) +provides the necessary support for a stream proxy server to work with +the SSL/TLS protocol. + + + + +This module is available as part of our +commercial subscription. + + + +
+ + +
+ + +file + +stream +server + + +Specifies a file with the certificate in the PEM format for the given +server. +If intermediate certificates should be specified in addition to a primary +certificate, they should be specified in the same file in the following +order: the primary certificate comes first, then the intermediate certificates. +A secret key in the PEM format may be placed in the same file. + + + + + + +file + +stream +server + + +Specifies a file with the secret key in the PEM format for the given +server. + + + + + + +ciphers +HIGH:!aNULL:!MD5 +stream +server + + +Specifies the enabled ciphers. +The ciphers are specified in the format understood by the +OpenSSL library, for example: + +ssl_ciphers ALL:!aNULL:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP; + + + + +The full list can be viewed using the +“openssl ciphers” command. + + + + + + +file + +stream +server + + +Specifies a file with DH parameters for EDH ciphers. + + + + + + +curve +prime256v1 +stream +server + + +Specifies a curve for ECDHE ciphers. + + + + + + +time +60s +stream +server + + +Specifies a timeout for the SSL handshake to complete. + + + + + + +file + +stream +server + + +Specifies a file with passphrases for +secret keys +where each passphrase is specified on a separate line. +Passphrases are tried in turn when loading the key. + + + +Example: + +stream { + ssl_password_file /etc/keys/global.pass; + ... + + server { + listen 127.0.0.1:12345; + ssl_certificate_key /etc/keys/first.key; + } + + server { + listen 127.0.0.1:12346; + + # named pipe can also be used instead of a file + ssl_password_file /etc/keys/fifo; + ssl_certificate_key /etc/keys/second.key; + } +} + + + + + + + +on | off +off +stream +server + + +Specifies that server ciphers should be preferred over client ciphers +when the SSLv3 and TLS protocols are used. + + + + + + + + [SSLv2] + [SSLv3] + [TLSv1] + [TLSv1.1] + [TLSv1.2] +SSLv3 TLSv1 TLSv1.1 TLSv1.2 +stream +server + + +Enables the specified protocols. +The TLSv1.1 and TLSv1.2 parameters work +only when the OpenSSL library of version 1.0.1 or higher is used. + + + + + + + + off | + none | + [builtin[:size]] + [shared:name:size] +none +stream +server + + +Sets the types and sizes of caches that store session parameters. +A cache can be of any of the following types: + + +off + +the use of a session cache is strictly prohibited: +nginx explicitly tells a client that sessions may not be reused. + + +none + +the use of a session cache is gently disallowed: +nginx tells a client that sessions may be reused, but does not +actually store session parameters in the cache. + + +builtin + +a cache built in OpenSSL; used by one worker process only. +The cache size is specified in sessions. +If size is not given, it is equal to 20480 sessions. +Use of the built-in cache can cause memory fragmentation. + + +shared + +a cache shared between all worker processes. +The cache size is specified in bytes; one megabyte can store +about 4000 sessions. +Each shared cache should have an arbitrary name. +A cache with the same name can be used in several +servers. + + + + + + +Both cache types can be used simultaneously, for example: + +ssl_session_cache builtin:1000 shared:SSL:10m; + +but using only shared cache without the built-in cache should +be more efficient. + + + + + + +file + +stream +server + + +Sets a file with the secret key used to encrypt +and decrypt TLS session tickets. +The directive is necessary if the same key has to be shared between +multiple servers. +By default, a randomly generated key is used. + + + +If several keys are specified, only the first key is +used to encrypt TLS session tickets. +This allows configuring key rotation, for example: + +ssl_session_ticket_key current.key; +ssl_session_ticket_key previous.key; + + + + +The file must contain 48 bytes of random data and can +be created using the following command: + +openssl rand 48 > ticket.key + + + + + + + +on | off +on +stream +server + + +Enables or disables session resumption through +TLS session tickets. + + + + + + +time +5m +stream +server + + +Specifies a time during which a client may reuse the +session parameters stored in a cache. + + + + +
+ +
diff --git a/xml/en/docs/stream/ngx_stream_upstream_module.xml b/xml/en/docs/stream/ngx_stream_upstream_module.xml --- a/xml/en/docs/stream/ngx_stream_upstream_module.xml +++ b/xml/en/docs/stream/ngx_stream_upstream_module.xml @@ -9,7 +9,7 @@ + rev="5">
@@ -34,17 +34,23 @@ This module is available as part of our +resolver 10.0.0.1; + upstream backend { + zone upstream_backend 64k; + hash $remote_addr consistent; server backend1.example.com:12345 weight=5; server 127.0.0.1:12345 max_fails=3 fail_timeout=30s; - server unix:/tmp/backend3; + server unix:/tmp/backend2; + server backend3.example.com:12345 resolve; } server { listen 12346; proxy_pass backend; + health_check; } @@ -72,7 +78,8 @@ Example: upstream backend { server backend1.example.com:12345 weight=5; server 127.0.0.1:12345 max_fails=3 fail_timeout=30s; - server unix:/tmp/backend3; + server unix:/tmp/backend2; + server backend3.example.com:12345 resolve; server backup1.example.com:12345 backup; } @@ -179,6 +186,34 @@ proxied server. Default value is zero, meaning there is no limit. + +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.7.10). + +In order for this parameter to work, +the directive +must be specified in the + block. +Example: + +stream { + resolver 10.0.0.1; + + upstream u { + zone ...; + ... + server example.com:12345 resolve; + } +} + + + + slow_start=time @@ -204,6 +239,27 @@ are ignored, and such a server will neve + +name size + +upstream +1.7.10 + + +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. +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 a special location +handled by +. + + + + + key [consistent] @@ -253,6 +309,229 @@ weighted round-robin balancing method. + + +connect | + first_byte | + last_byte + +upstream +1.7.11 + + +Specifies that a group should use a load balancing method where a connection +is passed to the server with the least average 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 connect parameter is specified, +time to connect to the upstream server is used. +If the first_byte parameter is specified, +time to receive the first byte of data is used. +If the last_byte is specified, +time to receive the last byte of data is used. + + + + + + +[parameters] + +server +1.7.10 + + +Enables periodic health checks of the servers in a +group. + + + +The following optional parameters are supported: + + + +interval=time + + +sets the interval between two consecutive health checks, +by default, 5 seconds; + + + +fails=number + + +sets the number of consecutive failed health checks of a particular server +after which this server will be considered unhealthy, +by default, 1; + + + +passes=number + + +sets the number of consecutive passed health checks of a particular server +after which the server will be considered healthy, +by default, 1; + + + +match=name + + +specifies the match block configuring the tests that a +successful connection should pass in order for a health check to pass; +by default, only the ability to connect to the server is checked. + + + + + + +For example, + +server { + proxy_pass backend; + health_check; +} + +will check the ability to connect to each +server in the backend group every five seconds. +When a connection to the server cannot be established, +the health check will fail, and the server will +be considered unhealthy. +Client connections are not passed to unhealthy servers. + + + +Health checks can also be configured to test data obtained from the server. +Tests are configured separately using the directive +and referenced in the match parameter. + + + +The server group must reside in the shared memory. + + + +If several health checks are defined for the same group of servers, +a single failure of any check will make the corresponding server be +considered unhealthy. + + + + + + +timeout +5s +stream +server +1.7.10 + + +Overrides the + +value for health checks. + + + + + + +name + +stream +1.7.10 + + +Defines the named test set used to verify server responses to health checks. + + + +The following parameters can be configured: + + + +send string; + + +sends a string to the server; + + + +expect ~ regexp; + + +a regular expression that the data obtained from the server should match. +The regular expression is specified with the preceding +“~*” modifier (for case-insensitive matching), or the +“~” modifier (for case-sensitive matching). + + + + + + +Health check is passed if: + + +the connection was successfully established; + + + +the string from the send parameter, +if specified, was sent; + + + +the data obtained from the server matched the regular expression +from the expect parameter, if specified; + + + +the time elapsed does not exceed the value specified +in the directive. + + + + + + +Example: + +upstream backend { + zone upstream_backend 10m; + server 127.0.0.1:12345; +} + +match http { + send "GET / HTTP/1.0\r\nHost: localhost\r\n\r\n"; + expect ~ "200 OK"; +} + +server { + listen 12346; + proxy_pass backend; + health_check match=http; +} + + + + + +Only the first + +bytes of data obtained from the server are examined. + + + + +
diff --git a/xml/ru/GNUmakefile b/xml/ru/GNUmakefile --- a/xml/ru/GNUmakefile +++ b/xml/ru/GNUmakefile @@ -70,6 +70,7 @@ REFS = \ http/ngx_http_stub_status_module \ http/ngx_http_sub_module \ http/ngx_http_upstream_module \ + http/ngx_http_upstream_conf_module \ http/ngx_http_userid_module \ http/ngx_http_uwsgi_module \ http/ngx_http_xslt_module \ diff --git a/xml/ru/docs/http/ngx_http_status_module.xml b/xml/ru/docs/http/ngx_http_status_module.xml --- a/xml/ru/docs/http/ngx_http_status_module.xml +++ b/xml/ru/docs/http/ngx_http_status_module.xml @@ -9,7 +9,7 @@ + rev="5">
@@ -160,7 +160,7 @@ http://127.0.0.1/status/upstreams/backen version Версия предоставляемого набора данных. -Текущей является версия 4. +Текущей является версия 5. nginx_version @@ -173,6 +173,13 @@ http://127.0.0.1/status/upstreams/backen Адрес сервера, принявшего запрос получения информации о состоянии. +generation + +Суммарное число +перезагрузок +конфигурации. + + load_timestamp Время последней перезагрузки конфигурации, в миллисекундах с начала эпохи. @@ -183,6 +190,19 @@ http://127.0.0.1/status/upstreams/backen Текущее время в миллисекундах с начала эпохи. +processes + + + +respawned + +Суммарное число перезапусков аварийно завершённых +дочерних процессов. + + + + + connections @@ -331,11 +351,13 @@ http://127.0.0.1/status/upstreams/backen Текущее число активных соединений. + max_conns @@ -451,6 +473,24 @@ http://127.0.0.1/status/upstreams/backen когда сервер в последний раз был выбран для обработки запроса (1.7.5). +header_time + +Среднее время получения +заголовка +ответа от сервера (1.7.10). +Поле доступно при использовании метода балансировки +. + + +response_time + +Среднее время получения +всего +ответа от сервера (1.7.10). +Поле доступно при использовании метода балансировки +. + + @@ -551,6 +591,28 @@ http://127.0.0.1/status/upstreams/backen +Поле keepalive сервера группы +было удалено в версии 5. + + + +Поле +было добавлено в версии 5. + + + +Поле в + +было добавлено в версии 5. + + + +Поля и в + +были добавлены в версии 5. + + + Поле в было добавлено в версии 4. diff --git a/xml/ru/docs/http/ngx_http_upstream_module.xml b/xml/ru/docs/http/ngx_http_upstream_conf_module.xml copy from xml/ru/docs/http/ngx_http_upstream_module.xml copy to xml/ru/docs/http/ngx_http_upstream_conf_module.xml --- a/xml/ru/docs/http/ngx_http_upstream_module.xml +++ b/xml/ru/docs/http/ngx_http_upstream_conf_module.xml @@ -1,28 +1,27 @@ - + rev="1">
-Модуль ngx_http_upstream_module -позволяет описывать группы серверов, -которые могут использоваться в директивах -, -, -, - и -. +Модуль ngx_http_upstream_conf_module +позволяет оперативно настраивать группы серверов +при помощи простого HTTP-интерфейса без необходимости перезапуска nginx. +Группа серверов +http +или +stream +должна находиться в разделяемой памяти.
@@ -32,47 +31,15 @@ -upstream backend { - server backend1.example.com weight=5; - server backend2.example.com:8080; - server unix:/tmp/backend3; +upstream backend { + zone upstream_backend 64k; - server backup1.example.com:8080 backup; - server backup2.example.com:8080 backup; + ... } server { - location / { - proxy_pass http://backend; - } -} - - - - -Динамически настраиваемая группа, -доступна как часть -коммерческой подписки: - -upstream dynamic { - zone upstream_dynamic 64k; - - server backend1.example.com weight=5; - server backend2.example.com:8080 fail_timeout=5s slow_start=30s; - server 192.0.2.1 max_fails=3; - - server backup1.example.com:8080 backup; - server backup2.example.com:8080 backup; -} - -server { - location / { - proxy_pass http://dynamic; - health_check; - } - location /upstream_conf { - upstream_conf; + upstream_conf; allow 127.0.0.1; deny all; } @@ -85,960 +52,6 @@ server {
- -название - -http - - -Описывает группу серверов. -Серверы могут слушать на разных портах. -Кроме того, можно одновременно использовать серверы, -слушающие на TCP- и UNIX-сокетах. - - - -Пример: - -upstream backend { - server backend1.example.com weight=5; - server 127.0.0.1:8080 max_fails=3 fail_timeout=30s; - server unix:/tmp/backend3; - - server backup1.example.com backup; -} - - - - -По умолчанию запросы распределяются по серверам циклически -(в режиме round-robin) с учётом весов серверов. -В вышеприведённом примере каждые 7 запросов будут распределены так: -5 запросов на backend1.example.com -и по одному запросу на второй и третий серверы. -Если при попытке работы с сервером происходит ошибка, то запрос -передаётся следующему серверу, и так далее до тех пор, пока не будут опробованы -все работающие серверы. -Если не удастся получить успешный ответ -ни от одного из серверов, то клиенту будет возвращён результат работы -с последним сервером. - - - - - - -адрес [параметры] - -upstream - - -Задаёт адрес и другие параметры -сервера. -Адрес может быть указан в виде доменного имени или IP-адреса, -и необязательного порта, или в виде пути UNIX-сокета, который -указывается после префикса “unix:”. -Если порт не указан, используется порт 80. -Доменное имя, которому соответствует несколько IP-адресов, -задаёт сразу несколько серверов. - - - -Могут быть заданы следующие параметры: - - - -weight=число - - -задаёт вес сервера, по умолчанию 1. - - - -max_fails=число - - -задаёт число неудачных попыток работы с сервером, которые должны произойти -в течение времени, заданного параметром fail_timeout, -чтобы сервер считался недоступным на период времени, также заданный -параметром fail_timeout. -По умолчанию число попыток устанавливается равным 1. -Нулевое значение отключает учёт попыток. -Что считается неудачной попыткой, определяется директивами -, -, -, - и -. - - - -fail_timeout=время - - -задаёт - - - -время, в течение которого должно произойти заданное число неудачных -попыток работы с сервером для того, чтобы сервер считался недоступным; - - - -и время, в течение которого сервер будет считаться недоступным. - - - -По умолчанию параметр равен 10 секундам. - - - -backup - - -помечает сервер как запасной сервер. -На него будут передаваться запросы в случае, если не работают основные серверы. - - - -down - - -помечает сервер как постоянно недоступный. - - - - - - -Кроме того, -следующие параметры доступны как часть -коммерческой подписки: - - - -max_conns=число - - -ограничивает максимальное число одновременных соединений -к проксируемому серверу (1.5.9). -Значение по умолчанию равно 0 и означает, что ограничения нет. - - - -resolve - - -отслеживает изменения IP-адресов, соответствующих доменному имени сервера, -и автоматически изменяет конфигурацию группы -без необходимости перезапуска nginx (1.5.12). - -Для работы этого параметра -директива -должна быть задана в блоке -. -Пример: - -http { - resolver 10.0.0.1; - - upstream u { - zone ...; - ... - server example.com resolve; - } -} - - - - - -route=строка - - -задаёт имя маршрута к серверу. - - - -slow_start=время - - -задаёт время, в течение которого вес сервера -восстановится от нуля до своего номинального значения в ситуации, когда -неработоспособный (unhealthy) сервер вновь становится работоспособным -(healthy) -или когда сервер становится доступным по прошествии времени, -в течение которого он считался недоступным. -Значение по умолчанию равно нулю и означает, что медленный старт выключен. - - - - - - - -Если в группе только один сервер, параметры max_fails, -fail_timeout и slow_start -игнорируются и такой сервер никогда не будет считаться недоступным. - - - - - - - -имя размер - -upstream - - -Задаёт имя и размер зоны разделяемой памяти, -в которой хранятся конфигурация группы и её рабочее состояние, -разделяемые между рабочими процессами. -В таких группах для изменения состава группы -или настроек отдельных серверов -нет необходимости перезапускать nginx. -Конфигурация доступна через специальный location, -в котором указана директива . - - - - -Эта директива доступна как часть -коммерческой подписки. - - - - - - - -ключ [consistent] - -upstream -1.7.2 - - -Задаёт метод балансировки нагрузки для группы, при котором -соответствие клиента серверу определяется при помощи -хэшированного значения ключа. -В качестве ключа может использоваться -текст, переменные и их комбинации. -Следует отметить, что любое добавление или удаление серверов в группе -может привести к перераспределению большинства ключей на другие серверы. -Метод совместим с библиотекой Perl -Cache::Memcached. - - - -Если задан параметр consistent, то вместо -вышеописанного метода будет использоваться метод консистентного хэширования -ketama. -Метод гарантирует, что при добавлении сервера в группу или его удалении -на другие серверы будет перераспределено минимальное число ключей. -Применение метода для кэширующих серверов обеспечивает -больший процент попаданий в кэш. -Метод совместим с библиотекой Perl -Cache::Memcached::Fast -при значении параметра ketama_points равным 160. - - - - - - - - -upstream - - -Задаёт для группы метод балансировки нагрузки, при котором запросы -распределяются по серверам на основе IP-адресов клиентов. -В качестве ключа для хэширования используются первые три -октета IPv4-адреса клиента или IPv6-адрес клиента целиком. -Метод гарантирует, что запросы одного и того же клиента -будут всегда передаваться на один и тот же сервер. -Если же этот сервер будет считаться недоступным, -то запросы этого клиента будут передаваться на другой сервер. -С большой долей вероятности это также будет один и тот же сервер. - -IPv6-адреса поддерживаются начиная с версий 1.3.2 и 1.2.2. - - - - -Если один из серверов нужно убрать на некоторое время, то для сохранения -текущего хэширования IP-адресов клиентов этот сервер нужно пометить -параметром down. - - - -Пример: - -upstream backend { - ip_hash; - - server backend1.example.com; - server backend2.example.com; - server backend3.example.com down; - server backend4.example.com; -} - - - - - -До версий 1.3.1 и 1.2.2 для серверов, использующих метод балансировки нагрузки -ip_hash, нельзя было задать вес. - - - - - - - -соединения - -upstream -1.1.4 - - -Задействует кэш соединений для группы серверов. - - - -Параметр соединения устанавливает максимальное число -неактивных постоянных соединений с серверами группы, которые будут -сохраняться в кэше каждого рабочего процесса. -При превышении этого числа наиболее давно не используемые соединения -закрываются. - -Следует особо отметить, что директива keepalive -не ограничивает общее число соединений с серверами группы, которые -рабочие процессы nginx могут открыть. -Параметр соединения следует устанавливать достаточно -консервативно, чтобы серверы группы по-прежнему могли обрабатывать -новые входящие соединения. - - - - -Пример конфигурации группы серверов memcached с постоянными соединениями: - -upstream memcached_backend { - server 127.0.0.1:11211; - server 10.0.0.2:11211; - - keepalive 32; -} - -server { - ... - - location /memcached/ { - set $memcached_key $uri; - memcached_pass memcached_backend; - } - -} - - - - -Для HTTP директиву - -следует установить в “1.1”, -а поле заголовка
Connection
 — очистить: - -upstream http_backend { - server 127.0.0.1:8080; - - keepalive 16; -} - -server { - ... - - location /http/ { - proxy_pass http://http_backend; - proxy_http_version 1.1; - proxy_set_header Connection ""; - ... - } -} - -
- - - -Хоть это и не рекомендуется, но также возможно использование постоянных -соединений с HTTP/1.0, путём передачи поля заголовка -
Connection: Keep-Alive
серверу группы. -
-
- - -Для работы постоянных соединений с FastCGI-серверами потребуется -включить директиву -: - -upstream fastcgi_backend { - server 127.0.0.1:9000; - - keepalive 8; -} - -server { - ... - - location /fastcgi/ { - fastcgi_pass fastcgi_backend; - fastcgi_keep_conn on; - ... - } -} - - - - - -При использовании методов балансировки нагрузки, отличных -от стандартного round-robin, следует активировать их до -директивы keepalive. - - - -Протоколы SCGI и uwsgi не определяют семантику постоянных соединений. - - - -
- - - - - -upstream -1.3.1 -1.2.2 - - -Задаёт для группы метод балансировки нагрузки, при котором запрос -передаётся серверу с наименьшим числом активных соединений, -с учётом весов серверов. -Если подходит сразу несколько серверов, они выбираются циклически -(в режиме round-robin) с учётом их весов. - - - - - - -[параметры] - -location - - -Активирует периодические проверки работоспособности серверов в -группе, указанной в содержащем location. - - - -Могут быть заданы следующие необязательные параметры: - - - -interval=время - - -задаёт интервал между двумя последовательными проверками, -по умолчанию 5 секунд; - - - -fails=число - - -задаёт число последовательных неуспешных проверок для определённого сервера, -после которых сервер будет считаться неработоспособным, -по умолчанию 1; - - - -passes=число - - -задаёт число последовательных успешных проверок для определённого сервера, -после которых сервер будет считаться работоспособным, -по умолчанию 1; - - - -uri=uri - - -задаёт URI, используемый в запросах, проверяющих работоспособность, -по умолчанию “/”; - - - -match=имя - - -указывает на блок match с условиями, которым должен -удовлетворять ответ, чтобы результат проверки считался успешным; -по умолчанию код ответа должен быть 2xx или 3xx. - - - - - - -В примере - -location / { - proxy_pass http://backend; - health_check; -} - -каждому серверу группы backend -с интервалом в 5 секунд посылаются запросы “/”. -Если происходит ошибка или таймаут при работе с сервером, или -код ответа проксируемого сервера не равен -2xx или 3xx, проверка считается неуспешной и сервер -признаётся неработоспособным. -На неработоспособные серверы клиентские запросы передаваться не будут. - - - -Проверки работоспособности могут тестировать код ответа, -наличие или отсутствие определённых полей заголовка и их значений, -а также содержимое тела ответа. -Тесты настраиваются отдельно при помощи директивы -и указываются в параметре match. -Например: - -http { - server { - ... - location / { - proxy_pass http://backend; - health_check match=welcome; - } - } - - match welcome { - status 200; - header Content-Type = text/html; - body ~ "Welcome to nginx!"; - } -} - -В такой конфигурации успешный ответ на проверочный запрос -должен иметь код 200, тип содержимого “text/html” -и “Welcome to nginx!” в теле ответа. - - - -Группа должна находиться в зоне разделяемой памяти. - - - -Если для группы задано несколько проверок, -то при любой неуспешной проверке соответствующий сервер будет -считаться неработоспособным. - - - - -Обратите внимание, что при использовании проверок -большинство переменных имеют пустые значения. - - - - - -Эта директива доступна как часть -коммерческой подписки. - - - - - - - -имя - -http - - -Задаёт именованный набор тестов для анализа ответов -на запросы проверки работоспособности. - - - -В ответе могут быть протестированы следующие объекты: - - -status 200; -код ответа равен 200 - -status ! 500; -код ответа не равен 500 - -status 200 204; -код ответа равен 200 или 204 - -status ! 301 302; -код ответа не равен ни 301, ни 302 - -status 200-399; -код ответа находится в диапазоне от 200 до 399 - -status ! 400-599; -код ответа находится вне диапазона от 400 до 599 - -status 301-303 307; -код ответа равен 301, 302, 303 или 307 - - - - - -header Content-Type = text/html; - -заголовок содержит
Content-Type
-со значением text/html -
- -header Content-Type != text/html; - -заголовок содержит
Content-Type
-со значением, отличным от text/html -
- -header Connection ~ close; - -заголовок содержит
Connection
-со значением, совпадающим с регулярным выражением close -
- -header Connection !~ close; - -заголовок содержит
Connection
-со значением, не совпадающим с регулярным выражением close -
- -header Host; -заголовок содержит
Host
- -header ! X-Accel-Redirect; -заголовок не содержит
X-Accel-Redirect
- -
- - - -body ~ "Welcome to nginx!"; - -тело ответа совпадает с регулярным выражением -“Welcome to nginx!” - - -body !~ "Welcome to nginx!"; - -тело ответа не совпадает с регулярным выражением -“Welcome to nginx!” - - - -
- - -Если задано несколько тестов, -то ответ должен удовлетворять всем тестам. - -Проверяются только первые 256 Кбайт тела ответа. - - - - -Примеры: - -# код ответа 200, тип содержимого "text/html" -# и тело ответа содержит "Welcome to nginx!" -match welcome { - status 200; - header Content-Type = text/html; - body ~ "Welcome to nginx!"; -} - - - -# код ответа не равен 301, 302, 303 и 307 и заголовок не содержит "Refresh:" -match not_redirect { - status ! 301-303 307; - header ! Refresh; -} - - - -# код ответа успешный и сервер не в сервисном режиме -match server_ok { - status 200-399; - body !~ "maintenance mode"; -} - - - - - - -Эта директива доступна как часть -коммерческой подписки. - - - -
- - - - -число -[timeout=время] - -upstream -1.5.12 - - -Если при обработке запроса невозможно сразу выбрать сервер группы -и в группе есть серверы, у которых число соединений достигло -ограничения , -запрос будет помещён в очередь. -Директива задаёт максимальное число запросов, которые могут одновременно -находиться в очереди. -Если очередь переполнена -или за время, задаваемое параметром timeout, -так и не удастся выбрать сервер для передачи ему запроса, -клиенту будет возвращена ошибка. - - - -По умолчанию параметр timeout равен 60 секундам. - - - - -Эта директива доступна как часть -коммерческой подписки. - - - - - - - - - cookie имя - [expires=время] - [domain=домен] - [path=путь] - - route переменная ... - - learn - create=$переменная - lookup=$переменная - zone=имя:размер - [timeout=время] - -upstream -1.5.7 - - -Включает режим привязки сеансов, в котором запросы клиента -будут передаваться на один и тот же сервер группы. -Доступны три метода: - -cookie - - - -При использовании метода cookie информация о -назначенном сервере передаётся в HTTP-куке: - -upstream backend { - server backend1.example.com; - server backend2.example.com; - - sticky cookie srv_id expires=1h domain=.example.com path=/; -} - - - - -Запрос от клиента, ещё не привязанного к определённому серверу, -передаётся на сервер, выбранный согласно настроенному методу балансировки. -Дальнейшие запросы от этого клиента передаются на тот же сервер. -Если назначенный сервер не может обработать запрос, выбирается новый -сервер как если бы клиент не имел привязки к серверу. - - - -Первый параметр задаёт имя куки, которую необходимо установить или проверить. -Дополнительные параметры могут быть следующими: - - -expires - -Задаёт время, в течение которого браузеру необходимо хранить куку. -Специальное значение max устанавливает срок хранения куки до -31 декабря 2037 года 23:55:55 GMT. -Если параметр не указан, то время действия куки ограничивается сессией браузера. - - -domain - -Задаёт домен, для которого устанавливается кука. - - -path - -Задаёт путь, для которого устанавливается кука. - - - -Если пропущен тот или иной параметр, то соответствующего поля в куке не будет. - - - -route - - - -При использовании метода route проксируемый сервер назначает -клиенту маршрут по получении первого запроса. -Все последующие запросы от этого клиента будут содержать информацию о -маршруте в куке или URI. -Эта информация сравнивается с параметром “route” директивы - для идентификации сервера, на который -следует проксировать запрос. -Если назначенный сервер не может обработать запрос, выбирается новый сервер -согласно настроенному методу балансировки как если бы в запросе не было -информации о маршруте. - - - -Параметры метода route задают переменные, которые -могут содержать информацию о маршруте. -Первая непустая переменная используется для поиска соответствующего сервера. - - - -Пример: - -map $cookie_jsessionid $route_cookie { - ~.+\.(?P<route>\w+)$ $route; -} - -map $request_uri $route_uri { - ~jsessionid=.+\.(?P<route>\w+)$ $route; -} - -upstream backend { - server backend1.example.com route=a; - server backend2.example.com route=b; - - sticky route $route_cookie $route_uri; -} - -В этом примере маршрут берётся из куки “JSESSIONID”, -если она присутствует в запросе. -В противном случае используется маршрут из URI. - - - - -learn - - -При использовании метода learn (1.7.1) nginx -анализирует ответы от вышестоящего сервера и запоминает -начатые им сессии, которые обычно передаются в HTTP-куке. - -upstream backend { - server backend1.example.com:8080; - server backend2.example.com:8081; - - sticky learn - create=$upstream_cookie_sessionid - lookup=$cookie_sessionid - zone=client_sessions:1m; -} - - -В примере выше сервер группы создаёт сессию путём установки -куки “SESSIONID” в своём ответе. -Последующие запросы с этой кукой будут передаваться на этот же сервер. -Если сервер не может обработать запрос, выбирается новый -сервер как если бы клиент не имел привязки к серверу. - - - -Параметры create и lookup -задают переменные, в которых соответственно указывается способ -создания новых и поиска существующих сессий. -Оба параметра могут быть указаны больше одного раза -(в этом случае используется первая непустая переменная). - - - -Сессии хранятся в зоне разделяемой памяти, имя и -размер которой задаются параметром zone. -Зоны размером в 1 мегабайт достаточно для хранения около 8 тысяч сессий -на 64-битной платформе. -Сессии, к которым не было обращений в течение времени, заданного параметром -timeout, удаляются из зоны. -По умолчанию timeout равен 10 минутам. - - - - - - - - -Эта директива доступна как часть -коммерческой подписки. - - - - - - - -имя -[expires=время] -[domain=домен] -[path=путь] - -upstream - - -Эта директива устарела начиная с версии 1.5.7. -Вместо неё следует использовать аналогичную директиву - с изменённым синтаксисом: - -sticky cookie имя -[expires=время] -[domain=домен] -[path=путь]; - - - - - - @@ -1076,7 +89,7 @@ upstream backend { Команда настройки состоит из параметров, передаваемых в аргументах запроса, например: -http://127.0.0.1/upstream_conf?upstream=dynamic +http://127.0.0.1/upstream_conf?upstream=backend @@ -1086,6 +99,15 @@ http://127.0.0.1/upstream_conf?upstream= +stream= + +Выбирает группу серверов +stream. +Если параметр не задан, будет выбрана группа серверов +http. + + + upstream=имя Выбирает группу серверов для работы. @@ -1123,88 +145,112 @@ http://127.0.0.1/upstream_conf?upstream= server=адрес -То же, что и параметр “адрес” -директивы . +То же, что и параметр “адрес” сервера группы +http +или +stream. При добавлении сервер можно задать в виде доменного имени. В этом случае любые изменения IP-адресов, соответствующих доменному имени сервера, отслеживаются и автоматически применяются к конфигурации группы без необходимости перезапуска nginx (1.7.2). -Для этого в блоке должна -быть задана директива . -См. также параметр - директивы . +Для этого в блоке +http +или +stream +должна быть задана директива “resolver”. +См. также параметр “resolve” сервера группы +http +или +stream. weight=число -То же, что и параметр “weight” -директивы . +То же, что и параметр “weight” сервера группы +http +или +stream. max_conns=число -То же, что и параметр “max_conns” -директивы . +То же, что и параметр “max_conns” сервера группы +http +или +stream. max_fails=число -То же, что и параметр “max_fails” -директивы . +То же, что и параметр “max_fails” сервера группы +http +или +stream. fail_timeout=время -То же, что и параметр “fail_timeout” -директивы . +То же, что и параметр “fail_timeout” сервера группы +http +или +stream. slow_start=время -То же, что и параметр “slow_start” -директивы . +То же, что и параметр “slow_start” сервера группы +http +или +stream. down= -То же, что и параметр “down” -директивы . +То же, что и параметр “down” сервера группы +http +или +stream. drain= - -Переводит сервер группы в режим “draining” (1.7.5). +Переводит сервер группы серверов +http +в режим “draining” (1.7.5). В этом режиме на сервер будут проксироваться только -привязанные к нему запросы. +привязанные +к нему запросы. up= -Параметр, обратный по значению параметру “down” -директивы . +Параметр, обратный по значению параметру “down” сервера группы +http +или +stream. route=строка -То же, что и параметр “route” -директивы . +То же, что и параметр “route” сервера группы +http. -Первые два параметра выбирают объект. -Объектом может быть либо группа серверов, либо отдельный сервер. +Первые три параметра выбирают объект. +Объектом может быть либо группа серверов http или stream, +либо отдельный сервер. Если остальные параметры не указаны, то показывается конфигурация выбранной группы или сервера. @@ -1213,176 +259,75 @@ http://127.0.0.1/upstream_conf?upstream= Например, команда для просмотра конфигурации всей группы выглядит следующим образом: -http://127.0.0.1/upstream_conf?upstream=dynamic +http://127.0.0.1/upstream_conf?upstream=backend Для просмотра конфигурации отдельного сервера следует указать его идентификатор: -http://127.0.0.1/upstream_conf?upstream=dynamic&id=42 +http://127.0.0.1/upstream_conf?upstream=backend&id=42 - Для добавления нового сервера в группу следует указать его адрес в параметре “server=”. Если остальные параметры не указаны, то при добавлении сервера -их значения будут установлены по умолчанию (см. директиву ). +их значения будут установлены по умолчанию (см. директиву +“server” для +http +или +stream). Например, команда для добавления нового основного сервера в группу выглядит следующим образом: -http://127.0.0.1/upstream_conf?add=&upstream=dynamic&server=127.0.0.1:8080 +http://127.0.0.1/upstream_conf?add=&upstream=backend&server=127.0.0.1:8080 Добавление нового запасного сервера происходит следующим образом: -http://127.0.0.1/upstream_conf?add=&upstream=dynamic&backup=&server=127.0.0.1:8080 +http://127.0.0.1/upstream_conf?add=&upstream=backend&backup=&server=127.0.0.1:8080 Добавление нового основного сервера с нестандартными значениями параметров и с пометкой его как постоянно недоступного (“down”) происходит следующим образом: -http://127.0.0.1/upstream_conf?add=&upstream=dynamic&server=127.0.0.1:8080&weight=2&down= +http://127.0.0.1/upstream_conf?add=&upstream=backend&server=127.0.0.1:8080&weight=2&down= - - Для удаления сервера следует указать его идентификатор: -http://127.0.0.1/upstream_conf?remove=&upstream=dynamic&id=42 +http://127.0.0.1/upstream_conf?remove=&upstream=backend&id=42 - - Пометка существующего сервера как постоянно недоступного (“down”) происходит следующим образом: -http://127.0.0.1/upstream_conf?upstream=dynamic&id=42&down= +http://127.0.0.1/upstream_conf?upstream=backend&id=42&down= Изменение адреса существующего сервера происходит следующим образом: -http://127.0.0.1/upstream_conf?upstream=dynamic&id=42&server=192.0.2.3:8123 +http://127.0.0.1/upstream_conf?upstream=backend&id=42&server=192.0.2.3:8123 Изменение других параметров существующего сервера происходит следующим образом: -http://127.0.0.1/upstream_conf?upstream=dynamic&id=42&max_fails=3&weight=4 +http://127.0.0.1/upstream_conf?upstream=backend&id=42&max_fails=3&weight=4 - - - - -Эта директива доступна как часть -коммерческой подписки. - +Вышеприведённые примеры актуальны для группы серверов +http. +Аналогичные примеры для группы серверов +stream +требуют указания параметра “stream=”.
- -
- - -Модуль ngx_http_upstream_module -поддерживает следующие встроенные переменные: - - -$upstream_addr - -хранит IP-адрес и порт или путь к UNIX-сокету сервера группы. -Если при обработке запроса были сделаны обращения к нескольким серверам, -то их адреса разделяются запятой, например, -“192.168.1.1:80, 192.168.1.2:80, unix:/tmp/sock”. -Если произошло внутреннее перенаправление от одной группы серверов на другую -с помощью -
X-Accel-Redirect
или -, -то адреса, соответствующие разным группам серверов, разделяются двоеточием, -например, -“192.168.1.1:80, 192.168.1.2:80, unix:/tmp/sock : 192.168.10.1:80, 192.168.10.2:80”. -
- -$upstream_cache_status - - -хранит статус доступа к кэшу ответов (0.8.3). -Статус может быть одним из “MISS”, -“BYPASS”, “EXPIRED”, -“STALE”, “UPDATING”, -“REVALIDATED” или “HIT”. - - -$upstream_cookie_имя - - -кука с указанным именем, переданная сервером группы -в поле
Set-Cookie
заголовка ответа (1.7.1). -Необходимо иметь в виду, что куки запоминаются только из ответа -последнего сервера. -
- -$upstream_header_time - - -хранит время, -затраченное на получение заголовка ответа от сервера группы (1.7.10); -время хранится в секундах с точностью до миллисекунд. -Времена нескольких ответов -разделяются запятыми и двоеточиями подобно адресам в переменной -$upstream_addr. - - -$upstream_http_имя - -хранят поля заголовка ответа сервера. -Например, поле заголовка ответа
Server
-доступно в переменной $upstream_http_server. -Правила преобразования имён полей заголовка ответа в имена переменных -такие же, как для переменных с префиксом -“$http_”. -Необходимо иметь в виду, что поля заголовка запоминаются только из ответа -последнего сервера. -
- -$upstream_response_length - - -хранит длину ответа, полученного от сервера группы (0.7.27); -длина хранится в байтах. -Длины нескольких ответов -разделяются запятыми и двоеточиями подобно адресам в переменной -$upstream_addr. - - -$upstream_response_time - - -хранит время, затраченное на получение ответа от сервера группы; -время хранится в секундах с точностью до миллисекунд. -Времена нескольких ответов -разделяются запятыми и двоеточиями подобно адресам в переменной -$upstream_addr. - - -$upstream_status - -хранит статус ответа, полученного от сервера группы. -Статусы нескольких ответов -разделяются запятыми и двоеточиями подобно адресам в переменной -$upstream_addr. - - -
-
- -
-
diff --git a/xml/ru/docs/http/ngx_http_upstream_module.xml b/xml/ru/docs/http/ngx_http_upstream_module.xml --- a/xml/ru/docs/http/ngx_http_upstream_module.xml +++ b/xml/ru/docs/http/ngx_http_upstream_module.xml @@ -10,7 +10,7 @@ + rev="36">
@@ -54,12 +54,15 @@ server { доступна как часть коммерческой подписки: +resolver 10.0.0.1; + upstream dynamic { zone upstream_dynamic 64k; server backend1.example.com weight=5; server backend2.example.com:8080 fail_timeout=5s slow_start=30s; server 192.0.2.1 max_fails=3; + server backend3.example.com resolve; server backup1.example.com:8080 backup; server backup2.example.com:8080 backup; @@ -70,12 +73,6 @@ server { proxy_pass http://dynamic; health_check; } - - location /upstream_conf { - upstream_conf; - allow 127.0.0.1; - deny all; - } } @@ -299,7 +296,8 @@ http { или настроек отдельных серверов нет необходимости перезапускать nginx. Конфигурация доступна через специальный location, -в котором указана директива . +в котором указана директива +. @@ -533,6 +531,38 @@ server { + +header | last_byte + +upstream +1.7.10 + + +Задаёт для группы метод балансировки нагрузки, при котором запрос +передаётся серверу с наименьшими средним временем ответа и +числом активных соединений с учётом весов серверов. +Если подходит сразу несколько серверов, то они выбираются циклически +(в режиме round-robin) с учётом их весов. + + + +Если указан параметр header, +то учитывается время получения +заголовка ответа. +Если указан параметр last_byte, то учитывается +время получения всего ответа. + + + + +Эта директива доступна как часть +коммерческой подписки. + + + + + + [параметры] @@ -842,6 +872,8 @@ match server_ok { cookie имя [expires=время] [domain=домен] + [httponly] + [secure] [path=путь] route переменная ... @@ -889,22 +921,32 @@ upstream backend { Дополнительные параметры могут быть следующими: -expires +expires=время -Задаёт время, в течение которого браузеру необходимо хранить куку. +Задаёт время, в течение которого браузеру необходимо хранить куку. Специальное значение max устанавливает срок хранения куки до 31 декабря 2037 года 23:55:55 GMT. Если параметр не указан, то время действия куки ограничивается сессией браузера. -domain +domain=домен -Задаёт домен, для которого устанавливается кука. +Задаёт домен, для которого устанавливается кука. -path +httponly + +Добавляет атрибут HttpOnly к куке (1.7.11). + + +secure -Задаёт путь, для которого устанавливается кука. +Добавляет атрибут Secure к куке (1.7.11). + + +path=путь + +Задаёт путь, для которого устанавливается кука. @@ -1038,253 +1080,6 @@ upstream backend { - - - - -location - - -Активирует HTTP-интерфейс для настройки групп серверов в содержащем location. -Доступ в location следует -ограничить. - - - -С помощью команд настройки можно: - - -просматривать конфигурацию группы; - - -просматривать или изменять конфигурацию, а также -удалять серверы; - - -добавлять новые серверы. - - - -Поскольку адреса в группе не обязаны быть уникальными, -обращение к отдельным серверам в группе осуществляется по их идентификаторам. -Идентификаторы назначаются автоматически и показываются при добавлении сервера -или просмотре конфигурации группы. - - - - -Команда настройки состоит из параметров, передаваемых в аргументах запроса, -например: - -http://127.0.0.1/upstream_conf?upstream=dynamic - - - - -Поддерживаются следующие параметры: - - - - -upstream=имя - -Выбирает группу серверов для работы. -Параметр является обязательным. - - - -id=число - -Выбирает сервер для просмотра, изменения или удаления. - - - -remove= - -Удаляет сервер из группы. - - - -add= - -Добавляет новый сервер в группу. - - - -backup= - -Необходим для добавления запасного сервера. - -До версии 1.7.2 параметр backup= требовался -также для просмотра, изменения или удаления существующих запасных серверов. - - - - -server=адрес - -То же, что и параметр “адрес” -директивы . - -При добавлении сервер можно задать в виде доменного имени. -В этом случае любые изменения IP-адресов, соответствующих доменному имени -сервера, отслеживаются и автоматически применяются к конфигурации группы -без необходимости перезапуска nginx (1.7.2). -Для этого в блоке должна -быть задана директива . -См. также параметр - директивы . - - - - -weight=число - -То же, что и параметр “weight” -директивы . - - - -max_conns=число - -То же, что и параметр “max_conns” -директивы . - - - -max_fails=число - -То же, что и параметр “max_fails” -директивы . - - - -fail_timeout=время - -То же, что и параметр “fail_timeout” -директивы . - - - -slow_start=время - -То же, что и параметр “slow_start” -директивы . - - - -down= - -То же, что и параметр “down” -директивы . - - -drain= - - -Переводит сервер группы в режим “draining” (1.7.5). -В этом режиме на сервер будут проксироваться только -привязанные к нему запросы. - - - -up= - -Параметр, обратный по значению параметру “down” -директивы . - - - -route=строка - -То же, что и параметр “route” -директивы . - - - - -Первые два параметра выбирают объект. -Объектом может быть либо группа серверов, либо отдельный сервер. -Если остальные параметры не указаны, то показывается конфигурация выбранной -группы или сервера. - - - -Например, команда для просмотра конфигурации всей группы -выглядит следующим образом: - -http://127.0.0.1/upstream_conf?upstream=dynamic - - -Для просмотра конфигурации отдельного сервера следует указать его идентификатор: - -http://127.0.0.1/upstream_conf?upstream=dynamic&id=42 - - - - - -Для добавления нового сервера в группу -следует указать его адрес в параметре “server=”. -Если остальные параметры не указаны, то при добавлении сервера -их значения будут установлены по умолчанию (см. директиву ). - - - -Например, команда для добавления нового основного сервера в группу -выглядит следующим образом: - -http://127.0.0.1/upstream_conf?add=&upstream=dynamic&server=127.0.0.1:8080 - - -Добавление нового запасного сервера происходит следующим образом: - -http://127.0.0.1/upstream_conf?add=&upstream=dynamic&backup=&server=127.0.0.1:8080 - - -Добавление нового основного сервера с нестандартными -значениями параметров и с пометкой его как постоянно недоступного -(“down”) происходит следующим образом: - -http://127.0.0.1/upstream_conf?add=&upstream=dynamic&server=127.0.0.1:8080&weight=2&down= - - - - -Для удаления сервера следует указать его идентификатор: - -http://127.0.0.1/upstream_conf?remove=&upstream=dynamic&id=42 - - - - -Пометка существующего сервера как постоянно недоступного -(“down”) происходит следующим образом: - -http://127.0.0.1/upstream_conf?upstream=dynamic&id=42&down= - - -Изменение адреса существующего сервера происходит следующим образом: - -http://127.0.0.1/upstream_conf?upstream=dynamic&id=42&server=192.0.2.3:8123 - - -Изменение других параметров существующего сервера происходит следующим образом: - -http://127.0.0.1/upstream_conf?upstream=dynamic&id=42&max_fails=3&weight=4 - - - - - - -Эта директива доступна как часть -коммерческой подписки. - - - - -
diff --git a/xml/ru/docs/index.xml b/xml/ru/docs/index.xml --- a/xml/ru/docs/index.xml +++ b/xml/ru/docs/index.xml @@ -8,7 +8,7 @@
@@ -409,6 +409,11 @@ ngx_http_upstream_module + +ngx_http_upstream_conf_module + + + ngx_http_userid_module diff --git a/xml/ru/docs/ngx_core_module.xml b/xml/ru/docs/ngx_core_module.xml --- a/xml/ru/docs/ngx_core_module.xml +++ b/xml/ru/docs/ngx_core_module.xml @@ -10,7 +10,7 @@ + rev="13">
@@ -158,6 +158,7 @@ events { logs/error.log error main http +stream server location @@ -194,6 +195,12 @@ events { nginx с --with-debug, см. “”. + + +Директива может быть указана на +уровне stream +начиная с версии 1.7.11. +