1、stream 模块简介: Nginx 从 1.9.0 版本开始,新增了 stream 模块,可以实现四层协议的转发、代理或负载均衡,比如内网的 MySQL 服务,想暴露到公网上使用,就可以通过 Nginx 代理方式进
1、stream模块简介:
Nginx从1.9.0版本开始,新增了stream模块,可以实现四层协议的转发、代理或负载均衡,比如内网的MySQL服务,想暴露到公网上使用,就可以通过Nginx代理方式进行内网MySQL访问,也可实现后端服务的负载均衡。
2、演示环境:
主机名
操作系统
IP
端口
nginx
CentOS 7.9
192.168.0.120
80
mariadb
CentOS 7.9
192.168.0.121
3306
备注:两台主机分别关闭firewalld和SELinux
3、mariadb主机部署MariaDB:
(1)安装、启动MariaDB:
# yum -y install mariadb-server# systemctl start mariadb
# systemctl enable mariadb
# ss -tunlp | grep 3306
(2)初始化MariaDB:
# mysql_secure_installation(3)登录MariaDB,删除不必要用户:
# mysql -uroot -pMariaDB [(none)]> use mysql;MariaDB [mysql]> select host,user,password from user;
MariaDB [mysql]> delete from user where host='localhost';
MariaDB [mysql]> delete from user where host='127.0.0.1';
MariaDB [mysql]> delete from user where host='::1';
MariaDB [mysql]> flush privileges;
MariaDB [mysql]> select host,user,password from user;
(4)创建测试数据库:
MariaDB [mysql]> create database nginx_proxy;MariaDB [mysql]> show databases;
(5)授权root用户远程登录,方便测试:
MariaDB [mysql]> grant all on *.* to 'root'@'192.168.0.%' identified by '123456';MariaDB [mysql]> flush privileges;
4、nginx主机部署Nginx:
(1)安装依赖软件包:
# yum -y install gcc gcc-c++ pcre-devel zlib-devel(2)编译安装Nginx:
# tar -xf nginx-1.20.1.tar.gz -C /usr/src
# cd /usr/src/nginx-1.20.1
# ./configure --prefix=/usr/local/nginx --with-stream
# make && make install
备注:--with-stream启用TCP/UDP代理模块
(3)配置stream模块:
# vim /usr/local/nginx/conf/nginx.confworker_processes auto;events {
use epoll;
worker_connections 65535;
}
stream {
server {
listen 3366;
proxy_connect_timeout 60s;
proxy_timeout 10m;
proxy_pass 192.168.0.121:3306;
}
}
http {
......
}
备注:
a、proxy_connect_timeout:定义与代理服务器建立连接的超时时长,默认60秒
b、proxy_timeout:设置客户端或代理服务器中两个连续读或写操作之间的连接超时时长,如果在此时间内未传输任何数据,则连接将关闭,默认10分钟
(4)启动Nginx:
# /usr/local/nginx/sbin/nginx -t# /usr/local/nginx/sbin/nginx
# ss -tunlp | grep 80
5、测试:
(1)nginx主机安装数据库客户端工具:
# yum -y install mysql(2)nginx主机通过Nginx代理模块访问内网MariaDB:
# mysql -uroot -h192.168.0.120 -P3366 -p