Ubuntu 預設 MySQL 安裝綁定 127.0.0.1,導致遠程連接被拒。一鍵解除:註釋 bind-address 並重啟服務。
mysql -h 127.0.0.1 -u root -p 正常mysql -h server_ip -u root -p 報錯 ERROR 2003 (HY000): Can't connect to MySQL serverGRANT ALL ON *.* TO 'user'@'%'、防火牆已放行 3306
# /etc/mysql/my.cnf 或 /etc/mysql/mysql.conf.d/mysqld.cnf
bind-address = 127.0.0.1 # 僅監聽回環地址
nano /etc/mysql/my.cnf(或 /etc/mysql/mysql.conf.d/mysqld.cnf)bind-address = 127.0.0.1# bind-address = 127.0.0.1Ctrl+O → Enter → Ctrl+Xsystemctl restart mysql / service mysql restart
# 查看監聽端口
netstat -tlnp | grep 3306
ss -tlnp | grep 3306
# 應顯示 0.0.0.0:3306 或 :::3306(監聽所有介面)
# 遠程測試
mysql -h server_ip -u remote_user -p
| 措施 | 命令/配置 |
|---|---|
| 防火牆限制來源 IP | ufw allow from 10.0.0.0/8 to any port 3306 |
| 用戶僅允許特定 IP | CREATE USER 'app'@'10.0.%' IDENTIFIED BY 'strongpass'; |
| 啟用 SSL 連接 | require_secure_transport=ON + 憑證配置 |
| 修改默認端口 | port = 33067(配置文件 + 防火牆) |
| 關閉不需要的用戶 | DROP USER ''@'localhost'; DROP USER 'root'@'%'; |