我的防火墙阻止从docker集装箱到外部的networking连接

对我来说这是一个非常标准的设置,我有一个运行docker和ufw作为我的防火墙的Ubuntu机器。

如果启用了防火墙,则docker实例无法连接到外部

$ docker run -i -t ubuntu /bin/bash WARNING: Docker detected local DNS server on resolv.conf. Using default external servers: [8.8.8.8 8.8.4.4] root@d300c5f17207:/# apt-get update Err http://archive.ubuntu.com precise InRelease 0% [Connecting to archive.ubuntu.com] W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/precise/InRelease W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/precise/Release.gpg Temporary failure resolving 'archive.ubuntu.com' W: Some index files failed to download. They have been ignored, or old ones used instead. 

这里是ufw日志显示从docker容器阻塞的连接。

 $ sudo tail /var/log/ufw.log Jun 30 15:41:56 localhost kernel: [61609.503199] [UFW BLOCK] IN=testbr0 OUT=eth0 PHYSIN=veth8Rj8Nh MAC=fe:ff:ed:42:b0:01:0a:7c:42:7c:a6:72:08:00 SRC=172.16.42.2 DST=8.8.8.8 LEN=64 TOS=0x00 PREC=0x00 TTL=63 ID=14886 DF PROTO=UDP SPT=60192 DPT=53 LEN=44 Jun 30 15:42:01 localhost kernel: [61614.500867] [UFW BLOCK] IN=testbr0 OUT=eth0 PHYSIN=veth8Rj8Nh MAC=fe:ff:ed:42:b0:01:0a:7c:42:7c:a6:72:08:00 SRC=172.16.42.2 DST=8.8.4.4 LEN=64 TOS=0x00 PREC=0x00 TTL=63 ID=16137 DF PROTO=UDP SPT=44812 DPT=53 LEN=44 Jun 30 15:42:06 localhost kernel: [61619.498516] [UFW BLOCK] IN=testbr0 OUT=eth0 PHYSIN=veth8Rj8Nh MAC=fe:ff:ed:42:b0:01:0a:7c:42:7c:a6:72:08:00 SRC=172.16.42.2 DST=8.8.8.8 LEN=64 TOS=0x00 PREC=0x00 TTL=63 ID=14887 DF PROTO=UDP SPT=60192 DPT=53 LEN=44 

我曾尝试使用IP添加规则。

 $ sudo ufw allow in from 172.16.42.2 $ sudo ufw allow out from 172.16.42.2 

并没有改变仍然被阻止。

我怎么能esily允许从容器到ufw规则外的所有连接?

也许这是由于目前的版本,但目前的答案不适用于我的系统(基于Ubuntu镜像的Docker 0.7.2)。

Docker官方文档中解释了这个解决scheme。

对于懒惰的人:

  • 编辑/etc/default/ufwDEFAULT_FORWARD_POLICY的值更改为"ACCEPT"
  • 重新加载与[sudo] ufw reload

这可以确保ufw将您的stream量转发到Docker的桥接networking(就我目前对这些事物的理解而言)。

这对我来说是固定的:

  ufw allow in on docker0 

编辑/etc/ufw/before.rules如下:

*filter部分,在所需行的第一个块之后,添加:

 # docker rules to enable external network access from the container # forward traffic accross the bridge -A ufw-before-forward -i docker0 -j ACCEPT -A ufw-before-forward -i testbr0 -j ACCEPT -A ufw-before-forward -m state --state RELATED,ESTABLISHED -j ACCEPT 

在文件末尾, 表示COMMIT的行之后 ,添加以下部分:

 *nat :POSTROUTING ACCEPT [0:0] -A POSTROUTING -s 172.16.42.0/8 -o eth0 -j MASQUERADE # don't delete the 'COMMIT' line or these rules won't be processed COMMIT 

保存文件后,用sudo ufw disable && sudo ufw enable重新启动ufw

你确定是否允许有关港口的连接?