Upstream#
Provides a context for describing groups of servers that can be used in the proxy_pass, fastcgi_pass, uwsgi_pass, scgi_pass, memcached_pass, and grpc_pass directives.
Session persistence, request queueing (PRO), and feedback-based load balancing (PRO)
are provided by the separate Upstream Sticky,
Upstream Queue, and
Upstream Feedback modules,
whose directives also go in the upstream block.
Related guides
Load Balancing: methods, weights, failures, and zone.
Console Light Web Panel: shows only groups with a zone.
Configuration Example#
upstream backend {
zone backend 1m;
server backend1.example.com weight=5;
server backend2.example.com:8080;
server backend3.example.com service=_example._tcp resolve;
server unix:/tmp/backend3;
server backup1.example.com:8080 backup;
server backup2.example.com:8080 backup;
}
resolver 127.0.0.53 status_zone=resolver;
server {
location / {
proxy_pass http://backend;
}
}
Directives#
backup_switch (PRO)#
The directive enables the ability to start server selection not from the primary group, but from the active group, i.e., the one where a server was successfully found last time. If a server cannot be found in the active group for the next request, and the search moves to the backup group, then this group becomes active, and subsequent requests are first directed to servers in this group.
| If the |
Example:
upstream my_backend {
zone my_backend 1m;
server primary1.example.com;
server primary2.example.com;
server backup1.example.com backup;
server backup2.example.com backup;
backup_switch permanent=2m;
}
If the balancer switches from primary servers to the backup group, all subsequent requests are handled by this backup group for 2 minutes. After 2 minutes elapse, the balancer rechecks the primary servers and makes them active again if they are working normally.
bind_conn (PRO)#
Allows binding a server connection to a client connection when the
value, specified as a string of variables, becomes different from "" and
"0".
If the bound server cannot take the next request over the client connection — for example after resolve removes its address from the group, or while the server is unavailable — the bound connection is closed and another server is chosen via the configured balancing method.
Warning
The bind_conn directive must be used after all directives
that set a load balancing method,
otherwise it will not work.
If it is used together with the sticky directive,
then bind_conn must come after sticky.
Warning
When using the directive, the Proxy module settings must allow the use of persistent connections, for example:
proxy_http_version 1.1;
proxy_set_header Connection "";
A typical use case for the directive is proxying connections with NTLM authentication, where it is necessary to ensure client-to-server binding at the beginning of negotiation:
map $http_authorization $ntlm {
~*^NTLM 1;
~*^Negotiate 1;
}
upstream ntlm_backend {
zone ntlm_backend 1m;
server 127.0.0.1:8080;
bind_conn $ntlm;
}
server {
# ...
location / {
proxy_pass http://ntlm_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
# ...
}
}
hash#
When building from the source code, support for this
directive can be disabled with the build option
--without-http_upstream_hash_module.
Specifies a load balancing method for a server group where the client-server mapping is determined using the hashed key value. The key can contain variables. 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.
hash $remote_addr;
| If the |
A name in the server directive can resolve to several addresses,
either when the configuration is loaded or through the
resolve parameter.
With consistent, the method hashes the name, not its addresses (with
the service parameter, it hashes the target names of the SRV records):
a request whose key maps to a name is passed to one of that name's addresses by
weighted round-robin balancing, so the key is not tied to any
single address.
Without consistent, each address counts as a separate server, but Angie
does not sort the addresses, so the address a key reaches can differ between
Angie instances.
To tie keys to individual addresses, see the
load-balancing guide.
ip_hash#
When building from the source code, support for this
directive can be disabled with the build option
--without-http_upstream_ip_hash_module.
Specifies a load balancing method for the group where requests are distributed among servers based on client IP addresses. The first three octets of the client's 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 that case, client requests will be passed to another server. Most likely this will also be the same server.
If one of the servers needs to be temporarily removed, it should be marked with the down parameter to preserve the current hashing of client IP addresses:
upstream backend {
zone backend 1m;
ip_hash;
server backend1.example.com;
server backend2.example.com;
server backend3.example.com down;
server backend4.example.com;
}
keepalive#
When building from the source code, support for this
directive can be disabled with the build option
--without-http_upstream_keepalive_module.
Activates the cache of 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.
Note
It should be particularly noted that the keepalive directive does not limit the total number of connections to upstream servers that Angie worker processes can open. The connections parameter should be set low enough to let upstream servers process new incoming connections as well.
Note
Cached connections are matched to upstream servers by address. When
resolve or the API command
DELETE removes an address from the group, connections cached for
that address are not closed: they occupy cache slots until the server
closes them, keepalive_timeout expires, or they are evicted, and
are reused only if that address returns to the group. The
proxy_connection_drop, fastcgi_connection_drop,
uwsgi_connection_drop, scgi_connection_drop, and
grpc_connection_drop directives do not close them: they act only on
active connections.
Warning
The keepalive directive must be used after all directives that set
a load balancing method, otherwise it will not work.
Example configuration of memcached upstream with keepalive connections:
upstream memcached_backend {
zone memcached_backend 1m;
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 proxy_http_version directive should be set to "1.1" and the Connection header field should be cleared:
upstream http_backend {
zone http_backend 1m;
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 "";
# ...
}
}
Note
Alternatively, HTTP/1.0 persistent connections can be used by passing the "Connection: Keep-Alive" header field to an upstream server, though this method is not recommended.
For FastCGI servers, it is required to set fastcgi_keep_conn for keepalive connections to work:
upstream fastcgi_backend {
zone fastcgi_backend 1m;
server 127.0.0.1:9000;
keepalive 8;
}
server {
#...
location /fastcgi/ {
fastcgi_pass fastcgi_backend;
fastcgi_keep_conn on;
# ...
}
}
Note
SCGI and uwsgi protocols do not have a concept of keepalive connections.
keepalive_requests#
Sets the maximum number of requests that can be served through one keepalive connection. After the maximum number of requests is made, the connection is closed.
Closing connections periodically is necessary to free per-connection memory allocations. Therefore, using too high maximum number of requests could result in excessive memory usage and not recommended.
keepalive_time#
Limits the maximum time during which requests can be processed through one keepalive connection. After this time is reached, the connection is closed following the subsequent request processing.
keepalive_timeout#
Sets a timeout during which an idle keepalive connection to an upstream server will stay open.
Note
This timeout governs idle connections to upstream servers. It is not the client-side keepalive_timeout (in the http, server, or location context), and it does not affect how long Angie waits for a new upstream connection to be established, which is set by the protocol's own connect timeout, such as proxy_connect_timeout.
least_conn#
When building from the source code, support for this
directive can be disabled with the build option
--without-http_upstream_least_conn_module.
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.
least_time#
| |
Default | — |
upstream |
When building from the source code, support for this
directive can be disabled with the build option
--without-http_upstream_least_time_module.
Specifies that the group should use a load balancing method where an active server's chance of receiving the request is inversely proportional to its average response time; the less it is, the more requests a server gets.
| The directive accounts for the average time to receive response headers. |
| The directive uses the average time to receive the entire response. |
| Serves the same purpose as response_time_factor and overrides it if the parameter is set. |
| Specifies a condition variable
that controls which responses are included in the calculation.
The average is updated
only if the condition variable for the response
is not Note By default, probes (PRO)
are not included in the calculation;
combining the $upstream_probe variable
with |
Current values are presented as header_time (headers only)
and response_time (entire responses) in the server's health object
among the upstream metrics in the API.
random#
When building from the source code, support for this
directive can be disabled with the build option
--without-http_upstream_random_module.
Specifies a load balancing method for the group where a request is passed to a randomly selected server, taking into account server weights.
| Angie randomly selects two servers, then selects one of them using the least_conn method, where a request is passed to the server with the least number of active connections. |
| Names the method that chooses between the two servers selected with
|
response_time_factor#
Sets the smoothing factor for the previous value when calculating the average response time for the least_time load balancing method using the exponentially weighted moving average formula.
The higher the specified number, the less new values affect the average; if
90 is specified, 90% of the previous value and only 10% of
the new value are taken. Valid values range from 0 to 99 inclusive.
Current calculation results are presented as header_time
(headers only) and response_time (entire responses) in the server's health
object among the upstream metrics in the API.
Note
Only successful responses are included in the calculation; what is considered an unsuccessful
response is determined by the proxy_next_upstream,
fastcgi_next_upstream, uwsgi_next_upstream,
scgi_next_upstream, memcached_next_upstream, and
grpc_next_upstream directives. Additionally, the header_time
value is recalculated only if all headers are received and processed, and
response_time — only if the entire response is received.
server#
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, port 80 is used. A domain name that resolves to multiple IP addresses defines multiple servers at once.
The following parameters can be defined:
| Sets the weight of the server. Default is 1. |
| Limits the maximum number of simultaneous active connections to the proxied server. The default value is |
Note
With idle keepalive connections enabled, multiple worker processes, and a shared memory zone, the total number of active and idle connections to the proxied server may exceed the max_conns value.
| Sets the number of unsuccessful attempts to communicate with the server that should occur during the specified fail_timeout period for the server to be considered unavailable; after this, it will be checked again after the same period. What is considered an unsuccessful attempt is defined by the proxy_next_upstream, fastcgi_next_upstream, uwsgi_next_upstream, scgi_next_upstream, memcached_next_upstream, and grpc_next_upstream directives. When Note If a If after resolving all
|
| Sets the period of time during which a specified number of unsuccessful attempts to communicate with the server (max_fails) must occur for the server to be considered unavailable. The server then remains unavailable for the same period of time before being checked again. Default value is 10 seconds. Note If a If after resolving all |
| Marks the server as a backup server. It will be passed requests when the primary servers are unavailable. If the backup_switch (PRO) directive is specified, its active backup logic also applies. |
| Marks the server as permanently unavailable. |
| Marks the server as draining; this means
it only receives requests from sessions
previously bound via sticky.
Otherwise, the behavior is the same as in |
Warning
The backup and slow_start parameters cannot be used together
with the hash, ip_hash, and
random load balancing methods; the weight and
slow_start parameters cannot be used with
least_time.
An unsupported combination is a configuration error: Angie does not start and
reports balancing method does not support parameter.
The down and drain parameters are mutually exclusive.
| Allows monitoring changes to the list of IP addresses corresponding to a domain name and updating it without reloading the configuration. The group must reside in shared memory; a resolver must also be defined. Connections cached for an address are not closed when that address is removed from the group. |
| Enables resolution of DNS SRV records and sets the service name. For
the parameter to work, the If the service name does not contain a dot, a name is formed according to the RFC standard:
the service name is prefixed with Angie resolves SRV records by combining the normalized service name and hostname and obtaining a list of servers for the resulting combination via DNS, along with their priorities and weights.
|
In this example, a lookup is performed for the record _http._tcp.backend.example.com:
server backend.example.com service=http resolve;
| Sets the server ID in the group. If the parameter is not specified, the ID is set as a hexadecimal MD5 hash of the IP address and port or UNIX socket path. |
| Same as |
| Sets the time for gradual recovery of a returning server's weight when load balancing with the round-robin or least_conn method. If the parameter is set and the server is considered operational again after a failure from the perspective of max_fails and upstream_probe (PRO), such a server gradually increases to its specified weight over the given time period. If the parameter is not set, in a similar situation the server immediately starts operating with its specified weight. |
Note
If only one server is specified in the upstream,
slow_start does not work and will be ignored.
state (PRO)#
Specifies a file where the list of upstream servers is persistently stored.
When installing from
our packages,
the directory
/var/lib/angie/state/ (/var/db/angie/state/ on FreeBSD)
is created specifically for storing such files
with appropriate access permissions,
and in the configuration you only need to add the file name:
upstream backend {
zone backend 1m;
state /var/lib/angie/state/<FILE_NAME>;
}
The server list here has a format similar to server.
The file contents are modified whenever servers are changed in the
/config/http/upstreams/ section
via the configuration API.
The file is read when Angie starts or when the configuration is reloaded.
Warning
To use the state directive in an upstream block,
there must be no server directives in it,
but a shared memory zone (zone) is required.
upstream#
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 {
zone backend 1m;
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. The distribution is smooth: a higher-weight server's requests are spread across the rotation rather than sent in a single burst.
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, Angie returns its own error page rather than the last server's response.
Note
By default, a server that fails an occasional attempt without reaching max_fails temporarily receives a smaller share of requests, regaining its full share over the requests that follow. This differs from slow_start, which ramps a server back up only after it has been marked unavailable and has recovered.
zone#
When building from the source code, support for this
directive can be disabled with the build option
--without-http_upstream_zone_module.
Defines the name and size of the shared memory zone that keeps the group's configuration and run-time state that are shared between worker processes. Several groups may share the same zone. In this case, it is enough to specify the size only once.
Note
A configuration reload creates the zone again whether or not size
changes: counters, passive-check state, and accumulated balancing history
start from zero. The addresses resolved for servers with resolve
carry over to the new zone, and in Angie PRO, so does the health flag
that active checks with the persistent parameter rely on.
Note
Upstream metrics are collected only when this zone is configured. Without it, the group does not appear in /status/http/upstreams/<upstream>, the HTTP Upstreams Widget, or Prometheus output, and no warning is logged. See Example configuration.
Built-in Variables#
The stores 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 192.168.1.1:80, 192.168.1.2:80, unix:/tmp/sock : 192.168.10.1:80, 192.168.10.2:80 If a server cannot be selected, the variable keeps the name of the server group. number of bytes received from an upstream server. Values from several connections are separated by commas and colons like addresses in the $upstream_addr variable. number of bytes sent to an upstream server. Values from several connections are separated by commas and colons like addresses in the $upstream_addr variable. Added in version 1.11.0. contains the cache key used for the request. keeps the status of accessing a response cache. The status can be either
If the request bypassed the cache without accessing it,
the variable is not set. keeps time spent on establishing a connection with the upstream server; the time is kept in seconds with millisecond resolution. In case of SSL, includes time spent on handshake. Times of several connections are separated by commas and colons like addresses in the $upstream_addr variable. Added in version 1.12.0: PRO address of the proxied server selected for the current connection attempt;
unlike $upstream_addr, which accumulates the addresses of every server
tried across retries, this variable always holds a single address and is
available immediately after the server is selected, including while
proxy_bind variables are evaluated. keeps time spent on receiving the response header 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. keep server response header fields. For example, the keeps time the request spent in the queue
before the next server selection;
the time is kept in seconds with millisecond resolution.
Times of several attempts are separated by commas and colons
like addresses in the $upstream_addr variable. Added in version 1.11.0. request method used for the upstream request. It can differ from the client
request method when caching converts keeps the length of the response obtained from the upstream server; the length is kept in bytes. Lengths of several responses are separated by commas and colons like addresses in the $upstream_addr variable. 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. keeps the status code recorded by Angie for each upstream attempt. For DoH
requests, a truncated UDP response is recorded as 426 and an accepted DNS
response as 200. Status codes from several attempts are separated by commas and
colons like addresses in the $upstream_addr variable. Status of requests in groups that use sticky. Request sent to an upstream where sticky is not enabled. Request does not contain sticky information. Request with sticky information sent to the desired server. Request with sticky information sent to a server
selected by the load balancing algorithm. Statuses from several connections are separated by commas and colons
like addresses in the $upstream_addr variable. keeps fields from the end of the response obtained from the upstream server. Added in version 1.12.0. keeps the transport protocol, http_upstream module supports the following built-in variables:$upstream_addr#X-Accel-Redirect or error_page, then the server addresses from different groups are separated by colons, e.g.:$upstream_bytes_received#$upstream_bytes_sent#$upstream_cache_key#$upstream_cache_status#MISS, BYPASS, EXPIRED, STALE, UPDATING,
REVALIDATED, or HIT:MISS: The response is not found in the cache,
and the request is passed to the upstream server.BYPASS: The cache is bypassed,
and the request is passed directly to the upstream server.EXPIRED: The cached response is stale,
and a new request is passed to the upstream server to update the content.STALE: The cached response is stale,
but is still served to clients
until the content is eventually updated from the upstream server.UPDATING: The cached response is stale,
but is still served to clients
while the currently ongoing update from the upstream server is in progress.REVALIDATED: The cached response is stale,
but was successfully revalidated
and does not need to be updated from the upstream server.HIT: The response was taken from the cache.$upstream_connect_time#$upstream_current_addr (PRO)#$upstream_header_time#$upstream_http_<name>#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_queue_time (PRO)#$upstream_request_method#HEAD to GET or when
proxy_method is set.$upstream_response_length#$upstream_response_time#$upstream_status#$upstream_sticky_status#""NEWHITMISS$upstream_trailer_<name>#$upstream_transport#TCP or UDP, used for each
upstream connection attempt. Values from several attempts are separated by
commas and colons like addresses in the $upstream_addr variable.