首页 > 解决方案 > MySQL远程连接被拒绝

问题描述

我正在尝试连接在我的 VPS 上运行的 MySql(比如说主机名 db.example.com)。

问题是:在 db.example.com 上,我可以本地连接 mysql(从数据库服务器本身),但我不能远程连接(从我的开发机器)。

我应该如何检查设置?

我可以 ssh 到 db.example.com 并通过运行以下命令进行检查。

在服务器 db.example.com(ubuntu 18.04)上:

$ mysql -u satrex -p
> success

mysql> select user, host from mysql.user where user = 'satrex';
+--------+------+
| user   | host |
+--------+------+
| satrex | %    |
+--------+------+
$ sudo ufw status
>Status: active
To                         Action      From
--                         ------      ----
3306                       ALLOW       Anywhere
Apache Full                ALLOW       Anywhere
3306 (v6)                  ALLOW       Anywhere (v6)
Apache Full (v6)           ALLOW       Anywhere (v6)
$ sudo lsof -i:3306
> COMMAND PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
mysqld  597 mysql   43u  IPv4  16358      0t0  TCP *:mysql (LISTEN)
$ sudo cat /etc/mysql/mysql.conf.d/mysqld.cnf 
>
[mysqld]
port            = 3306
....
# bind-address                = 127.0.0.1
bind-address            = 0.0.0.0

然后我尝试从开发机器连接。

在开发机器上(macOS catalina)

我可以通过 telnet 连接到服务器。

$ telnet db.example.com 80
> Trying 160.16.xxx.xxx ...
Connected to db.example.com.

但在 3306 端口被拒绝。

$ telnet db.example.com 3306
> Trying 160.16.xxx.xxx ...
telnet: connect to address 160.16.xxx.xxx: Connection refused
telnet: Unable to connect to remote host

与 mysql 客户端相同。

$ mysql --host=db.example.com --user=satrex --password
> Enter password:
> ERROR 2003 (HY000): Can't connect to MySQL server on 'db.example.com:3306' (61)

我想知道我缺少连接的基本设置。它应该在配置 MySQL 本身之前。

现在 db.myself 正在监听端口 80,如 ufw 所示,另一方面,端口 3306,ufw 显示为正在监听,但没有运气。

标签: mysql

解决方案


首先,您需要检查您的安全组是否允许 EC2 实例访问 0.0.0.0(全局) 在此处输入图像描述

然后在您的 SQL EC2 实例上检查绑定地址sudo grep -R bind /etc/mysql ,如果它看起来像这样,那么我们需要修改一些东西

在此处输入图像描述

转到此路径/etc/mysql/mysql.conf.d并修改此文件sudo vim mysqld.cnf 在此处输入图像描述

绑定地址应该是bind-address = 0.0.0.0

终于是时候重启mysql服务了

sudo systemctl restart mysql.service

对我来说,如果它对你有用,这个解决方案就是有效的,如果你仍然觉得这个问题有困难,请投票谢谢


推荐阅读