我想限制正在运行的 Docker 容器的连接。我有一套iptables
规则可以有效地做到这一点。但是,规则集取决于在链之前应用我自己的规则链DOCKER
。
基本上我想要这个结果
Chain FORWARD (policy DROP)
target prot opt source destination
PRE_DOCKER all -- 0.0.0.0/0 0.0.0.0/0 /* Insert before Docker's filtering to apply our own */
DOCKER all -- 0.0.0.0/0 0.0.0.0/0
ACCEPT all -- 0.0.0.0/0 0.0.0.0/0 ctstate RELATED,ESTABLISHED
ACCEPT all -- 0.0.0.0/0 0.0.0.0/0
ACCEPT all -- 0.0.0.0/0 0.0.0.0/0
Chain PRE_DOCKER (policy DROP)
target prot opt source destination
//My own rules go here targeting the DOCKER chain
我无法在系统启动时设置这些规则。我有一个systemd
文件,内容如下
[Unit]
Description=Restore iptables firewall rules
Before=iptables-store.service
Requires=docker.service
After=docker.service
Conflicts=shutdown.target
[Service]
Type=oneshot
ExecStart=/sbin/iptables-restore --noflush /var/lib/iptables/rules-save
[Install]
WantedBy=basic.target
但在启动时,我收到错误
iptables-restore v1.4.21: Couldn't load target `DOCKER':No such file or directory
我认为这意味着 Docker 服务尚未创建其规则。
构建我的单元文件或iptables
规则的正确方法是什么,以便获得所需的输出。
/var/lib/iptables/rules-save
为了完整性,以下是我设置的内容。
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]
:PRE_DOCKER - [0:0]
-I FORWARD -o docker0 -j PRE_DOCKER -m comment --comment "Insert before Docker's filtering to apply our own"
-A PRE_DOCKER ! -i eth0 -o docker0 -j DOCKER -m comment --comment "Anything coming from something other than the public interface send to DOCKER chain"
-A PRE_DOCKER -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT -m comment --comment "Allow connections from established connections"
-A PRE_DOCKER -j DROP -m comment --comment "Drop anything else"
-A INPUT ! -i eth0 -j ACCEPT -m comment --comment "Accept anything coming from something other than the public interface"
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT -m comment --comment "Allow connections from established connections"
COMMIT
答案1
我真的想不通。我猜想 docker.service 创建 iptables DOCKER 链的时间与 systemd 将其视为已完成启动的时间之间存在一些时间问题。
因此我采用轮询方法检查链是否存在,然后才尝试恢复规则。
while ! iptables -n --list DOCKER >/dev/null 2>&1
do
sleep 1;
done
/sbin/iptables-restore --noflush /var/lib/iptables/rules-save