nginx反向代理和负载均衡
实验环境
主机名 | IP地址 | 角色 | 服务 |
---|---|---|---|
proxy | 192.168.100.33 | 代理 | nginx |
nginx | 192.168.100.131 | web | nginx |
apache | 192.168.100.116 | web | apache |
实验思路
Nginx实现负载均衡用到了proxy_pass代理模块核心配置, 将客户端请求代理转发至一组upstream虚拟服务池,默认的方式是轮询,如果要确定同一个访问者发出的请求总是由同一个后端服务器来处理,可以设置ip_hash
配置服务
- proxy端配置
#gzip on;
upstream dsb {
server 192.168.100.131:8080;
server 192.168.100.116:8090;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://dsb;
root html;
index index.html;
}
- 在apache这台服务器上,修改端口号,添加图片
[root@apache ~]# vim /etc/httpd/conf/httpd.conf
#Listen 12.34.56.78:80
Listen 8090
[root@apache ~]# ss -anlt
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:22 *:*
LISTEN 0 100 127.0.0.1:25 *:*
LISTEN 0 128 :::22 :::*
LISTEN 0 100 ::1:25 :::*
LISTEN 0 128 :::8090 :::*
[root@apache html]# ls
dsb.jpg
- 修改nginx 这台服务器上的端口,添加网页测试
[root@nginx html]# vim /etc/nginx/nginx.con
server {
listen 8080 default_server;
listen [::]:8080 default_server;
server_name _;
root /usr/share/nginx/html;
[root@nginxhtml]# ss -anlt
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:8080 *:*
LISTEN 0 128 *:22 *:*
LISTEN 0 100 127.0.0.1:25 *:*
LISTEN 0 128 :::8080 :::*
LISTEN 0 128 :::22 :::*
LISTEN 0 100 ::1:25 :::*
[root@nginx html]# ls
404.html 50x.html dsb.jpg
验证结果
第一次访问主服务器
再次访问主服务器
- 配置权重比
upstream dsb {
server 192.168.100.131:8080 weight=2;
server 192.168.100.116:8090 weight=1;
}
//131访问两次,116访问一次
- 一个访问者发出的请求总是由同一个后端服务器来处理
设置ip_hash
upstream dsb {
ip_hash;
server 192.168.100.131:8080 ;
server 192.168.100.116:8090 ;
}
//访问者都是由同一个后端服务器来处理,当这个服务器down后,自动切换到另一个服务器