Nginx实现TCP端口的侦听及转发

一、说明

由于我们在使用mqtt时,会接收大量的客户端连接,单机的mqtt肯定是扛不住的,所以需要一个mqtt的集群来处理,这时就得有一个网关来负责请求的转发

nginx从1.9.0版本开始,新增了ngx_stream_core_module模块,使nginx支持四层代理和负载均衡。 默认编译时该模块未编译进去,需要编译时添加 --with-stream,--with-stream_ssl_module,使其支持stream代理

在之前的版本如果想支持,需要打补丁,安装模块nginx_tcp_proxy_module。 http代理,通常就是我们说的七层代理,工作在第七层应用层。 而tcp代理,就是我们常说的四层代理,工作在网络层和传输层

http代理,通常就是我们说的七层代理,工作在第七层应用层
而tcp代理,就是我们常说的四层代理,工作在网络层和传输层

需要用到的命令

命令说明
firewall-cmd --list-ports  

查看开放的端口号 

firewall-cmd --zone=public --add-port=8888/tcp --permanent开放对应端口号:8888
firewall-cmd --zone=public --remove-port=80/tcp --permanent关闭端口号
firewall-cmd --reload 重启防火墙 
 systemctl status firewalld.service 查看防火墙状态

二、操作步骤

2.1 查看nginx是否安装stream

nginx -V | tr ' ' '\n'|grep stream

如果出现下面两项,说明支持

--with-stream
--with-stream_ssl_module

2.2 如果没有则重新安装nginx

1. sudo yum install nginx -y
2. sudo yum -y install epel-release
3. yum -y install nginx-all-modules.noarch
4. vi nginx.conf   #顶部加一行load_module /usr/lib64/nginx/modules/ngx_stream_module.so;

2.3 tcp代理(mqtt为例)

  1. tcp代理与我们平常说的网站反向代理不一样,它是基于tcp协议
  2. stream反向代理模块与http和events是平级的,不要把配置写到http里面了

为了方便添加stream配置,我们单独在nginx目录下创建一个stream目录,存放tcp代理配置文件

/etc/nginx/nginx.conf 中加入如下:

stream {

log_format proxy '$remote_addr [$time_local] '

'$protocol $status $bytes_sent $bytes_received '

'$session_time "$upstream_addr" '

'"$upstream_bytes_sent" "$upstream_bytes_received" "$upstream_connect_time"';

access_log  /var/log/nginx/stream.log proxy;

open_log_file_cache off;

include stream/*conf;

}

在nginx/stream下创建一个mqtt.conf配置文件

upstream mqtt_tcp_server{
    server ec2-52-90-93-84.compute-1.amazonaws.com:8883;
} 
server {
listen 8883; #监听端口
proxy_connect_timeout 150s;
proxy_timeout 150s;
proxy_pass mqtt_tcp_server; #反向代理地址
proxy_buffer_size 3M;
tcp_nodelay on;
}

重载nginx

/usr/local/nginx/sbin/nginx -s reload

当我们访问nginx的8883端口时,会自动代理到目标主机的8883端口上

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值