Nginx自1.9.0版本新增了stream模块,可以实现对四层TCP/UDP协议的转发、代理、负载均衡等,比如本文中的实例就有mysql、zookeeper和dns的代理或负载方法。
安装stream模块
如果是编译安装nginx,需要加上“--with-stream”参数,比如:
./configure --prefix=/opt/nginx --with-stream
顺便给一个比较全的编译安装命令:
./configure --prefix=/opt/nginx \ --pid-path=/var/run/nginx/nginx.pid \ --lock-path=/var/lock/nginx.lock \ --error-log-path=/var/log/nginx/error.log \ --http-log-path=/var/log/nginx/access.log \ --with-http_gzip_static_module \ --http-client-body-temp-path=/var/temp/nginx/client \ --http-proxy-temp-path=/var/temp/nginx/proxy \ --http-fastcgi-temp-path=/var/temp/nginx/fastcgi \ --http-uwsgi-temp-path=/var/temp/nginx/uwsgi \ --http-scgi-temp-path=/var/temp/nginx/scgi \ --with-ipv6 \ --with-stream \ --with-http_ssl_module
如果是yum安装nginx,可以独立安装stream模块:
yum -y install nginx-mod-stream
配置stream模块
stream { log_format proxy '$remote_addr [$time_local] ' '$protocol $status $bytes_sent $bytes_received ' '$session_time "$upstream_addr" ' '"$upstream_bytes_sent" "$upstream_bytes_received" "$upstream_connect_time"'; access_log /var/log/nginx/stream-access.log proxy; open_log_file_cache off; include /etc/nginx/conf.d/*.stream; }
以下是代理/负载mysql的实例:
upstream mysql { hash $remote_addr consistent; server 10.10.100.100:3306 max_fails=3 fail_timeout=30s; server 10.10.100.101:3306 weight=9; server 10.10.100.102:3306 weight=1; } server { listen 13306; proxy_connect_timeout 30s; proxy_timeout 1h; proxy_pass mysql; allow 10.10.200.0/24; deny all; }
以下是代理zookeeper的实例:
upstream zookeeper { server 10.10.100.200:2181 weight=5; } server { listen 12181 tcp; proxy_responses 1; proxy_timeout 15s; proxy_pass zookeeper; }
以下是DNS负载的实例(udp):
upstream dns { server 10.10.200.101:53; server 10.10.200.102:53; } server { listen 53 udp; proxy_responses 1; proxy_timeout 15s; proxy_bind $server_addr:$remote_port; proxy_pass dns; }
原创文章禁止转载:技术学堂 » Nginx优化全攻略之Stream模块