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

成功:

相关推荐
鹧鸪yy1 分钟前
认识Node.js及其与 Nginx 前端项目区别
前端·nginx·node.js
爱喝矿泉水的猛男1 小时前
Git Commit 提交信息标准格式
git·commit
℘团子এ1 小时前
git中,将新项目推送到新建的远程仓库
git
gitboyzcf1 小时前
Git 常用命令
前端·git·后端
Gss7771 小时前
源代码编译安装lamp
linux·运维·服务器
哈里谢顿2 小时前
Git 最实用的四个还原命令详解
git
敲上瘾2 小时前
Linux I/O 多路复用实战:Select/Poll 编程指南
linux·服务器·c语言·c++·select·tcp·poll
__lll_2 小时前
Nginx proxy_pass 404/502 根源:漏写末尾斜杠 / 的修复指南
nginx
huangyuchi.2 小时前
【Linux系统】匿名管道以及进程池的简单实现
linux·运维·服务器·c++·管道·匿名管道·进程池简单实现
元清加油3 小时前
【Goland】:协程和通道
服务器·开发语言·后端·网络协议·golang