Nginx 代理 TCP協議 MySQL連接


使用nginx代理mysql連接有個好處就是,如果做了容災處理的話, 可以瞬間平滑切換到可用服務上。

 

1. vi /etc/nginx/nginx.conf ,在 http{} 結構體外(也就是文件末尾)添加如下配置:

stream {

    upstream cloudsocket {
       hash $remote_addr consistent;
      # $binary_remote_addr;
       server 192.168.182.155:3306 weight=5 max_fails=3 fail_timeout=30s;
    }
    server {
       listen 3306;#數據庫服務器監聽端口
       proxy_connect_timeout 10s;
       proxy_timeout 300s;#設置客戶端和代理服務之間的超時時間,如果5分鍾內沒操作將自動斷開。
       proxy_pass cloudsocket;
    }
}

 

2. cat /etc/nginx/nginx.conf ,內容如下:

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

stream {
    upstream cloudsocket {
       hash $remote_addr consistent;
      # $binary_remote_addr;
       server 192.168.182.155:3306 weight=5 max_fails=3 fail_timeout=30s;
    }
    server {
       listen 3306;#數據庫服務器監聽端口
       proxy_connect_timeout 10s;
       proxy_timeout 300s;#設置客戶端和代理服務之間的超時時間,如果5分鍾內沒操作將自動斷開。
       proxy_pass cloudsocket;
    }
}

 

3. systemctl restart nginx ,重啟nginx。

4.驗證

登錄192.168.182.156服務器執行看是否有3306端口的監聽

[root@localhost sbin]# netstat -nap|grep 3306
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      89870/nginx: master 

用Navicat for MySQ工具測試是否能連接

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM