Four-layer proxy configuration using Nginx

1. Basic introduction

Usually, when we configure the Nginx proxy, we generally configure httpthe httpsproxy based on the or protocol, that is, the application layer. But sometimes, we don't want to configure this kind of application layer based proxy. For example: we want to proxy to the database, but the database does not support application layer proxy.


Therefore, we cannot configure it as usual, but after Nginx version 1.9.0 , Nginx can implement a four-layer-based reverse proxy by configuring --with-streammodules . Therefore, we can access the database by proxying the port to the port.

The above is just an analogy. In fact, we can proxy to any service that uses the four-layer protocol through the four-layer proxy, not just the database.

Second, use Nginx to achieve four-layer proxy configuration

1. Install Nginx

[root@Nginx ~]# yum -y install pcre-devel zlib-devel popt-devel openssl-devel openssl
[root@Nginx ~]# wget http://www.nginx.org/download/nginx-1.21.0.tar.gz
[root@Nginx ~]# ls
anaconda-ks.cfg  nginx-1.21.0.tar.gz
[root@Nginx ~]# tar zxf nginx-1.21.0.tar.gz -C /usr/src/
[root@Nginx ~]# cd /usr/src/nginx-1.21.0/
[root@Nginx nginx-1.21.0]# useradd -M -s /sbin/nologin nginx
[root@Nginx nginx-1.21.0]# ./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-file-aio \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--with-http_flv_module \
--with-http_ssl_module \
--with-stream \
--with-pcre && make && make install
[root@Nginx nginx-1.21.0]# ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/
[root@Nginx nginx-1.21.0]# cd
[root@Nginx ~]# nginx
[root@Nginx ~]# netstat -anpt | grep 80

2. Modify the Nginx configuration file

  • streamIt can be at the same level as httpthe region .
[root@Nginx ~]# cat <<END >> /usr/local/nginx/conf/nginx.conf
stream {
    
    
  upstream test_mysql {
    
    
    hash $remote_addr consistent;				# 通过配置一致性 hash 来防止调度异常
    server 192.168.1.1:3306 weight=5 max_fails=3 fail_timeout=30s;
  }
  server {
    
    
    listen 10086 so_keepalive=on;				# 开启 TCP 存活探测
    proxy_connect_timeout 10s;					# 连接超时时间
    proxy_timeout 300s;							# 端口保持时间
    proxy_pass test_mysql;
  }
}
END
[root@Nginx ~]# nginx -s reload

3. Verify

1) Install MariaDBthe database

[root@Nginx ~]# yum -y install mariadb mariadb-server mariadb-libs mariadb-devel
[root@Nginx ~]# systemctl start mariadb
[root@Nginx ~]# mysqladmin -uroot password '123123'

insert image description here
2) Verify
insert image description here

Guess you like

Origin blog.csdn.net/weixin_46902396/article/details/124322638
Recommended