前言

nginx 在 1.9.0 的时候,增加了一个 stream 模块,用来实现四层协议(网络层和传输层)的转发、代理、负载均衡等。stream 模块的用法跟 http 的用法类似,允许我们配置一组 TCP 或者 UDP 等协议的监听,然后通过 proxy_pass 来转发我们的请求,通过 upstream 添加多个后端服务,实现负载均衡。

编译安装

nginx 默认是没有编译这个模块的,要使用 stream 模块,编译的时候记得加上–with-stream 这个参数即可。

./configure --prefix=/usr/local/nginx --user=www --group=www --with-http_ssl_module --with-http_v2_module --with-http_gzip_static_module --with-http_stub_status_module  --with-stream

make

make install

检查是否已经带有 stream 模块

/usr/local/nginx/sbin/nginx  -V
nginx version: nginx/1.12.2
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-16) (GCC)
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments:   --prefix=/usr/local/nginx --user=www --group=www --with-http_ssl_module --with-http_v2_module --with-http_gzip_static_module --with-http_stub_status_module  --with-stream

简单配置

在 nginx.conf 默认配置文件里面,默认没有 stream 的配置。stream 模块的配置跟 http 配置是同级的,因此要注意不要写到 http 里面。

user www;
worker_processes auto;
error_log /data/log/nginx/error.log;
pid /run/nginx.pid;
events {
    worker_connections 1024;
}
# 这里是http模块的相关配置
http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    access_log  /data/log/nginx/access.log  main;
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;
    include             /usr/local/nginx/etc/mime.types;
    default_type        application/octet-stream;
    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /data/www/html;

error_page 404 /404.html;
            location = /40x.html {
        }
        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }
}
#这里开始才是stream模块的配置
stream {
    upstream tcp_server {
        server  192.168.1.10:8888;
        server  192.168.1.11:8888;
        }
     upstream  udp_server{
        server 192.168.1.10:8877;
        server 192.168.1.11:8877;
        }
    server {
            listen 10133;
            proxy_pass tcp_server;
        }
    server {
            listen 10123 udp;
            proxy_pass  udp_server;
        }
}

配置完可以使用/usr/local/nginx/sbin/nginx -t 进行测试。

总结

以前做四层协议负载均衡的时候,一般都会用到 lvs、HAproxy、F5 等,但是要么很贵,要么配置麻烦,而 nginx 配置简单,能快速完成工作。