nginx的负载均衡几种配置的示例代码
时间: 2024-09-11 21:09:52 浏览: 35
Nginx作为一款流行的开源Web服务器和反向代理,提供了多种负载均衡策略。以下是几个常见的配置示例:
1. **轮询(Round Robin)**:
```nginx
upstream backend {
server server1.example.com;
server server2.example.com;
server server3.example.com;
}
server {
location / {
proxy_pass http://backend;
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
}
}
```
这里,请求会轮流发送到后端的每一个服务器。
2. **最少连接数(Least Connections)**:
```nginx
upstream backend {
least_conn;
server server1.example.com;
server server2.example.com;
server server3.example.com;
}
```
请求会被发送到连接数最少的服务器。
3. **IP哈希(IP Hashing)**:
```nginx
upstream backend {
ip_hash;
server server1.example.com;
server server2.example.com;
server server3.example.com;
}
```
通过客户端的IP地址做哈希,保证来自同一客户端的请求始终路由到同一台服务器。
4. **权重轮询(Weighted Round Robin)**:
```nginx
upstream backend {
weight = 10; # server1 has a higher weight
server server1.example.com weight=10 max_fails=3 fail_timeout=10s;
server server2.example.com;
server server3.example.com;
}
```
这里的`weight`属性定义了服务器的优先级,权重越高,被选中的概率越大。
阅读全文