預設 MySQL 監聽 0.0.0.0:3306 (所有網卡介面),暴露於公網極度危險。限制僅監聽 127.0.0.1 (本機) 或內網特定 IP,是資料庫網路層面的第一道防線。
bind-address (推薦、標準、持久化)編輯 /etc/my.cnf 或 /etc/mysql/my.cnf:
[mysqld]
# 僅本機回環
bind-address = 127.0.0.1
# 或僅特定內網 IP (單 IP)
bind-address = 10.0.1.5
# MySQL 8.0+ 支援多 IP (逗號分隔)
bind-address = 127.0.0.1,10.0.1.5
重啟生效:systemctl restart mysqld。
--bind-address (臨時、測試、容器化適用)編輯 /etc/init.d/mysql (SysVinit) 或 systemd 服務檔:
# SysVinit 範例
$bindir/mysqld_safe --datadir=$datadir --pid-file=$pid_file --bind-address=127.0.0.1 &
# systemd 臨時覆蓋
systemctl edit mysqld
# 輸入:
[Service]
ExecStart=
ExecStart=/usr/sbin/mysqld --bind-address=127.0.0.1 $MYSQLD_OPTS
# 檢查監聽狀態
netstat -tlnp | grep 3306
# 輸出應僅顯示:
# tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN 1234/mysqld
ss -tlnp | grep 3306 # 現代替代指令
| 層面 | 措施 | 指令/配置 |
|---|---|---|
| 網路 | bind-address 限制介面 | bind-address = 127.0.0.1 |
| 防火牆 | 僅允許應用伺服器 IP 存取 3306 | ufw allow from 10.0.1.0/24 to any port 3306 |
| 帳號 | root 僅 localhost,應用帳號指定 Host | CREATE USER 'app'@'10.0.1.%' IDENTIFIED BY '...'; |
| 加密 | 強制 SSL/TLS 連線 | REQUIRE SSL / mysql_ssl_rsa_setup |
| 審計 | 啟用審計日誌記錄登入/查詢 | plugin-load-add=audit_log.so |
skip-networking 等同綁定本機:skip-networking 會完全禁用 TCP/IP,**只能用 Unix Socket 連線**,會導致部分語言驅動 (預設 TCP) 連線失敗。bind-address=127.0.0.1 仍保留 TCP 回環連線,相容性更好。0.0.0.0,靠宿主機防火牆/安全群組控制存取,或使用 Docker Network 隔離。SET GLOBAL bind_address **不支援**,必須重啟服務。grep bind-address /etc/my.cnf /etc/mysql/my.cnf /etc/mysql/mysql.conf.d/mysqld.cnf 確認配置生效檔案。systemctl restart mysqld && sleep 2 && netstat -tlnp | grep 3306 驗證。mysql -h 127.0.0.1 -u app -p。