我有一个运行几个docker的容器的主机。
这个主机有几个networking接口,我的目标是使一些暴露的端口从容器只能通过某些接口访问,并阻止访问他人。
我想使用主机的iptables的。
但它不可能简单地做到:
iptables -I INPUT -i vlan2 --dport 80 -j DROP
因为数据包是通过预先路由转发的。
iptables -t nat -L PREROUTING 2 Chain PREROUTING (policy ACCEPT) target prot opt source destination DOCKER all -- anywhere anywhere ADDRTYPE match dst-type LOCAL Chain DOCKER (2 references) target prot opt source destination DNAT tcp -- anywhere anywhere tcp dpt:mysql to:172.17.0.2:33066 DNAT tcp -- anywhere anywhere tcp dpt:http to:172.17.0.4:80
有两个暴露的端口80和3306到不同的容器,我想使其无法从接口vlan2访问
我加了这个之后:
iptables -I FORWARD -i vlan2 -p tcp --dport 80 -j REJECT
Web服务器停止工作,但
iptables -I FORWARD -i vlan2 -p tcp --dport 3306 -j REJECT
不要阻止连接到MySQL,我仍然能够连接。 而tcpdumpcertificate了这一点:
tcpdump -n -i vlan2 port 3306 tcpdump: verbose output suppressed, use -v or -vv for full protocol decode listening on vlan2, link-type EN10MB (Ethernet), capture size 262144 bytes 22:48:13.066636 IP 3.2.2.2.47259 > 1.1.2.3.3306: Flags [S], seq 3619220560, win 29200, options [mss 1460,sackOK,TS val 90183390 ecr 0,nop,wscale 7], length 0 22:48:13.066740 IP 1.1.2.3.3306 > 3.2.2.2.47259: Flags [S.], seq 2743923517, ack 3619220561, win 28960, options [mss 1460,sackOK,TS val 10989883 ecr 90183390,nop,wscale 7], length 0
我不明白这两个规则的区别。
如何使用主机的iptables来防止访问容器
问题是你的nat表的PREROUTING链中的NAT规则将主机的端口3306为172.17.0.2:而不是172.17.0.2:因此过滤表的FORWARD链中的规则不匹配任何东西它会尝试丢弃转发到目标端口3306stream量。