使用模块module
- upstream 负载均衡 Module ngx_http_upstream_module
- proxy_pass 负载均衡 Module ngx_http_proxy_module
反向代理
配置起来很简单比如我要将所有的请求到转移到真正提供服务的一台机器的 8080 端口,只要这样:
location / {
proxy_pass 123.34.56.67:8080;
}
负载均衡
我们在 upstream 中指定了一组机器,并将这个组命名为 backend,这样在 proxypass 中只要将请求转移到 backend 这个 upstream 中我们就实现了在四台机器的反向代理加负载均衡。其中的 iphash 指明了我们均衡的方式是按照用户的 ip 地址进行分配。
upstream backend {
ip_hash;
server backend1.example.com;
server backend2.example.com;
server backend3.example.com;
server backend4.example.com;
}
location / {
proxy_pass http://backend;
}