使用Nginx转发TCP/UDP端口

Posted by Sunday on 2018-10-24

ngx_stream_core_module

编译Nginx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
cd /usr/local/src
wget http://nginx.org/download/nginx-1.12.2.tar.gz
tar zxf nginx-1.12.2.tar.gz
cd nginx-1.12.2
./configure --prefix=/usr/local/nginx --with-stream

--prefix=/usr/local/webserver/nginx --with-file-aio --with-poll_module \
--with-http_realip_module --with-http_image_filter_module \
--with-http_gzip_static_module --with-http_addition_module --with-http_sub_module \
--with-http_dav_module --with-http_flv_module --with-http_slice_module \
--with-http_mp4_module --with-http_random_index_module \
--with-http_secure_link_module --with-http_degradation_module --with-http_ssl_module \
--with-http_stub_status_module --with-http_v2_module \
--with-ld-opt=/usr/local/jemalloc/lib/libjemalloc.so.2 --with-stream
make && make install

nginx.conf

注:steam只能在nginx.conf中配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
worker_processes auto;

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

events {
worker_connections 1024;
}

http{
...
}
stream {
upstream mysql {
hash $remote_addr consistent;
server 192.168.1.41:6379 weight=5 max_fails=3 fail_timeout=30s;
server server unix:/tmp/mysql.sock
}

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

server {
listen 33061;
#listen 63795 so_keepalive=on;
#listen 63795 so_keepalive=30m::10;
proxy_connect_timeout 1s;
proxy_timeout 3s;
proxy_pass mysql;
}

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;
}
}

长连接说明

开启长连接,并且使用内核参数

1
2
3
4
5
6
listen 12345 so_keepalive=on;

# sysctl -p | grep tcp_keepalive
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_keepalive_probes = 5
net.ipv4.tcp_keepalive_intvl = 15

开启长连接,指定超时时间

1
2
#将空闲超时设置为30分钟.将探测间隔保留为系统默认值,并将探测计数设置为10个探测器。
listen 12345 so_keepalive=30m::10;