nginx四层代理mysql

1)安装两个数据库,四层代理是走tcp ,udp,协议的

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

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

2)启动数据库,创建一个测试账号,创建不同的数据库作为区分

节点1 启动数据库
[root@mysql-1 ~]#systemctl start mariadb

创建测试账号
[root@mysql-1 ~]#mysql -e "grant all on *.* to test1@'192.168.8.%' identified by 'xingyu'"

创建数据库
[root@mysql-1 ~]#mysql -e "create database mysql103"


节点2 启动数据库
[root@mysql-2 ~]#systemctl start mariadb

创建测试账号
[root@mysql-2 ~]#mysql -e 'grant all on *.* to test1@"192.168.8.%" identified by "xingyu"'

创建数据库
[root@mysql-2 ~]#mysql -e "create database mysql104"

3)安装nginx,修改nginx主配置文件

[root@nginx ~]#yum install nginx -y

在nginx配置文件最后添加以下几行
[root@nginx ~]#vim /etc/nginx/nginx.conf

stream {
    upstream mysql {
        server 192.168.8.103:3306;      #后端数据库地址
        server 192.168.8.104:3306;      #后端数据库地址
    }
    server {
        listen 192.168.8.100:3306;      #本机地址
        proxy_pass mysql;
    }

}


检查语法是否正确
[root@nginx ~]#nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful


启动nginx服务
[root@nginx ~]#nginx


可以看到nginx已监听3306端口
[root@nginx ~]#ss -ntl
State      Recv-Q Send-Q                   Local Address:Port                                  Peer Address:Port              
LISTEN     0      100                          127.0.0.1:25                                               *:*                  
LISTEN     0      128                          127.0.0.1:9000                                             *:*                  
LISTEN     0      128                      192.168.8.100:3306        

4)测试,(注:测试机需要有mysql客户端,如果没有执行 yum install mariadb -y 安装)

默认以轮询的方式调度

[root@test ~]#mysql -utest1 -pxingyu -h192.168.8.100 -e "show databases"
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| mysql103           |
| performance_schema |
| test               |
+--------------------+
[root@test ~]#mysql -utest1 -pxingyu -h192.168.8.100 -e "show databases"
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| mysql104           |
| performance_schema |
| test               |
+--------------------+


©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。