使用nginx实现TCP代理

nginx从1.9.0开始发布ngx_stream_core_module模块,该模块支持tcp代理及负载均衡

查看安装的模块

包含--with-stream即有此模块

nginx -V |grep stream
.......
 --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module
......

注意:yum安装的nginx默认就有此模块,如果你的nginx是编译安装的默认是不开启此模块的。需要在编译时通过指定--with-stream参数来启用这个模块

配置stream模块

stream模块必须在nginx.conf中配置

stream {
    upstream mysql {
       server 172.16.77.162:3306;
    }
    server {
        listen 3307;
        proxy_connect_timeout 30s;
        proxy_timeout 10m;
        proxy_pass mysql;
    }
}

测试

  • 检查配置及重启
$ nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
$ nginx -s reload
  • 连接测试
  • 官网比较完整的示例
worker_processes auto;

error_log /var/log/nginx/error.log info;

events {
    worker_connections  1024;
}

stream {
    upstream backend {
        hash $remote_addr consistent;

        server backend1.example.com:12345 weight=5;
        server 127.0.0.1:12345            max_fails=3 fail_timeout=30s;
        server unix:/tmp/backend3;
    }

    upstream dns {
       server 192.168.0.1:53535;
       server dns.example.com:53;
    }

    server {
        listen 12345;
        proxy_connect_timeout 1s;
        proxy_timeout 3s;
        proxy_pass backend;
    }

    server {
        listen 127.0.0.1:53 udp reuseport;
        proxy_timeout 20s;
        proxy_pass dns;
    }

    server {
        listen [::1]:12345;
        proxy_pass unix:/tmp/stream.socket;
    }
}

参考链接

官方文档

你可能感兴趣的:(使用nginx实现TCP代理)