Nginx入门实践(五)
环境
系统:Windows7
Nginx版本:1.26.2
负载均衡模式
- round-robin轮询模式。
http {
upstream backend {
server backend1.com:8081;
server backend2.com:8082;
server backend3.com:8000;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://backend;
}
}
}
- least-connected最少连接模式:适用于请求花费时间较长的场景。
http {
upstream backend {
least_conn;
server backend1.com:8081;
server backend2.com:8082;
server backend3.com:8000;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://backend;
}
}
}
- ip_hash:适用于需要保持会话的场景,确保每一次请求都发送到同一台服务器。
http {
upstream backend {
ip_hash;
server backend1.com:8081;
server backend2.com:8082;
server backend3.com:8000;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://backend;
}
}
}
配置服务器权重
以round-robin为例
http {
upstream backend {
server backend1.com:8081 weight=3;
server backend2.com:8082;
server backend3.com:8000;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://backend;
}
}
}
健康检查:Nginx会自动探测服务的存活状态
探测次数:max_fails=3 ,默认0
探测超时时间:fail_timeout=30s
http {
upstream backend {
server backend1.com:8081 weight=3;
server backend2.com:8082 max_fails=3 fail_timeout=30s;
server backend3.com:8000;
}
}