nginx反向代理负载均衡实战
本文介绍nginx简单反向代理实例,架构简单如下:
配置被代理的服务器集群:
upstream webservers {
server localhost:8891 weight=1;
server localhost:8890 weight=1;
keepalive 100; #默认没有配置,这个不配置的话 keepalive也开启不了
}
默认情况下nginx与后端服务器没开启长链接。需要配置nginx:
location ~/bigspoon {
#root html;
# index index.html index.htm;
proxy_pass http://webservers;
proxy_http_version 1.1;
proxy_set_header Connection "";# 不配置的话nginx会默认是close
}
测试结果:
System.out.println("后端服务port:"+port+",nginx连后端服务的端口:"+request.getRemotePort());
随便在浏览器访问多次后
http1.1浏览器默认keepalive默认是开启的
8890节点:
后端服务port:8890,nginx连后端服务的端口:55858
后端服务port:8890,nginx连后端服务的端口:55859
后端服务port:8890,nginx连后端服务的端口:55858
后端服务port:8890,nginx连后端服务的端口:55859
后端服务port:8890,nginx连后端服务的端口:55858
8891节点
后端服务port:8891,nginx连后端服务的端口:55854
后端服务port:8891,nginx连后端服务的端口:55856
后端服务port:8891,nginx连后端服务的端口:55854
后端服务port:8891,nginx连后端服务的端口:55856
后端服务port:8891,nginx连后端服务的端口:55854
这里看出实际上nginx与每个节点建立了两个长连接,多次请求复用了相同的tcp连接。
本文只是反向代理简单实战,实际应用时,需要考虑nginx 超时时间配置如:
send_timeout 与客户端超时
proxy_read_timeout 与代理的服务器读超时
proxy_send_timeout 与代理的服务器发送超时 等
以及nginx缓存配置,请求报文大小配置等。