menu Chancel's blog
rss_feed
Chancel's blog
有善始者实繁,能克终者盖寡。

ufw无法禁用Docker端口访问问题

作者:Chancel Yang, 创建:2023-01-03, 字数:1945, 已阅:32, 最后更新:2023-01-03

这篇文章更新于 451 天前,文中部分信息可能失效,请自行甄别无效内容。

在机器上安装Docker之后,运行一个MySQL容器

Bash
sudo docker run mysql:5.7 -p 3306:3306

使用ufw设置除了内网机器172.16.0.100以外,拒绝任何网络访问

Bash
sudo ufw default deny incoming
sudo ufw allow from 172.16.0.100 to any port 3306

经过测试验证发现无效,其他机器依旧可以正常访问3306端口,查询iptables规则

Bash
~ ➤ sudo iptables -L -n                                                                                                                  
[sudo] password for chancel: 
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         

Chain FORWARD (policy DROP)
target     prot opt source               destination         
DOCKER-USER  all  --  0.0.0.0/0            0.0.0.0/0     
DOCKER-ISOLATION-STAGE-1  all  --  0.0.0.0/0            0.0.0.0/0      
...

Chain DOCKER-ISOLATION-STAGE-1 (1 references)
target     prot opt source               destination         
DOCKER-ISOLATION-STAGE-2  all  --  0.0.0.0/0            0.0.0.0/0           
DOCKER-ISOLATION-STAGE-2  all  --  0.0.0.0/0            0.0.0.0/0           
DOCKER-ISOLATION-STAGE-2  all  --  0.0.0.0/0            0.0.0.0/0           
DOCKER-ISOLATION-STAGE-2  all  --  0.0.0.0/0            0.0.0.0/0           
RETURN     all  --  0.0.0.0/0            0.0.0.0/0           


Chain DOCKER-USER (1 references)
target     prot opt source               destination         
RETURN     all  --  0.0.0.0/0            0.0.0.0/0

发现DOCKER有自己的一套iptables规则,在官方文档Docker and iptables有着如下描述

All of Docker’s iptables rules are added to the DOCKER chain. Do not manipulate this chain manually. If you need to add rules which load before Docker’s rules, add them to the DOCKER-USER chain. These rules are applied before any rules Docker creates automatically.

所以ufwfirewalld设置的规则对Docker来说是无效的,如果要实现控制容器的外部访问,可以对DOCKER-USER链进行操作,如下

Bash
iptables -I DOCKER-USER -i eth0 ! -s 172.16.0.100 -j DROP

其中eth0是你的外部接口名称,使用ip a可以查询外部接口名称


[[replyMessage== null?"发表评论":"发表评论 @ " + replyMessage.m_author]]

account_circle
email
web_asset
textsms

评论列表([[messageResponse.total]])

还没有可以显示的留言...
[[messageItem.m_author]] [[messageItem.m_author]]
[[messageItem.create_time]]
[[getEnviron(messageItem.m_environ)]]
[[subMessage.m_author]] [[subMessage.m_author]] @ [[subMessage.parent_message.m_author]] [[subMessage.parent_message.m_author]]
[[subMessage.create_time]]
[[getEnviron(messageItem.m_environ)]]