Nginx的Stream模块支持TCP和UDP转发
nginx从1.9.0版本开始,新增了ngx_stream_core_module模块,使nginx支持四层负载均衡。默认编译的时候该模块并未编译进去,需要编译的时候添加--with-stream,使其支持stream代理。
Nginx编译命令
如果只需要支持TCP和UDP,那么可以直接最精简
./configure --prefix= --with-stream --without-http
Nginx配置
官方示例
stream {
upstream backend {
hash $remote_addr consistent;
server backend1.example.com:12345 weight=5;
server 127.0.0.1:12345 max_fails=3 fail_timeout=30s;
server unix:/tmp/backend3;
}
upstream dns {
server 192.168.0.1:53535;
server dns.example.com:53;
}
server {
listen 12345;
proxy_connect_timeout 1s;
proxy_timeout 3s;
proxy_pass backend;
}
server {
listen 127.0.0.1:53 udp reuseport;
proxy_timeout 20s;
proxy_pass dns;
}
server {
listen [::1]:12345;
proxy_pass unix:/tmp/stream.socket;
}
}
zk负载
stream {
upstream zk_server {
server 172.16.3.8:2181 weight=5;
}
server {
listen 2181 tcp;
proxy_responses 1;
proxy_timeout 20s;
proxy_pass zk_server;
}
}
Mysql负载
user nobody;
worker_processes auto;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
use epoll;
worker_connections 1024;
}
stream {
server {
listen 3000;
proxy_pass 127.0.0.1:3306;
# support unix socket
# proxy_pass unix:/var/lib/mysql/mysql.socket;
}
}
UDP负载
issues:
- https://stackoverflow.com/questions/36880862/nginx-error-worker-connections-are-not-enough
- https://www.jianshu.com/p/244386221cc5
- http://nginx.org/en/docs/stream/ngx_stream_proxy_module.html#proxy_responses
DNS负载
user nobody;
worker_processes auto;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
use epoll;
worker_connections 1024;
}
stream {
server {
listen 53 udp;
proxy_pass 127.0.0.1:53;
}
}
网友评论