Nginx TCP代理

nginx 在1.9.0 版本发布以前如果要想做到基于TCP的代理及负载均衡需要通过打名为nginx_tcp_proxy_module的第三方patch来实现,该模块的代码托管在github上 网址:https://github.com/yaoweibin/nginx_tcp_proxy_module/,而我们今年要来简单测试一下nginx 的ngx_stream_core_module,该模块有nginx 官方发布并支持tcp代理及负载均衡。

 

ngx_stream_core_module 这个模块在1.90版本后将被启用。但是并不会默认安装,需要在编译时通过指定 --with-stream 参数来激活这个模块。

其他改进包括:

  • Change: 删除过时的 aio 和 rtsig 事件处理方法
  • Feature: 可在 upstream 块中使用 "zone" 指令
  • Feature: 流模块,支持 TCP 代理和负载均衡
  • Feature: ngx_http_memcached_module 支持字节范围
  • Feature: Windows 版本支持使用共享内存,带随机化地址空间布局.
  • Feature: "error_log" 指令可在 mail 和 server 级别
  • Bugfix: the "proxy_protocol" parameter of the "listen" directive did not work if not specified in the first "listen" directive for a listen socket.

简单配置步骤如下(测试MYSQL负载):

wget http://nginx.org/download/nginx-1.9.3.tar.gz
tar zxvf nginx-1.9.3.tar.gz
cd nginx-1.9.3yum -y install proc*
yum -y install openssl*
yum -y install pcre*

./configure --prefix=/usr/local/nginx-1.9.3_tcp \
--with-http_ssl_module --with-http_spdy_module \
--with-http_stub_status_module --with-pcre \
--with-stream

cd /usr/local/nginx-1.9.3_tcp/conf/
mv nginx.conf{,.bak}
vim nginx.conf


worker_processes auto;
events {
    worker_connections  1024;
}
error_log /var/log/nginx_error.log info;
stream {
    upstream mysqld {
        hash $remote_addr consistent;
        server 192.168.1.42:3306 weight=5 max_fails=1 fail_timeout=10s;
        server 192.168.1.43:3306 weight=5 max_fails=1 fail_timeout=10s;
    }
 
    server {
        listen 3306;
        proxy_connect_timeout 1s;
        proxy_timeout 3s;
        proxy_pass mysqld;
    }
 
}

另外还可以实现一个ssh 转发代理

upstream ssh {
        hash $remote_addr consistent;
        server 192.168.1.42:22 weight=5;
   } 
 
server {
    listen 2222;
    proxy_pass ssh;    
   }  

 

参考:

http://zhangge.net/5037.html

http://nginx.org/en/docs/stream/ngx_stream_core_module.html

posted @ 2015-07-22 13:52  艾阳君  阅读(3593)  评论(0编辑  收藏  举报