通过nginx搭建mysql代理
工作中,本地mysql工具无法访问远程的mysql数据库,但是开发机A可以访问,同时本地可以访问开发机A, 调研后,采用了nginx的stream进行mysql的请求转发
bashctar zxf nginx-1.23.3.tar.gz tar zxf pcre2-10.42.tar.gz
bashcd nginx-1.23.3
./configure
--prefix=/home/work/demo-nginx
--with-cc=/opt/compiler/gcc-10/bin/gcc
--with-pcre=/home/work/nginx-build/pcre2-10.42
--with-stream --with-http_ssl_module
make -j$(nproc)
cd objs/
查看是否有makeFile文件/home/work/demo-nginx/sbin/nginx -v
检测是否安装成功confstream { upstream mysql_backend { server xxx.xxx.xxx.xxx:6213; # 改成你的实际 MySQL 服务器地址 } server { listen 8307; # Nginx 对外暴露的端口(可以改) proxy_pass mysql_backend; } upstream mysql_backend1 { server xx.xx.xxx.xxx:6397; # 改成你的实际 MySQL 服务器地址 } server { listen 8308; # Nginx 对外暴露的端口(可以改) proxy_pass mysql_backend1; }
bash# 重启
/home/work/demo-nginx/sbin/nginx -s reload -c /home/work/demo-nginx/conf/nginx.conf
# 开启
/home/work/demo-nginx/sbin/nginx
可以写一个脚本进行手动方便操作
bash#!/bin/bash
NGINX_PATH="/home/work/demo-nginx"
NGINX_BIN="$NGINX_PATH/sbin/nginx"
NGINX_CONF="$NGINX_PATH/conf/nginx.conf"
NGINX_PID="$NGINX_PATH/logs/nginx.pid"
start_nginx() {
if [ -f "$NGINX_PID" ] && ps -p $(cat "$NGINX_PID") > /dev/null 2>&1; then
echo "✅ Nginx 已经在运行中 (PID: $(cat $NGINX_PID))"
else
echo "🚀 正在启动 Nginx..."
$NGINX_BIN -c "$NGINX_CONF"
if [ $? -eq 0 ]; then
echo "✅ 启动成功!"
else
echo "❌ 启动失败,请检查配置。"
fi
fi
}
stop_nginx() {
if [ -f "$NGINX_PID" ] && ps -p $(cat "$NGINX_PID") > /dev/null 2>&1; then
echo "🛑 正在停止 Nginx (PID: $(cat $NGINX_PID))..."
$NGINX_BIN -s stop -c "$NGINX_CONF"
sleep 1
echo "✅ 已停止"
else
echo "⚠️ Nginx 未运行或找不到 PID 文件"
fi
}
restart_nginx() {
echo "🔁 正在重启 Nginx..."
stop_nginx
sleep 1
start_nginx
}
case "$1" in
start)
start_nginx
;;
stop)
stop_nginx
;;
restart)
restart_nginx
;;
*)
echo "用法: $0 {start|stop|restart}"
exit 1
;;
esac
本文作者:曹子昂
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!