Nginx配置负载均衡和反向代理
1. 负载均衡
Nginx的负载均衡算法有以下几种:round-robin
,least-connected
,ip-hash
,weighted
,backup
。
-
round-robin — requests to the application servers are distributed in a round-robin fashion
轮询:这是Nginx默认的算法。将请求随机分配到到下游每个服务上,请求越多越平均。
配置如下:
http { upstream myapp1 { server srv1.example.com; server srv2.example.com; server srv3.example.com; } server { listen 80; location / { proxy_pass http://myapp1; } } }
-
least-connected — next request is assigned to the server with the least number of active connections
最少连接:下次请求被分配到拥有最少活跃连接数的服务上。
在
upstream
中配置least_conn
。配置如下:upstream myapp1 { least_conn; server srv1.example.com; server srv2.example.com; server srv3.example.com; }
-
ip-hash — a hash-function is used to determine what server should be selected for the next request (based on the client’s IP address).
ip-hash:用一种hash方式确定下一次请求选择哪个服务(基于客户端IP)。使用这种方式可以将客户端绑定到特定服务器上,使session保持粘性
sticky
或持久性persistent
。在
upstream
中配置ip_hash
。配置如下:upstream myapp1 { ip_hash; server srv1.example.com; server srv2.example.com; server srv3.example.com; }
-
weighted—It is also possible to influence nginx load balancing algorithms even further by using server weights.
权重:服务器权重也会影响nginx负载均衡算法。未配置服务器权重,意味着所有指定的服务器都被视为对特定负载平衡方法具有同等资格。
在
upstream
中配置weight
。配置如下:upstream myapp1 { server srv1.example.com weight=3; server srv2.example.com; server srv3.example.com; }
-
backup
热备:在主服务器正常工作时配置
backup
的备用服务器不会接收请求,当主服务器挂掉后本用服务器才会接收请求。在
upstream
中配置backup
。配置如下:upstream backend { server backend1.example.com weight=5; server backend2.example.com:8080; server unix:/tmp/backend3; server backup1.example.com:8080 backup; server backup2.example.com:8080 backup; } server { location / { proxy_pass http://backend; } }
参考:load-balancing、ngx-http-upstream-module
2. 反向代理
首先要理解正向代理和反向代理。如下图所示:
图左面为正向代理,代理客户端发送请求并接收服务端返回的响应;图右面为反向代理,代理服务端接收客户端请求并返回服务端响应。
具体的配置请参考下面两篇文档:Nginx 反向代理与负载均衡详解、Nginx 配置详解,这里为了节省时间不再解释。