http {
upstream backend {
server backend1.example.com weight=5;
server backend2.example.com;
server 192.0.0.1:8080 max_fails=3 fail_timeout=30s;
server unix:/tmp/backend3;
}
server {
location / {
proxy_pass http://backend;
}
}
}
基本配置说明:
backend1.example.com weight=5:设置后端服务器的权重为 5backend2.example.com:设置后端服务器的权重为 1(默认)192.0.0.1:8080 max_fails=3 fail_timeout=30s:设置后端服务器的最大失败次数为 3,失败超时时间为 30 秒unix:/tmp/backend3:设置后端服务器为 Unix Socket基本配置原理:
upstream 指令用于定义后端服务器组,server 指令用于定义后端服务器,proxy_pass 指令用于将请求转发到后端服务器组。
http {
upstream backend {
server backend1.example.com weight=5;
server backend2.example.com;
server 192.0.0.1:8080 max_fails=3 fail_timeout=30s;
server unix:/tmp/backend3;
keepalive 32;
}
server {
listen 80;
location / {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
}
}
完整配置说明:
keepalive 32:设置保持连接数为 32proxy_http_version 1.1:设置 HTTP 版本为 1.1proxy_set_header Connection "":设置 Connection 请求头为空完整配置原理:
keepalive 指令用于设置保持连接数,proxy_http_version 指令用于设置 HTTP 版本,proxy_set_header 指令用于设置请求头。
| 指令 | 说明 | 示例 |
|---|---|---|
weight | 服务器权重 | weight=5 |
max_fails | 最大失败次数 | max_fails=3 |
fail_timeout | 失败超时时间 | fail_timeout=30s |
keepalive | 保持连接数 | keepalive 32 |
proxy_http_version | HTTP 版本 | proxy_http_version 1.1 |
proxy_set_header | 设置请求头 | proxy_set_header Connection "" |
http {
upstream backend {
least_conn;
server backend1.example.com;
server backend2.example.com;
}
server {
location / {
proxy_pass http://backend;
}
}
}
负载均衡方法配置说明:
least_conn:使用最少连接算法负载均衡方法配置原理:
least_conn 指令用于设置负载均衡算法为最少连接算法。
http {
upstream backend {
ip_hash;
server backend1.example.com;
server backend2.example.com;
}
server {
location / {
proxy_pass http://backend;
}
}
}
会话保持配置说明:
ip_hash:使用 IP 哈希算法会话保持配置原理:
ip_hash 指令用于设置会话保持方法为 IP 哈希算法。