Nginx实现端口转发与负载均衡配置

前言:当我们的软件体系结构较为庞大的时候,访问量往往是巨大的,所以我们这里可以使用nginx的均衡负载

一、配置nginx实现端口转发

本地tomcat服务端口为8082

本地nginx端口为8080

目的:将nginx的8080转发到tomcat的8082端口上进行访问

1、首先更改nginx.conf配置文件

复制代码
 server {
        listen       8080;#8080为nginx端口
        server_name  localhost;
 
location /p/ {
            proxy_pass   http://localhost:8082/;#8082为tomcat端口
           #   proxy_pass   http://xx/;
       }
}
#将url中/p/路径的url转发到tomcat的8082端口上

测试,在nginx的html文件下新建一个1.html

1.html

复制代码
<html>
<script>
function myload(){
	var path="/p/pic/p1.jpg?i="+Math.random();
	myimg.src=path;
}
</script>
<body onload="myload()">
<img id="myimg" src="">

</body>
</html>

访问nginx:localhost:8080/1.html

二、配置负载均衡

1、首先启动两个tomcat或nginx

我这里启动两个tomcat,先更改tomcat端口号。

我这里tomcat端口分别为:8082、8083

更改配置文件如下:conf\server.xml

复制代码
   <Connector port="8082" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8082" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
<Server port="8005" shutdown="SHUTDOWN">

注:<Server port="8005" shutdown="SHUTDOWN">这个也要改,不能跟另外一个tomcat的shutdown这个端口冲突。

分别在两个tomcat的webapp\pic目录命名同名的一张图片p1.jpg,但图片内容不同

2、更改nginx.conf配置文件

复制代码
http{
    include       mime.types;
    default_type  application/octet-stream;
   sendfile        on;
#负载均衡配置
upstream xx {
       server 127.0.0.1:8082;
       server 127.0.0.1:8083;
    } 
server {
        listen       8080;#8080为nginx端口
        server_name  localhost;
 
location /p/ {
            #proxy_pass   http://localhost:8082/;#8082为tomcat端口
              proxy_pass   http://xx/;
       }
}
}
#将url中/p/路径的url转发到tomcat的8082或8083端口上

重启nginx:

复制代码
nginx -s quit #关闭
nginx -s stop #强制关闭
start nginx #启动

成功:

相关推荐
嘻嘻仙人3 天前
Ubuntu中 git上传自己的项目和二次上传一般流程
git·github
Patrick_Wilson3 天前
Squash Merge 的血缘陷阱:为什么删掉的代码又活了过来
前端·git·程序员
沉浸学习的匿名网友3 天前
什么是 .gitignore?为什么每个 Git 项目几乎都离不开它?
前端·git
深海鱼在掘金4 天前
Git 完全指南 —— 第3章:理解工作区、暂存区、版本库三个核心
git
江华森4 天前
Git 基础筑基:从原理到团队协作的全栈实战
git
JakeJiang5 天前
Git 必备命令指南:从日常高频到项目开发实战
git
Avan_菜菜5 天前
FRP 内网穿透完整实战:从 HTTP 映射到 HTTPS 自签代理
运维·nginx·https
叫我少年6 天前
Windows 中安装 git
git
zzzzzz3108 天前
9K Star 炸裂开源!这个 C 语言写的代码知识图谱,把 Linux 内核索引压缩到了 3 分钟
linux·服务器·sql
ping某9 天前
为什么 Nginx 明明监听了 80,转发后端时却用了 4xxxx 端口?
后端·nginx