nginx tcp 反向代理 mongodb mysql redis

MongoDB、MySQL、Redis 都应使用 TCP 连接配置,而不是在 HTTP 块中。

Configuring Reverse Proxy

To forward TCP connections or UDP datagrams from clients to an upstream group or a proxied server.

  1. Create a top‑level stream {} block:

  2. Define one or more server {} configuration blocks for each virtual server in the top‑level stream {} context.

  3. Within the server{} configuration block for each server, include the listen directive to define the IP address and/or port on which the server listens.(默认 tcp,如果是 udp 还需手动加上)

  4. Include proxy_pass directive to define the proxied server or an upstream group to which the server forwards traffic

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
stream {

    server {
        listen     12345;
        #TCP traffic will be forwarded to the "stream_backend" upstream group
        proxy_pass stream_backend;
    		proxy_buffer_size 16k;
    }

    server {
        listen     12346;
        #TCP traffic will be forwarded to the specified server
        proxy_pass backend.example.com:12346;
    }

    server {
        listen     53 udp;
        #UDP traffic will be forwarded to the "dns_servers" upstream group
        proxy_pass dns_servers;
    }
    # ...
}

Configuring TCP or UDP Load Balancing

  1. Create a group of servers, or an upstream group whose traffic will be load balanced. Define one or more upstream {} configuration blocks in the top‑level stream {} context and set the name for the upstream group.
  2. Note that you do not define the protocol for each server, because that is defined for the entire upstream group by the parameter you include on the listen directive in the server block, which you have created earlier.
  3. Configure the load‑balancing method used by the upstream group.
    • Round Robin – By default
    • Least Connections
    • Least Time (Nginx Plus only)
    • Hash:can configure session persistence
    • Random
  4. Optionally, for each upstream server specify server‑specific parameters.

Sample

 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
stream {
    upstream stream_backend {
        hash   $remote_addr consistent;
        server backend1.example.com:12345 weight=5;
        server backend2.example.com:12345 max_fails=2 fail_timeout=30s;
        server backend3.example.com:12345 max_conns=3;
    }
    
    upstream dns_servers {
        least_conn;
        server 192.168.136.130:53;
        server 192.168.136.131:53;
        server 192.168.136.132:53;
    }
    
    server {
        listen        12345;
        proxy_pass    stream_backend;
        proxy_timeout 3s;
        proxy_connect_timeout 1s;
    }
    
    server {
        listen     53 udp;
        proxy_pass dns_servers;
    }
    
    server {
        listen     12346;
        proxy_pass backend4.example.com:12346;
    }
}

Nginx 官方:TCP and UDP Load Balancing

updatedupdated2020-07-122020-07-12
加载评论