本文于 108 天前发布,最后更新于 105 天前
一、问题概述
对于一个 Linux 上新部署的 MySQL 数据库,往往在连接的时候有可能会碰到连接不上的问题。我就是在近日,写一篇 MySQL 数据库迁移到 DM 数据库的博客时,出奇的发现我博客所用的 MySQL 数据库居然只能从 Linux 本地连接。由于对 MySQL 不熟悉,这个问题困扰了我两三个小时。下面本文就来总结一下,MySQL 连接不上可能涉及的一些配置。
二、问题解决
(1)MySQL 的配置文件 my.cnf
如果你找不到你的 my.cnf 文件在哪,或者你的机器上有多个 my.cnf 文件导致你不清楚哪一个才是当前 MySQL 用到的 my.cnf,可以使用如下命令找到 my.cnf 文件:
| [root@dameng ~] |
| order of preference, my.cnf, $MYSQL_TCP_PORT, |
| /etc/my.cnf /etc/mysql/my.cnf ~/.my.cnf |
可以看到有多个 my.cnf 文件,先后顺序表明了他们的优先级,所以只需要配置第一个 /etc/my.cnf:
| |
| [mysqld] |
| bind-address = 0.0.0.0 |
| |
| |
| |
| |
注意:0.0.0.0 表示任何人都可以连接,如果没有特殊要求,为了安全起见,可以配置成具体的 IP。
重启数据库生效
(2)配置数据库的用户访问权限
新部署的 MySQL 数据库,root 用户默认是 127.0.0.1/localhost,那么这个用户就只能本地访问,其它机器用这个用户访问会提示没有权限,所以要将 host 改为 %,表示允许所有机器访问。
| mysql> use mysql; |
| Reading table information for completion of table and column names |
| You can turn off this feature to get a quicker startup with -A |
| |
| Database changed |
| mysql> select Host,User from user; |
| +-----------+------------------+ |
| | Host | User | |
| +-----------+------------------+ |
| | localhost | mysql.infoschema | |
| | localhost | mysql.session | |
| | localhost | mysql.sys | |
| | localhost | root | |
| +-----------+------------------+ |
| 4 rows in set (0.01 sec) |
| |
| mysql> update user set host='%' where host='localhost'; |
| Query OK, 4 rows affected (0.01 sec) |
| Rows matched: 4 Changed: 4 Warnings: 0 |
| |
| mysql> commit; |
| Query OK, 0 rows affected (0.00 sec) |
| |
| mysql> flush privileges; |
| Query OK, 0 rows affected (0.00 sec) |
(3)防火墙 firewalld 和 iptables
由于之前我就将 firewalld 关闭了,所以这个方面就没有多想。没想到,问题恰恰就出在这里。所以,今后在解决问题的时候一定要认真仔细,才不会疏漏掉任何的细节,才能更准确地定位问题的所在。
关闭 firewalld
| |
| systemctl stop firewalld |
| |
| systemctl disable firewalld |
我不清楚为什么我的服务器有两个防火墙,firewalld 和 iptables 同时存在,所以导致我漏掉了 iptables。而且我从 iptables 的配置文件 /etc/sysconfig/iptables 中看到了如下配置:
| -A INPUT -p tcp -m tcp --dport 3306 -j DROP |
所以我把 DROP 修改成了 ACCEPT,并且新增一行,开启 3306 端口:
| -A INPUT -m state --state NEW -m tcp -p tcp --dport 3306 -j ACCEPT |
重启 iptables 服务
| systemctl restart iptables |
(4)验证登录 - 通过网络 IP 连接
| [root@dameng ~] |
| Enter password: |
| Welcome to the MySQL monitor. Commands end with ; or \g. |
| Your MySQL connection id is 397 |
| Server version: 8.0.26 Source distribution |
| |
| Copyright (c) 2000, 2021, Oracle and/or its affiliates. |
| |
| Oracle is a registered trademark of Oracle Corporation and/or its |
| affiliates. Other names may be trademarks of their respective |
| owners. |
| |
| Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. |
| |
| mysql> |
登录成功。
三、问题总结
万事要认真仔细。