Nginx负载均衡
1.Nginx负载均衡概述
提升吞吐率, 提升请求性能, 提⾼容灾
image.png
负载均衡按范围划分:GSLB全局负载均衡、SLB
image.png
Nginx 是⼀个典型的 SLB
image.png
负载均衡按层级划分: 分为四层负载均衡和七层负载均衡
image.png
Nginx 是⼀个典型的七层 SLB
image.png
2.Nginx负载均衡配置场景
Nginx 实现负载均衡⽤到了 proxy_pass 代理模块核⼼配置, 将客户端请求代理转发⾄⼀组 upstream 虚拟服务池。
image.png
Nginx upstream 虚拟配置语法
Syntax: upstream name { ... }
Default: -
Context: http
//upstream例⼦
upstream backend {
server backend1.example.com weight=5;
server backend2.example.com:8080;
server unix:/tmp/backend3;
server backup1.example.com:8080 backup;
}
server {
location / {
proxy_pass http://backend;
}
}
2.1.创建对应 html ⽂件
[root@Nginx ~]# mkdir /soft/{code1,code2,code3} -p
[root@Nginx ~]# cat /soft/code1/index.html
<html>
<title> Code1</title>
<body bgcolor="red">
<h1> Code1-8081 </h1>
</body>
</html>
[root@Nginx ~]# cat /soft/code2/index.html
<html>
<title> Coder2</title>
<body bgcolor="blue">
<h1> Code1-8082</h1>
</body>
</html>
[root@Nginx ~]# cat /soft/code3/index.html
<html>
<title> Coder3</title>
<body bgcolor="green">
<h1> Code1-8083</h1>
</body>
</html>
2.2.建⽴对应的 releserver.conf 配置⽂件
[root@Nginx ~]# cat /etc/nginx/conf.d/releserver.conf
server {
listen 8081;
root /soft/code1;
index index.html;
}
server {
listen 8082;
root /soft/code2;
index index.html;
}
server {
listen 8083;
root /soft/code3;
index index.html;
}
2.3.配置 Nginx 反向代理
[root@Nginx ~]# cat /etc/nginx/conf.d/proxy.conf
upstream node {
server 192.168.69.113:8081;
server 192.168.69.113:8082;
server 192.168.69.113:8083;
}
server {
server_name 192.168.69.113;
listen 80;
location / {
proxy_pass http://node;
include proxy_params;
}
}
2.4.使⽤浏览器验证
image.png
image.png
image.png
3.Nginx负载均衡状态配置
后端服务器在负载均衡调度中的状态
image.png
测试 backup 以及 down 状态
upstream load_pass {
server 192.168.56.11:8001 down;
server 192.168.56.12:8002 backup;
server 192.168.56.13:8003 max_fails=1 fail_timeout=10s;
}
location / {
proxy_pass http://load_pass;
include proxy_params;
}
//关闭8003测试
4.Nginx负载均衡调度策略
image.pngNginx负载均衡权重轮询具体配置
upstream load_pass {
server 192.168.56.11:8001;
server 192.168.56.12:8002 weight=5;
server 192.168.56.13:8003;
}
Nginx负载均衡 ip_hash 具体配置
//如果客户端都⾛相同代理, 会导致某⼀台服务器连接过多
upstream load_pass {
ip_hash;
server 192.168.56.11:8001;
server 192.168.56.12:8002;
server 192.168.56.13:8003;
}
//如果出现通过代理访问会影响后端节点接收状态均衡
Nginx负载均衡url_hash具体配置
upstream load_pass {
hash $request_uri;
server 192.168.56.11:8001;
server 192.168.56.12:8002;
server 192.168.56.13:8003;
}
//针对三台服务器添加相同⽂件
/soft/code1/url1.html url2.html url3.html
/soft/code2/url1.html url2.html url3.html
/soft/code3/url1.html url2.html url3.html
5.Nginx负载均衡TCP配置
Nginx 四层代理仅能存在于 main
段
stream {
upstream ssh_proxy {
hash $remote_addr consistent;
server 192.168.56.103:22;
}
upstream mysql_proxy {
hash $remote_addr consistent;
server 192.168.56.103:3306;
}
server {
listen 6666;
proxy_connect_timeout 1s;
proxy_timeout 300s;
proxy_pass ssh_proxy;
}
server {
listen 5555;
proxy_connect_timeout 1s;
proxy_timeout 300s;
proxy_pass mysql_proxy;
}
}
网友评论