nginx在版本1.9.0以后支持tcp的负载均衡,具体可以参照官网关于模块ngx_stream_core_module的说明。一直以来,Nginx 并不支持tcp协议,所以后台的一些基于TCP的业务就只能通过其他高可用负载软件来完成了,比如Haproxy或者LVS。
编译Nginx启用ngx_stream_core_module模块
ngx_stream_core_module 这个模块在1.90版本后将被启用。但是并不会默认安装,需要在编译时通过指定 –with-stream 参数来激活这个模块。
# cd /usr/local/
# wget https://nginx.org/download/nginx-1.12.2.tar.gz
# tar zxf nginx-1.12.2.tar.gz
# cd nginx-1.12.2/
# ./configure --prefix=/usr/local/nginx --with-stream
# make && make install
配置Nginx负载均衡MySQL
# cd /usr/local/nginx/conf/
# vim nginx.conf
#user nobody;
worker_processes 1;
error_log logs/error.log debug;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
stream {
upstream mysql {
server 172.16.206.30:3306;
}
server {
listen 3306;
proxy_connect_timeout 8s;
proxy_timeout 24h;
proxy_pass mysql;
}
}
http {
include 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 logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
gzip on;
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/access.log main;
location / {
root html;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
stream与http同级别。