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

成功:

相关推荐
为自己_带盐5 分钟前
记一次“丝滑”的服务器迁移
运维·服务器
ん贤7 分钟前
io.copy
运维·服务器·网络·io.copy
默|笙7 分钟前
【Linux】进程控制(2)进程等待
linux·运维·服务器
QT 小鲜肉9 小时前
【Linux命令大全】001.文件管理之git命令(实操篇)
linux·服务器·笔记·git·elasticsearch
全栈陈序员10 小时前
理解 Git 的第一步:什么是版本控制系统?
git
曹牧11 小时前
C#:记录日志
服务器·前端·c#
我的offer在哪里12 小时前
git操作遇到的问题
git
运维行者_12 小时前
OPM 与传统管理工具的区别,在网络修复与自动化运维方面的优势在哪里?
运维·服务器·开发语言·网络·自动化·php·ssl
realhuizhu13 小时前
你的Git提交记录是“代码史诗”,还是“只有上帝能看懂的天书”?
git·版本控制·团队协作·ai工具·提示词工程
TG:@yunlaoda360 云老大14 小时前
华为云国际站代理商NAT的规格有哪些?
服务器·网络·华为云