Nginx作为TCP负载均衡

时间:2023-03-09 09:22:57
Nginx作为TCP负载均衡

  参考文档:https://www.cnblogs.com/stimlee/p/6243055.html

  Nginx在1.9版本以后支持TCP负载均衡,模块默认是没有编译的,需要编译时添加—with-stream参数

编译过程不详细

查看编译参数包含--with-stream

Nginx作为TCP负载均衡

  修改nginx配置文件

配置文件如下

worker_processes  1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
stream {
upstream mysql {
server 172.16.20.180:3306;
}
server {
listen 3306;
proxy_pass mysql;
}
}

Nginx作为TCP负载均衡

  重启nginx测试 访问本机的3306端口可以访问到后端的真实MySQL及代表配置成功

同理可配置其他任何TCP端口

生产中可拆分成模块配置,配置同http包含include配置,在./conf.d目录下关于TCP负载均衡的配置文件需以这里自定义的tcpstream为后缀名

Nginx作为TCP负载均衡