如何在Docker在启动时设置自己的规则后添加iptables规则?

我想限制连接到正在运行的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服务尚未创build其规则。

什么是正确的方式来构build我的单位文件或我的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 

我真的不知道这一点。 我猜这是docker.service创buildiptables DOCKER链时与systemd将其视为完成时的时间问题。

于是我采取了一种轮询方法,检查链条是否存在,然后试图恢复规则。

 while ! iptables -n --list DOCKER >/dev/null 2>&1 do sleep 1; done /sbin/iptables-restore --noflush /var/lib/iptables/rules-save