2018/03/31

centos7-mysql远程连接


my.cnf 里的 bind-address = 127.0.0.1 注释掉

我们通过 netstat -apn|grep 3306 查看当前mysql网络状态信息

# netstat -apn|grep 3306
tcp6       0      0 :::3306                 :::*                    LISTEN      25553/mysqld

以上 :::3306 表示监听了不限制访问IP,即第一步注释bind-address = 127.0.0.1所产生的效果


添加一个root用户,密码为123456,可访问所有权限,不限登陆主机

grant all privileges on *.* to 'root'@'%' identified by "123456" with grant option;

刷新权限:flush privileges;


如果执行完以上步骤后发现无法连接,则基本就在于防火墙问题上。

我们使用telnet进行测试3306端口能否成功

# telnet 192.168.2.21 3306
Trying 192.168.2.21...
telnet: connect to address 192.168.2.21: Connection timed out

可以看到没法telnet成功


centos7采用的是firewall作为防火墙,这里改为iptables防火墙

1.关闭firewall:

systemctl stop firewalld.service #停止firewall
systemctl disable firewalld.service #禁止firewall开机启动

firewall-cmd --state #查看默认防火墙状态(关闭后显示notrunning,开启后显示running)

2.安装iptables-services、iptables-devel

sudo yum install iptables-services iptables-devel

3.启用并启动iptables

sudo systemctl enable iptables.service
sudo systemctl start iptables.service

4.在iptables配置文件里添加3306可访问

-A INPUT -p tcp -m tcp --dport 3306 -j ACCEPT

重启防火墙,并保存配置

systemctl restart iptables.service
service iptables save

重新telnet下成功则可以进行远程访问mysql。