gpt4 book ai didi

UFW 阻止了 Docker 本地主机连接

转载 作者:行者123 更新时间:2023-12-02 20:33:51 28 4
gpt4 key购买 nike

情况

我正在尝试学习如何在本地机器上使用 docker。本地计算机设置为仅通过 VPN 路由流量。默认的 UFW 策略是 DENY所有传入和传出流量(通过 VPN 除外)。

问题

当我尝试启动 Docker 容器时 docker container run -p 80:80 nginx ,我无法在浏览器中使用 localhost 连接到 nginx 容器。

但是,我可以通过telnet连接到本地的nginx容器

$ telnet localhost 80
Trying 127.0.0.1...
Connected to localhost.

我知道 UFW 可能导致这种情况的原因是,一旦我禁用 UFW,我就可以毫无问题地连接到浏览器中的 localhost。

问题

当 UFW 设置为拒绝所有连接时,如何从浏览器连接到本地 nginx 容器?

最佳答案

我找到了解决我的问题的方法。

解决方案

ufw allow out on docker0 from 172.17.0.0/16

由于我知道 nginx 使用的特定端口,因此我也可以通过这样做使这条规则更严格
ufw allow out on docker0 from 172.17.0.0/16 port 80 proto tcp

解释

Docker 为容器创建了一个新接口(interface),你可以通过运行 ifconfig 来查看它。 :
docker0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
inet 172.17.0.1 netmask 255.255.0.0 broadcast 172.17.255.255
ether 02:42:a4:5e:e9:9c txqueuelen 0 (Ethernet)
RX packets 87 bytes 17172 (17.1 KB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 117 bytes 14956 (14.9 KB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

此接口(interface)通过 172.17.xxx.xxx 路由流量。你可以阅读更多关于我如何找到网络掩码 here .

这为我们提供了编写规则所需的所有信息。如果您在不同的端口上发布容器,您可以通过执行以下操作来检查端口号和协议(protocol):
  • 查找您的容器 ID docker container ls
  • 找到您的容器港口docker container port {id}
  • 关于UFW 阻止了 Docker 本地主机连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54059174/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com