Docker高级教程之智能添加与修改防火墙规则

2020-06-17 06:44:44易采站长站整理

{'Mode': 'internal', 'Container_name': 'test1', 'Source_port': '40031', 'Source_ip': '1.1.1.1/24', 'Local_port': '22', 'Port_mode': 'manual', 'Id': 2, 'Container_ip': '172.16.1.2/24'}

可以看到有2个刚才输入的规则

4、防火墙规则生效

先查看当前宿主机防火墙


[root@docker-test3 code]# iptables -t nat -L -nv
Chain PREROUTING (policy ACCEPT 117K packets, 11M bytes)
pkts bytes target prot opt in out source destination
15431 914K DOCKER all -- * * 0.0.0.0/0 0.0.0.0/0 ADDRTYPE match dst-type LOCAL
Chain INPUT (policy ACCEPT 11906 packets, 716K bytes)
pkts bytes target prot opt in out source destination
Chain OUTPUT (policy ACCEPT 1462 packets, 86817 bytes)
pkts bytes target prot opt in out source destination
24 1424 DOCKER all -- * * 0.0.0.0/0 !127.0.0.0/8 ADDRTYPE match dst-type LOCAL
Chain POSTROUTING (policy ACCEPT 4994 packets, 234K bytes)
pkts bytes target prot opt in out source destination
0 0 MASQUERADE all -- * * 172.16.0.0/16 !172.16.0.0/16
Chain DOCKER (2 references)
pkts bytes target prot opt in out source destination

可以看到只有默认的nat规则,其他的没有

现在使用-e参数来生效


[root@docker-test3 code]# python modify_docker_container_firewall.py test1 -e
config firewall rule is success!

可以看到运行成功


[root@docker-test3 code]# iptables -t nat -L -nv
Chain PREROUTING (policy ACCEPT 53 packets, 5242 bytes)
pkts bytes target prot opt in out source destination
5 300 DOCKER all -- * * 0.0.0.0/0 0.0.0.0/0 ADDRTYPE match dst-type LOCAL
Chain INPUT (policy ACCEPT 5 packets, 300 bytes)
pkts bytes target prot opt in out source destination
Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
0 0 DOCKER all -- * * 0.0.0.0/0 !127.0.0.0/8 ADDRTYPE match dst-type LOCAL
Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
0 0 MASQUERADE all -- * * 172.16.0.0/16 !172.16.0.0/16
Chain DOCKER (2 references)
pkts bytes target prot opt in out source destination
0 0 DNAT tcp -- !ovs2 * 1.1.1.0/24 0.0.0.0/0 tcp dpt:40030 to:172.16.1.2:22
0 0 DNAT tcp -- !ovs2 * 1.1.1.0/24 0.0.0.0/0 tcp dpt:40031 to:172.16.1.2:22

规则已经运行了

在去配置文件里看看


[root@docker-test3 code]# tail -n 12 /etc/sysconfig/iptables
*nat
:PREROUTING ACCEPT [2:269]:POSTROUTING ACCEPT [1739:127286]:OUTPUT ACCEPT [1739:127286]:DOCKER - [0:0]-A PREROUTING -m addrtype --dst-type LOCAL -j DOCKER
-A POSTROUTING -s 172.16.0.0/16 ! -d 172.16.0.0/16 -j MASQUERADE
-A OUTPUT ! -d 127.0.0.0/8 -m addrtype --dst-type LOCAL -j DOCKER
#follow is container:test1 firewall rule