Ubuntu 20.04下能否让UFW阻止Docker容器暴露的端口?
问题:如何配置UFW阻止Docker意外暴露的端口
背景
在Ubuntu 20.04服务器环境中,测试发现将Docker容器端口暴露为0.0.0.0:8101:80时,尽管UFW设置为默认拒绝入站,外部设备仍可访问该端口。我通常会把代理后端的Docker端口配置为127.0.0.1:port:port,但希望UFW能阻止这类因修改Docker Compose文件时遗漏127.0.0.1而导致的端口暴露。
系统环境
- 操作系统:Ubuntu 20.04
- UFW版本:0.36
- 代理:Nginx 1.22.1
- Docker版本:23.0.6
- Docker Compose版本:2.17.3
测试设置
UFW规则
$ Status: active Logging: on (high) Default: deny (incoming), allow (outgoing), deny (routed) New profiles: skip To Action From -- ------ ---- OpenSSH ALLOW IN Anywhere Nginx Full ALLOW IN Anywhere 8103/tcp ALLOW IN Anywhere 8104/tcp ALLOW IN Anywhere 8107/tcp DENY IN Anywhere 8108/tcp DENY IN Anywhere OpenSSH (v6) ALLOW IN Anywhere (v6) Nginx Full (v6) ALLOW IN Anywhere (v6) 8103/tcp (v6) ALLOW IN Anywhere (v6) 8104/tcp (v6) ALLOW IN Anywhere (v6) 8107/tcp (v6) DENY IN Anywhere (v6) 8108/tcp (v6) DENY IN Anywhere (v6)
监听端口配置
- 监听8101的Docker容器:service1 配置为
0.0.0.0:8101->80/tcp(Compose中默认写8101:80) - 监听8102的Docker容器:service2 配置为
127.0.0.1:8102->80/tcp - 用
nc -l [port]手动监听8103、8105及8107端口
外部客户端测试结果
| 端口 | 防火墙规则 | 监听状态 | nc -vz DOMAIN PORT结果 |
|---|---|---|---|
| 8101 | 默认规则 | Docker全局监听 | [domain] [IP] 8101 (ldoms-migr) open |
| 8102 | 默认规则 | Docker本地监听 | [domain] [IP] 8102 (kz-migr): Connection timed out |
| 8103 | 允许入站 | nc -l [port] | [domain] [IP] 8103 open |
| 8104 | 允许入站 | 无监听 | [domain] [IP] 8104: Connection refused |
| 8105 | 默认规则 | nc -l [port] | [domain] [IP] 8105: Connection timed out |
| 8106 | 默认规则 | 无监听 | [domain] [IP] 8106: Connection timed out |
| 8107 | 拒绝入站 | nc -l [port] | [domain] [IP] 8107: Connection timed out |
| 8108 | 拒绝入站 | 无监听 | [domain] [IP] 8108: Connection timed out |
结果解读
- Open:已通过防火墙且端口处于监听状态(8101、8103)
- Connection timed out:被防火墙拦截(8102、8105、8106、8107、8108)
- Connection refused:已通过防火墙但端口未监听(8104)
提问
能否配置UFW,防止他人修改Docker Compose文件时未添加127.0.0.1导致端口暴露被外部访问?
内容的提问来源于stack exchange,提问作者tobule
相关产品推荐
相关产品推荐

