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 #启动

成功:

相关推荐
nangonghen10 分钟前
Nginx stream模块是连接级别的负载均衡
nginx·负载均衡
YJQ996710 分钟前
Nginx与Tomcat负载均衡集群配置指南
nginx·tomcat·负载均衡
熬夜苦读学习39 分钟前
Linux线程控制
linux·运维·服务器·开发语言·后端
愚润求学1 小时前
【Linux】动静态库的使用
linux·运维·服务器·开发语言·c++·笔记
三天不学习1 小时前
Vue3 本地环境 Vite 与生产环境 Nginx 反向代理配置方法汇总【反向代理篇】
运维·nginx·vue3·vite·反向代理
2401_831501732 小时前
Linux之Yum源与Nginx服务篇
linux·运维·nginx
sz66cm3 小时前
Linux基础 -- 在内存中使用chroot修复eMMC
linux·服务器
Hi202402173 小时前
如何通过partclone克隆Ubuntu 22系统
运维·服务器·ubuntu
神仙别闹4 小时前
基于C#实现中央定位服务器的 P2P 网络聊天系统
服务器·网络·c#
Li_yizYa4 小时前
网络原理 | 网络基础概念复习
运维·服务器·网络·计算机网络