Middleware / 运维笔记

Nginx 实现 UDP 反向代理

Einic Yeo · 5月21日 · 2019年 · ·

今天讲讲怎样实现UDP的反向代理,Nginx从1.9.13起开始发布ngx_stream_core_module模块不仅能支持TCP代版权声明:本文遵循 CC 4.0 BY-SA 版权协议,若要转载请务必附上原文出处链接及本声明,谢谢合作!理及负载均衡,其实也是支持UDP协议的。

安装Nginx并启用模块

ngx_stream_core_module这个模块并不会默认启用,需要在编译时通过指定--with-stream参数来激活版权声明:本文遵循 CC 4.0 BY-SA 版权协议,若要转载请务必附上原文出处链接及本声明,谢谢合作!这个模块。

  • 编译安装
$ yum -y install proc* openssl* pcre*
$ wget http://nginx.org/download/nginx-1.15.10.tar.gz
$ tar zxvf nginx-1.15.10.tar.gz
$ cd nginx-1.15.10
$ ./configure  --prefix=/usr/local/nginx --sbin-path=/usr/sbin/nginx --conf-path=/usr/local/nginx/conf/nginx.conf --error-log-path=/data/wwwlogs/nginx/error.log --http-log-path=/data/wwwlogs/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-http_ssl_module --with-http_realip_module --with-http_addition_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_stub_status_module --with-http_auth_request_module --with-threads --with-stream --with-stream_ssl_module --with-mail --with-mail_ssl_module --with-file-aio --with-ipv6 --with-http_spdy_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic'
$ make
$ make install
  • 配置stream模块

UDP负载均衡解决了两个关键点:高可用性和横向扩展。UDP设计是不保证端至端传送版权声明:本文遵循 CC 4.0 BY-SA 版权协议,若要转载请务必附上原文出处链接及本声明,谢谢合作!数据的,因此需要在客户端软件来处理网络级错误和重传机制。

实例:负载均衡DNS

stream模块必需在nginx.conf中配置

$ vim  /usr/local/nginx/conf/nginx.conf

worker_processes auto;
error_log /data/wwwlogs/nginx_error.log info;

events {
    worker_connections  1024;
}

stream {

upstream dns {
  server 192.168.0.1:53;
  server dns.example.com:53;
}

server {
  listen 127.0.0.1:53 udp;
  proxy_responses 1;
  proxy_timeout 20s;
  proxy_pass dns;
}

}

参考文档版权声明:本文遵循 CC 4.0 BY-SA 版权协议,若要转载请务必附上原文出处链接及本声明,谢谢合作!

http://nginx.org/en/版权声明:本文遵循 CC 4.0 BY-SA 版权协议,若要转载请务必附上原文出处链接及本声明,谢谢合作!docs/stream/ngx_stream_core_module.html

0 条回应