相关推荐recommended
Nginx的stream配置
作者:mmseoamin日期:2024-02-04

一、stream模块概要

stream模块一般用于tcp/UDP数据流的代理和负载均衡,可以通过stream模块代理转发TCP消息。 ngx_stream_core_module模块由1.9.0版提供。 默认情况下,没有构建此模块,必须使用-with stream配置参数启用。 也就是说,必须在使用./configure --with-stream编译时添加流模块。 流模块的使用方法与http模块相同,语法也基本相同。

二、使用场景说明

stream主要有两个可用场景:

  • 一是实现流量的代理转发。 这里所述的代理转发是指,只有一些端口服务被限制为活动IP地址。 例如,mysql账户一般将源地址限制为APP应用服务器,而nginx可能同时是web APP应用服务器。 开发人员需要验证一些数据库数据问题,但帐户的源地址有限制。 此时,通过在nginx中进行流传送,可以实现从开发终端向mysql的访问。
  • 二是实现流量负载均衡。 有多个tcp或udp端口服务,如DNS。 流模块支持负载平衡算法,如轮询、最小连接数和ip_hash,从而实现数据流负载平衡。

    三、配置实例

    开启stream

    修改/etc/nginx/nginx.conf

    #增加stream配置,开启stream模块
    http{
    xxxxxxxxxx
           }
    #stream模块和http模块是并列级别的,所以stream要写在http{}外边
    stream {
        log_format basic '$remote_addr [$time_local] '
                     '$protocol $status $bytes_sent $bytes_received '
                     '$session_time';
        access_log /var/log/nginx/stream-access.log basic buffer=32k;
        # 为了让这个配置文件简单一些,将配置stream放入到/etc/nginx/conf.d,并以.stream做后缀名。
        # 需要为每个端口创建一个.stream做后缀名的配置文件
        include /etc/nginx/conf.d/*.stream;
    }
    
    stream {
            upstream back{
                    server 192.168.208.1:3000;
            }
            server {
                    listen 2000 udp;
                    proxy_connect_timeout 5s;
                    proxy_timeout 300s;
                    proxy_pass back;
            }
    }