用例:客户端访问Nginx服务,Nginx反向代理的作用:项目部署在多个Tomcat上 即使其中一个tomcat不能访问了也能访问其他的Tomcat服务 其他负载均衡的作用效果可以自行百度。(分享给跟我一样的小白)
![](https://i-blog.csdnimg.cn/blog_migrate/2e6c05e876f8565196b03068ac7299ea.png)
推荐文章:
-Nginx安装及配置详解
1.条件准备:
1.1.Nginx安装包 下载地址
1.2.Tomcat安装包 下载地址
1.3.基本Tomcat和Nginx的相关知识要懂 起码得知道如何配置 和 如何启动
2.Tomcat部署并启动(多个Tomcat服务)
部署2个Tomcat-8070端口 和 Tomcat8071端口 (修改Tomcat端口)
遇到一些坑 启动Tomcat的时候 bin/下面的startup.bat会提示未配置Java_home 和 jre_home变量 的解决方案(点击这里):
因为startup.bat启动的时候会去同个目录下的setclasspath.bat里面找classpath
有件编辑添加这两句:(路径要根据具体电脑的JDK安装路径来改)
set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_121 set JRE_HOME=C:\Program Files\Java\jdk1.8.0_121\jre
修改端口并启动8070那个tomcat
8071端口
3.Nginx配置并部署
配置两个Tomcat服务指向 localhost:8070 和 localhost:8071他们的权重都是5(权重越大就越容易被访问)
-
upstream localhost {
-
#根据ip计算将请求分配各那个后端tomcat,许多人误认为可以解决session问题,其实并不能。
-
#同一机器在多网情况下,路由切换,ip可能不同
-
#ip_hash;
-
server localhost:
8070 weight=
5;
-
server localhost:
8071 weight=
5;
-
}
-
server {
-
listen
80;
-
server_name localhost;
-
-
location / {
-
proxy_connect_timeout
3;
-
proxy_send_timeout
30;
-
proxy_read_timeout
30;
-
proxy_pass http:
//localhost;
-
}
-
-
-
#error_page
404 /
404.html;
-
-
# redirect server error pages to the
static page /
50x.html
-
#
-
error_page
500
502
503
504 /
50x.html;
-
location = /
50x.html {
-
root html;
-
}
-
-
# proxy the PHP scripts to Apache listening on
127.0.0.1:
80
-
#
-
#location ~ \.php$ {
-
# proxy_pass http:
//127.0.0.1;
-
#}
-
-
# pass the PHP scripts to FastCGI server listening on
127.0.0.1:
9000
-
#
-
#location ~ \.php$ {
-
# root html;
-
# fastcgi_pass
127.0.0.1:
9000;
-
# fastcgi_index index.php;
-
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
-
# include fastcgi_params;
-
#}
-
-
# deny access to .htaccess files,
if Apache
's document root
-
# concurs with nginx's one
-
#
-
#location ~ /\.ht {
-
# deny all;
-
#}
-
}
我们通过访问localhost:80来访问指定的两个服务8070和8071两个服务
4.测试
1.同时开启8071和8071的服务时候 (修改权重容易看到区别)
2.假设8071服务不能访问了(8071Tomcat 关掉)则自动会去访问8070的服务
3.假设8070服务不能访问了(8070Tomcat 关掉)则自动会去访问8071的服务
4.两个服务都不能访问的时候(8071和8071都关掉)
这个错误是Nginx启动成功但是未找到服务!
===============================================
更新:Nginx反向代理导致ip错误的问题 程序里面getRequestUrl() 会变成localhost
解决:- Nginx 使用 proxy_pass 后在 Java 中 getRequestUrl() 的问题
localhost里面添加
proxy_set_header Host $host; proxy_set_header X-Real-Ip $remote_addr; proxy_set_header X-Forwarded-For $remote_addr;
如下