2025-04-22
linux相关
00

目录

背景
采用nginx的原因
nginx安装
额外

通过nginx搭建mysql代理

背景

工作中,本地mysql工具无法访问远程的mysql数据库,但是开发机A可以访问,同时本地可以访问开发机A, 调研后,采用了nginx的stream进行mysql的请求转发

采用nginx的原因

  • mysql连接为tcp的方式,素以需要用到nginx的sream模块进行转发

nginx安装

  1. 下载nginx安装包,并解压
  2. 下载pcre 安装包,并解压
bashc
tar zxf nginx-1.23.3.tar.gz tar zxf pcre2-10.42.tar.gz
  1. 进入nginx文件夹中,执行编译
bash
cd 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
  1. 执行安装 make -j$(nproc)
  2. 备注
  • 检测nginx是否编译成功:cd objs/ 查看是否有makeFile文件
  • 安装后,/home/work/demo-nginx/sbin/nginx -v 检测是否安装成功
  1. 编译nginx.conf
conf
stream { 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; }
  1. 开启或重启nginx
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 许可协议。转载请注明出处!