現象:在 Mac 系統上,mysql 不允許遠程連接。
首先按照常規的方法操作:
進入 mysql: $ mysql -u root -p
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'yourpassword' WITH GRANT OPTION;
mysql> FLUSH PRIVILEGES;
再次嘗試連接,還是不行。
后來發現,即使在本地使用 IP 也無法連接。那估計就是 mysql 服務綁定的 IP 有問題,要找到 mysql 的配置文件看看。
當時用 Homebrew 安裝的 mysql,查看 brew info mysql
,沒有找到 mysql 配置文件的位置,卻有這樣一句話:
MySQL is configured to only allow connections from localhost by default
查看 msyql --help
,mysql 提示會按照下面的順序查找配置文件。
Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/local/etc/my.cnf ~/.my.cnf
最終發現,使用 Homebrew 安裝 mysql,默認配置在 /usr/local/etc/my.cnf
,內容是:
# Default Homebrew MySQL server config
[mysqld]
# Only allow connections from localhost
bind-address = 127.0.0.1
顧名思義,bind-addres
的配置綁定了本地IP,所以遠程無法連接。再看看 mysql 官方文檔, bind-address
的配置是這樣描述的:
If the address is 0.0.0.0, the server accepts TCP/IP connections on all server host IPv4 interfaces.
If the server was started with —bind-address=127.0.0.1, it will listen for TCP/IP connections only locally on the loopback interface and will not accept remote connections.
于是修改配置為: bind-address = 0.0.0.0
重啟 mysql:brew services restart mysql
再次嘗試遠程連接,終于通了。