Docker 同一网络中的容器无法相互通信

Docker containers in the same network cannot communicate with each other

我是第一次在 Centos 中使用 Docker。

在部署两个容器时,我发现我的互联网有路由问题,然后我发现我什至无法让它们相互通信(尽管在默认 bridge 网络上).

在一个容器中会发生这种情况:

/ # ip a | grep 172
    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
/ # ping 172.17.0.3
PING 172.17.0.3 (172.2.0.3): 56 data bytes
^C
--- 172.17.0.3 ping statistics ---
3 packets transmitted, 0 packets received, 100% packet loss

另一个,同样的行为:

/ # ip a | grep 172
    inet 172.17.0.3/16 brd 172.17.255.255 scope global eth0
/ # ping 172.17.0.2
PING 172.17.0.2 (172.2.0.2): 56 data bytes
^C
--- 172.2.0.2 ping statistics ---
3 packets transmitted, 0 packets received, 100% packet loss

并且他们在同一个网络中:

$ docker inspect 91767dd3adfa | grep -i networkid
                    "NetworkID": "d36d28507f9cc3f6c40437330af3778c117d303e106de0b3b43ad7919d2791c7",
$ docker inspect a393490d8d02 | grep -i networkid
                    "NetworkID": "d36d28507f9cc3f6c40437330af3778c117d303e106de0b3b43ad7919d2791c7",
$ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
d36d28507f9c        bridge              bridge              local
f32f4c8d6187        host                host                local
5693790b1713        none                null                local

为什么会这样?我在 Ubuntu 和 MacOS 中使用过 Docker,它可以无缝运行。

尝试创建一个新网络并将容器关联到该网络,默认网络 docker "bridge" 不能像其他手动创建的网络那样工作

我看到的完全是你的错误,机器的IP在网络172.17.0.0/16 但是您正在尝试 ping 172.2.0.0/16 上的机器,因此它将无法正常工作,因为具有此网络的机器超出范围,而且现有机器的 IP 不是您要向其发送 ping 请求的机器。

我找到了解决方案。

启用防火墙以允许连接进出 docker0 网络。

这是使用以下命令执行的:

iptables -I INPUT -s <network> -i docker0 -m comment --comment "00015 input on docker0" -j ACCEPT
# accept any package coming from the network to docker0 interface
iptables -I FORWARD -m comment --comment "00010 conntrack on forward" -m state --state RELATED,ESTABLISHED -j ACCEPT
# maintain any 'session' or link to be able to return packages fro meth0 to docker0 (answer). Very tightened to the existance of a 'nat', otherwise this entry does not have any impact
iptables -I FORWARD -s <network> -i docker0 -o eth0 -m comment --comment "00011 forward to eth0 from docker0" -j ACCEPT
#forward packages
iptables -t nat -I POSTROUTING -s  <network> -o eth0 -m comment --comment "00013 masquerade on eth0 from docker0"
-j MASQUERADE
# create nat in order for any package that goes out of the host to be able to come back using the ip of the host and after the ip of the container