nginx的反向代理功能和负载均衡

使用nginx实现反向代理

Nginx只做请求的转发,后台有多个http服务器提供服务,nginx的功能就是把请求转发给后面的服务器,决定把请求转发给谁。

1安装tomcat

在一个虚拟机上创建两个tomcat实例,模拟多个服务器。

2需求

通过访问不同的域名访问运行在不同端口的tomcat,适用于分布式部署

8080.tomcat.com 访问运行8080端口的tomcat

8081.tomcat.com 访问运行8081端口的tomcat

3域名需要配置host文件:

# vim /etc/hosts

4Nginx的配置

 1 upstream tomcat1 {
 2     server 127.0.0.1:8080;
 3     }
 4     upstream tomcat2 {
 5     server 127.0.0.1:8081;
 6     }
 7    server {
 8         listen       80;
 9         server_name  8080.itheima.com;
10 
11         #charset koi8-r;
12 
13         #access_log  logs/host.access.log  main;
14 
15         location / {
16             proxy_pass   http://tomcat1;
17             index  index.html index.htm;
18         }
19 
20         
21     }
22     server {
23         listen       80;
24         server_name  8081.itheima.com;
25 
26         #charset koi8-r;
27 
28         #access_log  logs/host.access.log  main;
29 
30         location / {
31             proxy_pass   http://tomcat2;
32             index  index.html index.htm;
33         }
34 
35         
36     }
37 


如果在同一个域名下有多台服务器提供服务,此时需要nginx负载均衡。

只需要在一个upstream下添加服务机即可

置负载均衡的权重

在后边添加:weight=x,x越大,被分配到请求的概率越大,如图

-----------------------------------------------------------------------------------------------------------------------------------------

其他选项说明:

 1 节点说明:
 2 在http节点里添加:
 3 
 4 #定义负载均衡设备的 Ip及设备状态 
 5 upstream myServer {   
 6 
 7     server 127.0.0.1:9090 down; 
 8     server 127.0.0.1:8080 weight=2; 
 9     server 127.0.0.1:6060; 
10     server 127.0.0.1:7070 backup; 
11 }
12 
13 在需要使用负载的Server节点下添加
14 
15 proxy_pass http://myServer;
16 
17 upstream 每个设备的状态:
18 
19 down 表示单前的server暂时不参与负载 
20 weight  默认为1.weight越大,负载的权重就越大。 
21 max_fails :允许请求失败的次数默认为1.当超过最大次数时,返回proxy_next_upstream 模块定义的错误 
22 fail_timeout:max_fails 次失败后,暂停的时间。 
23 backup: 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻。
原文地址:https://www.cnblogs.com/webyyq/p/8973572.html