使用nginx反向代理mysql服务

1 注意

  • 配置nginx代理mysql需要nginx版本至少1.9的版本,版本太低没有stream这个功能
  • nginx配置文件位置可能的位置 /usr/local/nginx/conf /etc/nginx /usr/local/etc/nginx
  • 记得关掉防火墙

2 nginx安装

1. 参考:[nginx官方文档](http://nginx.org/en/linux_packages.html)
2. shell安装脚本
#!/bin/bash
#Date:2020-9-01
#Author:wjt
#Function:  install nginx
#####################################################################
#sed -i 's/\r$//' nginx.sh

sudo yum install yum-utils
cat>/etc/yum.repos.d/nginx.repo<<EOF
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/\$releasever/\$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/\$releasever/\$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
EOF
sudo yum-config-manager --enable nginx-mainline
sudo yum install nginx -y

3 修改nginx配置文件

配置文件nginx.conf位置 /etc/nginx


user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
     
    worker_connections  1024;
}


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

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    # include /etc/nginx/conf.d/*.conf;
}

# mysql反向代理配置
stream {
     
    upstream mysql {
     
        hash $remote_addr consistent;
        # mysql服务真实地址
        server 172.17.0.1:3307 weight=50 max_fails=1 fail_timeout=10s;

    }
      
server {
     
        #nginx监听的端口
        listen 3301;  
        proxy_connect_timeout 1s;
        proxy_timeout 3s;
        proxy_pass mysql;
    }
}


# 如果你的mysql服务是通过docker搭建的,那你需要用这个指令去获取容器的独立IP
#docker inspect --format='{
     {.NetworkSettings.IPAddress}}' 容器名称|容器id
#docker inspect --format='{
     {.NetworkSettings.IPAddress}}' mysql-8.0

4 nginx服务管理命令

nginx -s reload            # 重新载入配置文件
nginx -s reopen            # 重启 Nginx
nginx -s stop               # 停止 Nginx
systemctl stop firewalld # 关闭防火墙

5 参考

菜鸟Nginx 安装配置

nginx官方文档

博客园防火墙参考

你可能感兴趣的:(nginx,nginx,linux)