nginx以upstream分组的方式实现tcp反向代理

nginx在1.9版本开始支持tcp模式的负载均衡,在1.9.13版本开始支持udp协议的负载均衡,udp主要用于DNS的域名解析,其配置方式和指令和http代理类似,其基于ngx_steam_proxy_module模块实现tcp负载,另外基于ngx_stream_upstream_module实现后端服务器的分组转发、权重分配、状态监测、调度算法等高级功能 官方文档的example:

worker_processes auto;
error_log /var/log/nginx/error.log info;
events {
    worker_connections  1024;
}
stream {        #定义stream
    upstream backend {      #定义后端服务器
        hash $remote_addr consistent;   #定义调度算法

        server backend1.example.com:12345 weight=5;     #定义具体的server信息
        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 reuseport;
        proxy_timeout 20s;
        proxy_pass dns;
    }
    server {
        listen [::1]:12345;
        proxy_pass unix:/tmp/stream.socket;
    }
}

upstream分组实现tcp反向代理

server IP
nginx 172.20.27.10
mysql 172.20.27.20
client 172.20.27.100

反向代理端操作

1.在nginx服务器上定义stream

[root@nginx ~]# vim /apps/nginx/conf/tcp/tcp_proxy.conf 
stream {    #定义stream
    upstream mysql_host {   #定义后端服务器
        server 172.20.27.20:3306;
  }
    server {
        listen 172.20.27.10:3306;
        proxy_connect_timeout 5s;
        proxy_timeout 5s;
        proxy_pass mysql_host
  }
}

2.在著配置文件中导入tcp_proxy.conf配置

[root@nginx ~]# vim /apps/nginx/conf/nginx.conf
include /apps/nginx/conf/tcp/*.conf; #需要定在main配置段

3.检查配置文件启动服务

[root@nginx ~]# nginx -t
nginx: the configuration file /apps/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /apps/nginx/conf/nginx.conf test is successful
[root@nginx ~]# nginx -s reload

mariadb端操作

1.安装MySQL

[root@mariadb ~]# yum install mariadb-server -y

2.启动MySQL服务

[root@mariadb ~]# systemctl start mariadb

3.为反向代理授权一个账户

[root@mariadb ~]# msyql -e "GRANT ALL PRIVILEGES ON *.* TO 'root'@'172.20.27.10' IDENTIFIED BY '111111';"

测试

使用客户端去访问反向代理的3306端口

[root@client ~]# mysql -uroot -p111111 -h172.20.27.10 -P3306
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 8
Server version: 5.5.60-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]>