如何解决远程连接mysql出现Can't connect to MySQL server on (111 "Connection refused")的问题

导语:有位客户的机器需要开放Mysql的远程连接,当配置完账号权限后,却发现远程连接的时候出现Can’t connect to MySQL server on (111 “Connection refused”)的问题,叶子经过排查解决了这个问题。下面是步骤。

开放Mysql的远程连接

在服务器上登录mysql,然后执行以下的命令。

登录mysql:

/usr/local/mysql-5.6/bin/mysql -u root -p

执行赋权的命令:

MySQL> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'IDENTIFIED BY '123456' WITH GRANT OPTION; 
MySQL> flush privileges;

也可以直接重启mysql。

/usr/local/mysql-5.6/support-files/mysql.server restart

远程连接Mysql

在本地连接mysql,我们可以使用mysql workbench,这是一款英文的mysql的客户端。

连接的时候出现错误:Can’t connect to MySQL server on Ip地址 (111 “Connection refused”)。

检查防火墙

先检查防火墙的3306端口是不是放开了。这台服务器使用的是iptables,打开iptables,配置3306端口。

vi /etc/sysconfig/iptables

# Firewall configuration written by system-config-firewall
# Manual customization of this file is not recommended.
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -p tcp -m tcp --dport 10100:10180 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 21 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 3306 -j ACCEPT
-A INPUT -j REJECT –reject-with icmp-host-prohibited
-A FORWARD -j REJECT –reject-with icmp-host-prohibited
COMMIT

重启防火墙

/etc/init.d/iptables restart

检查my.cnf

在my.cnf的配置文件中,有参数控制它是否运行在网络上。例如查看这个my.cnf。

vi /usr/local/mysql-5.6/my.cnf

如果是老的版本,使用#屏蔽skip-networking,如下。

#skip-networking

如果是新的版本,使用#屏蔽bind-address。

#bind-address  = 127.0.0.1

或者指定允许访问的ip

#bind-address       = 192.168.1.2

然后重启mysql。

/usr/local/mysql-5.6/support-files/mysql.server restart

这里是用文件的方式来启动mysql,你可以用服务的方式。

叶子在屏蔽#skip-networking后,再远程连接mysql就OK了。

附录iptables防火墙的命令

查询防火墙状态:

[root@localhost ~]# service   iptables status

停止防火墙:

[root@localhost ~]# service   iptables stop

启动防火墙:

[root@localhost ~]# service   iptables start

重启防火墙:

[root@localhost ~]# service   iptables restart

永久关闭防火墙:

[root@localhost ~]# chkconfig   iptables off

永久关闭后启用:

[root@localhost ~]# chkconfig   iptables on

编辑防火墙规则

vi /etc/sysconfig/iptables

重启防火墙的其他方式

/etc/init.d/iptables restart

结束

你学会了吗?

发表评论

邮箱地址不会被公开。 必填项已用*标注