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

成功:

相关推荐
小Lu的开源日常2 小时前
如何将 GitHub 仓库从个人账户转移到组织账户
git·开源·github
源梦想2 小时前
火柴人龙拳网页格斗小游戏Linux部署演示
linux·运维·服务器
芒克芒克2 小时前
《Git 入门:从概念到环境准备》
git
我就是程序猿2 小时前
Git的操作
git
洒家肉山大魔王2 小时前
Git && IDE 对长路径支持不足 导致 文件被“误判”不存在
git·idea
BD_Marathon2 小时前
【Zookeeper】搭建Zookeeper服务器
linux·服务器·zookeeper
星尘库2 小时前
怎么实现js混淆加密 每隔一段时间 会失效 需要重新加密使用
java·服务器·前端
q***87602 小时前
Nginx之rewrite重写功能
数据库·mysql·nginx
摇滚侠2 小时前
零基础小白自学Git_Github教程,Git 与 GitHub 的历史起源,笔记05
笔记·git·github
庚昀◟2 小时前
Wsl系统下使用Ubuntu下载官网Nginx并加入系统服务
linux·nginx·ubuntu