預設 MySQL 綁定 0.0.0.0:3306(全介面監聽),暴露於公網極不安全。需限制僅允許本機或內網 IP 連線。
mysqld --user=mysql --bind-address=127.0.0.1
# 找到啟動行
$bindir/mysqld_safe --datadir=$datadir --pid-file=$pid_file &
# 改為
$bindir/mysqld_safe --datadir=$datadir --pid-file=$pid_file --bind-address=127.0.0.1 &
[mysqld]
bind-address = 127.0.0.1
# 或指定內網 IP
# bind-address = 192.168.0.5
# 同時監聽本機與內網 (MySQL 8.0.13+)
# bind-address = 127.0.0.1,192.168.0.5
# 重啟服務
systemctl restart mysqld
# 或
/etc/init.d/mysqld restart
# 檢查監聽
netstat -lntp | grep 3306
# 預期輸出
tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN 1234/mysqld
即使 bind-address 設定內網 IP,仍建議配置 iptables/firewalld 僅允許應用伺服器 IP 存取 3306:
# firewalld 範例
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.10/32" port protocol="tcp" port="3306" accept'
firewall-cmd --reload
因資料庫僅對內網開放,建議部署 phpMyAdmin 或 Adminer 於應用伺服器,透過 Web 介面管理,避免開放 3306 至管理者電腦。