Nginx做TCP/UDP代理
nginx相关网址
官网:https://www.nginx.com/ 文档:https://docs.nginx.com/ 开源文档:https://nginx.org/en/docs/ TCP和UDP负载均衡说明:https://docs.nginx.com/nginx/admin-guide/load-balancer/tcp-udp-load-balancer/ TCP健康检测:https://docs.nginx.com/nginx/admin-guide/load-balancer/tcp-health-check// UDP健康检测:https://docs.nginx.com/nginx/admin-guide/load-balancer/udp-health-check/ ngx_stream_proxy_module模块文档:https://nginx.org/en/docs/stream/ngx_stream_proxy_module.html ngx_stream_upstream_module模块文档:https://nginx.org/en/docs/stream/ngx_stream_upstream_module.html ngx_stream_upstream_hc_module模块文档:https://nginx.org/en/docs/stream/ngx_stream_upstream_hc_module.html
官方示例分析
stream {
upstream stream_backend {
least_conn;
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监听本地12345端口的TCP数据包,反向代理给stream_backend组,最小连接数方式进行负载均衡。 nginx监听本地53端口的UDP数据包,反向代理给dns_servers组,最小连接数方式进行负载均衡。 nginx监听本地12346端口的TCP数据包,直接反向代理给backend4.example.com:12346
mysql代理示例
./nginx.conf
...
stream {
proxy_connect_timeout 3s;
include stream/*conf;
}
...
./stream/mysql.conf
upstream mysql {
server 192.168.1.100:3306;
}
server {
listen 3306;
proxy_connect_timeout 3s;
proxy_timeout 3s;
proxy_pass mysql;
}
ssh 代理示例
./nginx.conf
...
stream {
proxy_connect_timeout 3s;
include stream/*conf;
}
...
./stream/ssh.conf
upstream ssh {
server 0.0.0.0:22;
}
server {
listen 22122;
proxy_pass ssh;
}
|