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.
-
Create a top‑level
stream {}
block: -
Define one or more
server {}
configuration blocks for each virtual server in the top‑levelstream
{}
context. -
Within the
server{}
configuration block for each server, include thelisten
directive to define the IP address and/or port on which the server listens.(默认 tcp,如果是 udp 还需手动加上) -
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;
}
}
- 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‑levelstream {}
context and set the name for the upstream group. - 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 theserver
block, which you have created earlier. - 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
- 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;
}
}