tcp/udp
-
For UDP traffic, also include the udp parameter. As TCP is the default protocol for the stream context, there is no tcp parameter to the listen directive
example:stream { server { listen 12345; # ... } server { listen 53 udp; # ... } # ... }
load balance
-
Round Robin(default)
-
Least Connections NGINX selects the server with the smaller number of current active connections
-
Hash NGINX selects the server based on a user‑defined key, for example, the source IP address ($remote_addr):
upstream stream_backend { hash $remote_addr; server backend1.example.com:12345; server backend2.example.com:12345; server backend3.example.com:12346; }
The Hash load‑balancing method is also used to configure session persistence. As the hash function is based on client IP address, connections from a given client are always passed to the same server unless the server is down or otherwise unavailable. Specify an optional consistent parameter to apply the ketama consistent hashing method:
hash $remote_addr consistent;
-
Random – Each connection will be passed to a randomly selected server. If the two parameter is specified, first, NGINX randomly selects two servers taking into account server weights, and then chooses one of these servers using the specified method:
least_conn – The least number of active connections
The Random load balancing method should be used for distributed environments where multiple load balancers are passing requests to the same set of backends. For environments where the load balancer has a full view of all requests, use other load balancing methods, such as round robin, least connections and least time.
-
Optionally, for each upstream server specify server‑specific parameters including maximum number of connections, server weight, and so on:
upstream stream_backend { hash $remote_addr consistent; server backend1.example.com:12345 weight=5; server backend2.example.com:12345; server backend3.example.com:12346 max_conns=3; } upstream dns_servers { least_conn; server 192.168.136.130:53; server 192.168.136.131:53; # ... }
Health Checks
- fail_timeout
- max_fails
The default values are 10 seconds and 1 attempt
upstream stream_backend {
server backend1.example.com:12345 weight=5;
server backend2.example.com:12345 max_fails=2 fail_timeout=30s;
server backend3.example.com:12346 max_conns=3;
}
参考文献:https://docs.nginx.com/nginx/admin-guide/