centos 远程连接数据库踩坑记
最近舍弃百度云服务器,割肉买了三年阿里云服务器,虽然配置相同,毕竟价钱在那摆着,不得不说,阿里云服务器是真的好用。。。强入广告,emmmmmm。废话不多说,直接上代码。
第一次安装可以根据菜鸟教程安装mysql,这里就不在赘述。https://www.runoob.com/mysql/mysql-install.html
server git:(master) ✗ mysql -h 120.*.*.* -u root -p
Enter password:
ERROR 1130 (HY000): Host '0.0.0.0' is not allowed to connect to this MySQL server
在本地测试连接数据库出现上述问题。
解决过程
shell > netstat -apn
查看所有端口信息,可以看出mysqld服务Listen端口号为3306
[root@test ~]# netstat -apn
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1185/sshd
tcp 0 36 0.0.0.0.181:22 0.0.0.0:8494 ESTABLISHED 1212/sshd: root@pts
tcp 0 0 0.0.0.0:41526 10.0.0.0.26:80 ESTABLISHED 1132/AliYunDun
tcp6 0 0 :::3306 :::* LISTEN 1061/mysqld
tcp6 0 0 0.0.0.0:3306 0.0.0.0:8345 ESTABLISHED 1061/mysqld
tcp6 0 0 0.0.0.0:3306 0.0.0.0:8344 ESTABLISHED 1061/mysqld
udp 0 0 0.0.0.0:68 0.0.0.0:* 721/dhclient
udp 0 0 127.0.0.1:323 0.0.0.0:* 517/chronyd
udp6 0 0 ::1:323 :::* 517/chronyd
这里处于隐私考虑,把真实ip全部替换为0.0.0.0
[root@test ~]# netstat -apn | grep 3306
查询3306端口占用情况
[root@test ~]# netstat -apn | grep 3306
tcp6 0 0 :::3306 :::* LISTEN 1061/mysqld
tcp6 0 0 0.0.0.0:3306 0.0.0.0:8345 ************ 1061/mysqld
tcp6 0 0 0.0.0.0:3306 0.0.0.0:8344 ************ 1061/mysqld
在服务器上能正常启动,这时考虑到防火墙问题,阿里云服务器防火墙默认关闭状态,这里需要重新开启下防火墙,并配置端口号,然后在阿里云控制平台添加安全组。
这里只展示配置port代码,防火墙具体配置在我的另外一篇博客中有写,可以参考。
[root@test ~]# firewall-cmd --permanent --add-port=3306/tcp
success
防火墙和安全组配置好之后,这时重试连接还是ERROR 1130 (HY000): Host '0.0.0.0'' is not allowed to connect to this MySQL server
- 修改mysql数据库中host配置
mysql> select host, user from user;
+-----------+------+
| host | user |
+-----------+------+
| 127.0.0.1 | root |
| ::1 | root |
| localhost | |
| localhost | root |
| naruto | |
| naruto | root |
+-----------+------+
mysql> update user set host = '%' where user = 'root';
// 这里会有下面的错误,不用管,继续撸
ERROR 1062 (23000): Duplicate entry '%-root' for key 'PRIMARY'
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
mysql> select host, user from user;
// 这时host已经更改了
+-----------+------+
| host | user |
+-----------+------+
| % | root |
| 127.0.0.1 | root |
| ::1 | root |
| localhost | |
| naruto | |
| naruto | root |
+-----------+------+
通过以上一顿操作后,在重试连接服务器数据库,
➜ test git:(master) ✗ mysql -h 0.0.0.0 -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
至此,centos mysql已经可以远程链接了。