58.Nginx的反向代理和负载均衡
Nginx的反向代理和负载均衡
基本概念
反向代理:Nginx作为后端服务器的代理,实现动静分离和负载均衡
负载均衡:将请求分发到多个后端服务器,提高处理能力和可靠性
动静分离:静态资源由Nginx直接处理,动态请求转发到后端应用服务器
代理的角色关系:
被代理角色:后端服务器
目标角色:客户端用户
代理角色:Nginx服务器
特征 | 正向代理 | 反向代理 |
---|---|---|
代理对象 | 代理客户端 | 代理服务器 |
配置位置 | 客户端需要主动配置 | 对客户端透明,无需配置 |
隐藏对象 | 隐藏客户端的身份 | 隐藏服务器的身份 |
应用场景 | 科学上网、内网访问控制、缓存加速 | 负载均衡、网站高可用、安全防护、动静分离 |
知名例子 | Shadowsocks, VPN(部分模式) | Nginx, Apache Traffic Server, CDN |
负载均衡
Nginx | 192.168.100.10 | centos7 |
---|---|---|
Rs2 | 192.168.100.20 | centos7 |
Rs3 | 192.168.100.30 | centos7 |
三台主机需要关闭防火墙和selinux,并且部署yum仓库
在,rs2和rs3安装httpd,在nginx主机上修改配置文件,设置负载均衡
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf#在http{}中配置upstream
upstream web{server 192.168.100.20;server 192.168.100.30;}server {listen 80;server_name localhost;location / {proxy_pass http://web;}
重载nginx
[root@nginx ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@nginx ~]# nginx -s reload
也可以通过在ip后加weight=2设置权重
假如后端真实服务器的端口为8080,则可以写
server 192.168.100.20:8080 weight=2;
ip_hash的配置
ip_hash的配置可以将ip分配给对应的http服务器,这样在下次访问的时候还是访问对应的httpd
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.confupstream web{ip_hash;server 192.168.100.20;server 192.168.100.30;}
[root@nginx ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@nginx ~]# nginx -s reload
分配给rs3后再次访问依然是rs3
假如集群中的某台服务器出现故障,想要从nginx的集群配置中移除掉,不可以直接的将那一行删掉,直接删掉会导致nginx的hash算法重新计算,那么用户的缓存都会失效,所以这里如果不用这台服务器,直接比较为down即可,也就是 server 192.168.100.10:8080 down
动静分离 nginx+tomcat
Tomcat:192.168.100.10
在nginx服务器部署tomcat
首先要安装java环境
[root@nginx ~]# yum -y install java-11-openjdk
[root@nginx ~]# tar -xzf apache-tomcat-10.0.23.tar.gz -C /usr/local/cd /usr/local/
[root@nginx ~]# cd /usr/local/
[root@nginx local]# ln -s apache-tomcat-10.0.23/ tomcat
自定义一个测试网页
[root@nginx local]# mkdir /usr/local/tomcat/webapps/test
[root@nginx local]# cd /usr/local/tomcat/webapps/test
[root@nginx test]# vim index.jsp<html>
<head><title>test page</title>
</head>
<body><%out.println("Hello World");%>
</body>
</html>
启动tomcat
[root@nginx bin]# ./startup.sh
Using CATALINA_BASE: /usr/local/tomcat
Using CATALINA_HOME: /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME: /usr
Using CLASSPATH: /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
Using CATALINA_OPTS:
Tomcat started.
配置nginx,设置动静分离
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.confupstream web{server 192.168.100.20;server 192.168.100.30;}upstream tomcat{server 192.168.100.10:8080;}location / {proxy_pass http://web;}location /test {proxy_pass http://tomcat;
}
[root@nginx ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@nginx ~]# nginx -s reload
测试查看