搭建nginx服务器来代理mysql

一、下载nginx包

二、安装&编译

yum -y install gcc gcc-c++ autocon
yum -y install pcre-devel openssl openssl-devel
tar -xvf nginx-1.18.0.tar.gz
cd nginx-1.18.0
./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_realip_module --with-http_flv_module --with-http_mp4_module --with-http_gzip_static_module --with-stream --with-stream_ssl_module
make
make install

三、配置

    /usr/local/nginx/conf/nginx.conf(可配置多个server)
#user  nobody;
worker_processes  2;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
          
   
    worker_connections  1024;
}

stream {
          
   
	upstream mysql1 {
          
   
        hash $remote_addr consistent;
        server $db_host1:$db_port1 max_fails=3 fail_timeout=30s;
    }
    server {
          
   
        listen 3021;
        proxy_connect_timeout 30s;
        proxy_pass mysql1;
    }

	upstream  mysql2 {
          
   
        hash $remote_addr consistent;
        server $db_host2:$db_port2 max_fails=3 fail_timeout=30s;
    }
    server {
          
   
        listen 3022;
        proxy_connect_timeout 30s;
        proxy_pass mysql2;
    }
}

四、启Nginx进程

1、启动:/usr/local/nginx/sbin/nginx 2、启动后会看到(ps -ef |grep nginx)一个master进程和两个worker进程 3、此时便可通过nginx的ip+server_port来连接mysql服务

经验分享 程序员 微信小程序 职场和发展