文章

nginx_stream模块

通常在yum安装nginx时,默认不会加载stream模块

1
2
3
4
需要同时安装 nginx-mod-stream 模块
yum install nginx nginx-mod-stream

ngx_stream_proxy_module

使用方法

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
1. 直接 代理端口的 stream, 需要使用流模式: stream(非 http内部加载)
stream {
    log_format proxy '$remote_addr \t[$time_local] '
                     '$protocol $status [$bytes_sent $bytes_received]'
                     '\t$session_time\t$upstream_addr '
                     '[$upstream_bytes_sent $upstream_bytes_received]\t$upstream_connect_time ';
                     
    include /etc/nginx/tcp/*.conf;
}

vim  /etc/nginx/tcp/tcp-stream.conf
server {
    listen 127.0.0.1:12345;
    proxy_pass 127.0.0.1:8080;
}

server {
    listen 12345;
    proxy_connect_timeout 1s;
    proxy_timeout 1m;
    proxy_pass example.com:12345;
}

server {
    listen 53 udp;
    proxy_responses 1;
    proxy_timeout 20s;
    proxy_pass dns.example.com:53;
}

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

例子

1. 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
user  root;
worker_processes  2;

events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

}

stream {
    log_format proxy '$remote_addr \t[$time_local] '
                     '$protocol $status [$bytes_sent $bytes_received]'
                     '\t$session_time\t$upstream_addr '
                     '[$upstream_bytes_sent $upstream_bytes_received]\t$upstream_connect_time ';
    #access_log logs/proxy/tcp.access.log proxy;
    #error_log logs/proxy/tcp.error.log;
    include tcp/*.conf;
}

2. tcp/proxy.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
upstream proxy-stable {
    #server    127.0.0.1:40026 weight=1 fail_timeout=30s max_fails=3;
    #server  172.20.1.85:40026    weight=1 fail_timeout=30s max_fails=3;
    server  172.16.0.127:40021    weight=1 fail_timeout=30s max_fails=3;
    server  172.16.0.127:40022    weight=1 fail_timeout=30s max_fails=3;
    server  172.16.0.127:40023    weight=1 fail_timeout=30s max_fails=3;
    #server  121.43.181.163:40010 weight=1 fail_timeout=30s max_fails=3;
    #check interval=3000 rise=2 fall=5 timeout=5000 type=tcp;
}

server {
    listen 40025;
    proxy_pass proxy-stable;
    access_log logs/proxy/proxy-stable.access.log proxy;
    error_log  logs/proxy/proxy-stable.error.log;
}
本文由作者按照 CC BY 4.0 进行授权