nginx转发tcp

配置nginx的tcp代理

请注意,stream块和http块是两个不同的模块,stream不属于http模块,即不能放到/etc/nginx/conf.d/,stream是通过tcp层转发,而不是http转发。

修改主配置文件,添加stream目录

[root@node1 ~]# cd /etc/nginx/
[root@node1 ~]# cp -a nginx.conf{,_$(date +%F)}
[root@node1 ~]# vim nginx.conf
# 最后追加如下内容
# tcp/ip proxy
include /etc/nginx/tcp.d/*.conf;

添加tcp转发配置

[root@node1 ~]# mkdir tcp.d
[root@node1 ~]# cd tcp.d

在新建的 tcp.d 目录下创建 conf 文件新建一个 tcp 配置,例如我转发到IP为8.8.8.8的389端口

[root@node1 ~]# vim openldap.conf
stream{
    upstream tcpssh{
        hash $remote_addr consistent;
        server  8.8.8.8:389 max_fails=3 fail_timeout=10s;  
    }
    server{
        listen 3389;
        proxy_connect_timeout 20s;
        proxy_timeout 5m;
        proxy_pass tcpssh;
    }
}

说明: “upstream tcpssh”:转发的目的地址和端口等设置;其中tcpssh为自定义; “server”:提供转发的服务,即访问localhost:3389,会跳转至代理“tcpssh”指定的转发地址.。 这里就是配置的监听本地3389端口,会将流量相应转发到8.8.8.8服务器的389端口上。

测试配置文件是否正确

[root@node1 ~]# nginx -t -c /etc/nginx/nginx.conf
[root@node1 ~]# nginx -t -c /etc/nginx/tcp.d/openldap.conf

启动nginx服务

[root@node1 ~]# systemctl start nginx.service
[root@node1 ~]# systemctl status nginx.service

评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注