Memcached 無認證機制,默認監聽所有接口,以高權限運行。暴露公網即意味著:
stats items + get key 遍歷所有緩存flush_all 導致緩存雪崩# 僅內網 IP
memcached -d -m 1024 -u memcached -l 192.168.0.200 -p 11211 -c 1024 -P /var/run/memcached.pid
# 僅本地回環(Web 與 Cache 同機)
memcached -d -m 1024 -u memcached -l 127.0.0.1 -p 11211 -c 1024 -P /var/run/memcached.pid
原則:Web 服務器通過內網 IP 訪問 Cache,公網網卡完全不監聽 11211。
# iptables 示例:僅允許 Web 服務器 192.168.0.2 訪問
iptables -F
iptables -P INPUT DROP
iptables -A INPUT -p tcp -s 192.168.0.2 --dport 11211 -j ACCEPT
iptables -A INPUT -p udp -s 192.168.0.2 --dport 11211 -j ACCEPT
# 持久化
service iptables save # CentOS 6
iptables-save > /etc/sysconfig/iptables # CentOS 7
同理適用 firewalld、ufw、云廠商安全組。
-u memcached(非 root),限制進程權限-U 0 關閉 UDP-c 1024 防連接耗盡-S 開啟,需客端庫支持curr_connections、cmd_get/set 突增告警prefix:module:key 防止業務誤讀/覆蓋# 外部嘗試連接(應失敗)
telnet public_ip 11211
# 內網正常連接
telnet 192.168.0.200 11211
stats
quit
iptables -A INPUT -p tcp --dport 11211 -j DROP 切斷flush_all 清理可能被污染的緩存網絡隔離是核心,防火牆是兜底。Memcached 設計初衷是可信內網高性能緩存,切勿暴露公網,切勿存儲未加密敏感數據,切勿以 root 運行。