EC2云主机开启MySql远程访问

最近在亚马逊云主机上安装MySql,想远程访问,结果无论如何都访问不了。在踩了若干坑之后,终于访问成功了,在此做一下记录:EC2云主机上安装了MySql后如何开启远程访问。

一、遇到的问题

想远程访问EC2上的MySql,总提示:
ERROR 2003 (HY000): Can't connect to MySQL server on 'xx.xx.xx.xx' (111)
或者
Host 'xx.xx.xx.xx' is not allowed to connect to this MySQL server

二、解决方案

1、设置EC2的防火墙

EC2默认防火墙是阻断所有流量,因此在EC2的Scurity Groups中除了其他必要的规则之外,还要添加一条入口流量规则:TCP的3306端口的任意源IP的连接都允许

2、MySql中设置用户的访问

MySql默认只允许从本机访问,要使得能够远程访问,分别在Terminal中执行以下命令:

mysql -u root -p
use mysql
update user set Host='%' where User='root'

这样就能从任意IP访问MySql了。

3、MySql中设置绑定IP

sudo vim /etc/mysql/my.cnf

然后把bind-address 127.0.0.1改为bind-address 0.0.0.0,这样EC2的IP无论怎样变化,都能够远程访问了。

4、重启MySql

sudo /etc/init.d/mysql restart

三、参考

Mysql初始化root密码和允许远程访问
Connect to mysql on Amazon EC2 from a remote server

/** * RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS. * LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/ /* var disqus_config = function () { this.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable }; */ (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = 'https://chenzz.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })();