Loading...

文章背景图

[学习,整理] 无法连接到mariadb/mysql

2021-03-22
1135
-
- 分钟

情况

测试环境为Ubuntu Server 20.04.1 LTS,在使用军哥的lnmp脚本搭建完lnmp环境并重启后,发现远程连接不上mariadb。

MariaDB [(none)]> use mysql;
Database changed
MariaDB [mysql]> select user,host from user;
+------+-----------+
| user | host      |
+------+-----------+
| root | 127.0.0.1 |
| root | ::1       |
| root | localhost |
+------+-----------+
4 rows in set (0.000 sec)

MariaDB [mysql]>

执行查询后发现没有host为%的root用户。于是使用grant命令创建了用于远程登录的root用户。

MariaDB [(none)]> GRANT ALL PRIVILEGES ON *.* TO 新用户名@"%" IDENTIFIED BY '密码' WITH GRANT OPTION;
Query OK, 0 rows affected (0.001 sec)

MariaDB [(none)]> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.000 sec)

但使用navicatheidisql还是无法连接。

于是看了一下端口情况。

root@vuw:~# iptables -L -n
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0            state RELATED,ESTABLISHED
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:22
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:80
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:443
DROP       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:3306
ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0            icmptype 8

发现3306端口被DROP了。


解决方案

创建一个文件,里面写上要放行的端口
文件路径随意,这里只作为参考:/etc/iptables.rules

*filter
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 3306 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 8080 -j ACCEPT
COMMIT

第一行必须为*filter,最后一行必须为COMMIT


再创建一个脚本,用于将规则导入iptables。
文件路径随意,这里只作为参考:/etc/init.d/port

#!/bin/bash
iptables-restore < /etc/iptables.rules

赋予脚本执行权限。

chmod +x /etc/init.d/port

添加一个service,在网络启动后,对端口进行放行。
/etc/systemd/system/AllowPort.service

[Unit]
Description=allow port
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
# 执行那个脚本
ExecStart=/etc/init.d/port
# 直接这样写会报错
#ExecStart=iptables-restore < /etc/iptables.rules

[Install]
WantedBy=multi-user.target

再将这个service设置为开机启动。

systemctl enable AllowPort

然后就可以重启,使用iptables -L -n命令验收成果了。
在自己解决完问题后去又去军哥的lnmp官网看了一下,在常见问题中就有这个问题的解决方案https://bbs.vpser.net/thread-13563-1-1.html


文章引用

ubuntu18.04 使用systemd方式添加开机运行sh脚本
ubuntu下设置iptables方法

评论交流

文章目录