目录

nginx 反向代理 mongodb mysql redis

目录

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

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

stream {

    server {
        listen     12345;
        proxy_pass stream_backend;
    		proxy_buffer_size 16k;
    }

    server {
        listen     12346;
        proxy_pass backend.example.com:12346;
    }

    server {
        listen     53 udp;
        proxy_pass dns_servers;
    }
}
  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.
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