MySQL bind-address 僅支援單一 IP (或 0.0.0.0 全開),無法原生實現「只允許特定多個 IP 連線」。生產環境需結合防火牆 (iptables/firewalld) 白名單實現精準存取控制。本文說明原理並給出生產可用規則集。
# my.cnf
[mysqld]
bind-address = 127.0.0.1 # 僅本機
bind-address = 192.168.1.10 # 單一業務 IP
bind-address = 0.0.0.0 # 全網卡監聽 (不安全)
官方文檔明確:「MySQL server listens on a single network socket... bound to a single address」。無法寫多個 IP 或 CIDR。
192.168.1.3192.168.1.4、192.168.1.5、192.168.1.6
# /etc/my.cnf
[mysqld]
bind-address = 0.0.0.0
# 重啟生效
systemctl restart mysqld
# 清空現有 INPUT 鏈相關規則 (謹慎操作)
# iptables -D INPUT -p tcp --dport 3306 -j ACCEPT # 逐條刪除舊規則
# 允許信任 IP
iptables -A INPUT -p tcp -s 192.168.1.4 --dport 3306 -j ACCEPT
iptables -A INPUT -p tcp -s 192.168.1.5 --dport 3306 -j ACCEPT
iptables -A INPUT -p tcp -s 192.168.1.6 --dport 3306 -j ACCEPT
# 允許本機回環 (本地管理、監控)
iptables -A INPUT -p tcp -s 127.0.0.1 --dport 3306 -j ACCEPT
# 拒絕其他所有
iptables -A INPUT -p tcp --dport 3306 -j DROP
# 保存規則
service iptables save # CentOS 6
# 或
iptables-save > /etc/sysconfig/iptables # 通用
iptables -A INPUT -p tcp --dport 3306 ! -s 192.168.1.4 -j DROP
iptables -A INPUT -p tcp --dport 3306 ! -s 192.168.1.5 -j DROP
iptables -A INPUT -p tcp --dport 3306 ! -s 192.168.1.6 -j DROP
# 注意:此寫法順序敏感,建議採用「明確允許 + 預設拒絕」正向邏輯
# 建立永久區域規則
firewall-cmd --permanent --new-service=mysql-custom
firewall-cmd --permanent --service=mysql-custom --set-short="MySQL Custom"
firewall-cmd --permanent --service=mysql-custom --add-port=3306/tcp
firewall-cmd --permanent --service=mysql-custom --add-source=192.168.1.4
firewall-cmd --permanent --service=mysql-custom --add-source=192.168.1.5
firewall-cmd --permanent --service=mysql-custom --add-source=192.168.1.6
firewall-cmd --permanent --add-service=mysql-custom
firewall-cmd --reload
# 驗證
firewall-cmd --list-all
防火牆是網路層防線,資料庫賬號是應用層防線,雙重生效:
-- 僅允許特定 IP 登入
CREATE USER 'app_user'@'192.168.1.4' IDENTIFIED BY 'strong_pass';
CREATE USER 'app_user'@'192.168.1.5' IDENTIFIED BY 'strong_pass';
CREATE USER 'app_user'@'192.168.1.6' IDENTIFIED BY 'strong_pass';
GRANT SELECT,INSERT,UPDATE,DELETE ON app_db.* TO 'app_user'@'192.168.1.%';
FLUSH PRIVILEGES;
# 1. 允許 IP 測試
mysql -h 192.168.1.3 -u app_user -p -e "SELECT 1;"
# 2. 非允許 IP 測試 (應顯示 Connection refused / timeout)
mysql -h 192.168.1.3 -u app_user -p -e "SELECT 1;" # 從 192.168.1.100 執行
# 3. 監控連線嘗試
tail -f /var/log/mysql/error.log # 記錄拒絕連線
# 或 iptables 日誌
iptables -A INPUT -p tcp --dport 3306 -j LOG --log-prefix "MYSQL_DROP: "
| 層級 | 機制 | 配置要點 |
|---|---|---|
| 網路層 | iptables/firewalld 白名單 | bind-address=0.0.0.0 + 明確允許 IP + 預設 DROP |
| 應用層 | MySQL 賬號 Host 限制 | CREATE USER 'user'@'specific_ip' |
| 傳輸層 | SSL/TLS 加密 (可選) | require_secure_transport=ON + 憑證配置 |
「網路層擋無關流量,應用層驗證身份」,纵深防禦才是生產環境資料庫存取控制的正確姿勢。