本地登錄正常,遠程客戶端(Workbench、Navicat、代碼)報錯 Host 'x.x.x.x' is not allowed to connect 或連接超時。
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'password' WITH GRANT OPTION;
FLUSH PRIVILEGES;
%` 表示任意主機。生產環境建議限制具體 IP:'root'@'192.168.1.100'。
本質是在 mysql.user 表插入一條 Host='%'、User='root' 的記錄。
USE mysql;
UPDATE user SET Host='%' WHERE User='root' AND Host='localhost';
FLUSH PRIVILEGES;
僅授權不開端口 = 連不上。
# CentOS 7+ firewalld
firewall-cmd --permanent --add-port=3306/tcp
firewall-cmd --reload
# iptables 經典
iptables -A INPUT -p tcp --dport 3306 -j ACCEPT
service iptables save
雲服務器(阿里雲/騰訊雲/AWS)還需在安全組/安全策略入站規則放行 3306。
編輯 /etc/my.cnf(或 /etc/mysql/my.cnf):
[mysqld]
bind-address = 0.0.0.0 # 監聽所有網卡
# 或具體內網 IP:bind-address = 192.168.1.50
修改後 必須重啟 MySQL。若配置文件無此項,默認綁定 127.0.0.1(僅本地)。
mysql -uroot -p 登入成功。telnet ip 3306 端口通。SELECT Host,User FROM mysql.user WHERE User='root'; 顯示含 % 或目標 IP。