51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

MySQL数据库远程telnet不通只能本地连接

一、问题概述 {#一、问题概述}

对于一个Linux上新部署的MySQL数据库,往往在连接的时候有可能会碰到连接不上的问题。我就是在近日,写一篇MySQL数据库迁移到DM数据库的博客时,出奇的发现我博客所用的MySQL数据库居然只能从Linux本地连接。由于对MySQL不熟悉,这个问题困扰了我两三个小时。下面本文就来总结一下,MySQL连接不上可能涉及的一些配置。

二、问题解决 {#二、问题解决}

(1)MySQL的配置文件my.cnf

如果你找不到你的my.cnf文件在哪,或者你的机器上有多个my.cnf文件导致你不清楚哪一个才是当前MySQL用到的my.cnf,可以使用如下命令找到my.cnf文件:

[root@dameng ~]# mysql --help|grep my.cnf
                      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。没有就自己新增。
[mysqld]
bind-address = 0.0.0.0

找到 skip-networking,将其注释或删除,没有就可以不用管。
------------------------------------



取消注释或删除 skip-networking 以启用网络连接
===============================


`skip-networking`

注意:0.0.0.0 表示任何人都可以连接,如果没有特殊要求,为了安全起见,可以配置成具体的IP。

重启数据库生效

systemctl restart mysqld

(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 ~]# mysql -h ip -uroot -p
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> `

登录成功。

三、问题总结 {#三、问题总结}

万事要认真仔细。

赞(4)
未经允许不得转载:工具盒子 » MySQL数据库远程telnet不通只能本地连接