nginx作为tcp负载均衡
这两天考虑mysql的集群,考虑负载均衡,了解nginx在版本1.9.0以后支持tcp的负载均衡,具体可以参照官网关于模块ngx_stream_core_module的叙述
nginx从1.9.0后引入模块ngx_stream_core_module,模块是没有编译的,需要用到编译需添加--with-stream配置参数,stream负载均衡官方配置样例
worker_processes auto; error_log /var/log/nginx/error.log info; events { worker_connections 1024; } 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; proxy_responses 1; proxy_timeout 20s; proxy_pass dns; } server { listen [::1]:12345; proxy_pass unix:/tmp/stream.socket; } }
参照此配置文件修改自定义配置文件
user nginx; #user root; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; } stream{ upstream mysql{ server 192.168.1.106:3306 weight=1; server 192.168.1.108:3306 weight=1; } server{ listen 3307; proxy_pass mysql; } }
stream与http同级别,上文为main