將 Docker 容器的訪問許可權限制為一組 IP

首先,如果需要,安裝 ipset 。請參閱你的發行版以瞭解如何操作。舉個例子,這是 Debian 類發行版的命令。

$ apt-get update
$ apt-get install ipset

然後建立一個配置檔案來定義一個 ipset,其中包含要為其開啟 Docker 容器訪問許可權的 IP。

$ vi /etc/ipfriends.conf
# Recreate the ipset if needed, and flush all entries
create -exist ipfriends hash:ip family inet hashsize 1024 maxelem 65536
flush
# Give access to specific ips
add ipfriends XXX.XXX.XXX.XXX
add ipfriends YYY.YYY.YYY.YYY

載入此 ipset。

$ ipset restore < /etc/ipfriends.conf

確保你的 Docker 守護程式正在執行:輸入以下命令後不應顯示錯誤。

$ docker ps

你已準備好插入 iptables 規則。你必須尊重訂單。

// All requests of src ips not matching the ones from ipset ipfriends will be dropped.
$ iptables -I DOCKER -i ext_if -m set ! --match-set ipfriends src -j DROP
// Except for requests coming from a connection already established.
$ iptables -I DOCKER -i ext_if -m state --state ESTABLISHED,RELATED -j ACCEPT

如果要建立新規則,則需要在插入新規則之前刪除已新增的所有自定義規則。

$ iptables -D DOCKER -i ext_if -m set ! --match-set ipfriends src -j DROP
$ iptables -D DOCKER -i ext_if -m state --state ESTABLISHED,RELATED -j ACCEPT