Nginx 原生僅支援 HTTP(七層),不支援 TCP 代理。需引入第三方模塊 `nginx_tcp_proxy_module` 實現 MySQL(3306 端口)負載均衡。
wget https://nginx.org/download/nginx-1.2.1.tar.gz
tar -xzvf nginx-1.2.1.tar.gz
cd nginx-1.2.1/
patch -p1 < /path/to/nginx_tcp_proxy_module/tcp.patch
./configure --add-module=/usr/local/ngx_cache_purge-1.4 \
--prefix=/usr/local/nginx --with-http_stub_status_module \
--add-module=/path/to/nginx_tcp_proxy_module
http {
server {
listen 80;
location /status {
check_status; # 狀態頁
}
}
}
tcp {
upstream mysql {
server 10.10.10.17:3306 weight=1;
server 10.10.10.18:3306 weight=1;
# check interval=3000 rise=2 fall=5 timeout=1000; # 健康檢查
}
server {
listen 3306;
proxy_pass mysql;
}
}
2012/09/07 18:22:32 [3921] 10.10.10.107 0.0.0.0:3306 2012/09/07 18:22:31 10.10.10.18:3306 1446 4383
2012/09/07 18:22:32 [3921] 10.10.10.107 0.0.0.0:3306 2012/09/07 18:22:32 10.10.10.17:3306 1446 4383
...
日誌顯示請求按權重輪詢分發至兩台 MySQL 後端,負載均衡生效。