是否可以让 Docker 容器访问主机开放的端口?具体来说,我在主机上运行了 MongoDB 和 RabbitMQ,我想在 Docker 容器中运行一个进程来监听队列并(可选)写入数据库。
我知道我可以将一个端口从容器转发到主机(通过 -p 选项)并从 Docker 容器内连接到外部世界(即互联网),但我不想公开 RabbitMQ以及从主机到外部世界的 MongoDB 端口。
编辑:一些澄清:
Starting Nmap 5.21 ( http://nmap.org ) at 2013-07-22 22:39 CEST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00027s latency).
PORT STATE SERVICE
6311/tcp open unknown
joelkuiper@vps20528 ~ % docker run -i -t base /bin/bash
root@f043b4b235a7:/# apt-get install nmap
root@f043b4b235a7:/# nmap 172.16.42.1 -p 6311 # IP found via docker inspect -> gateway
Starting Nmap 6.00 ( http://nmap.org ) at 2013-07-22 20:43 UTC
Nmap scan report for 172.16.42.1
Host is up (0.000060s latency).
PORT STATE SERVICE
6311/tcp filtered unknown
MAC Address: E2:69:9C:11:42:65 (Unknown)
Nmap done: 1 IP address (1 host up) scanned in 13.31 seconds
我必须这样做才能在容器中获得任何互联网连接:My firewall is blocking network connections from the docker container to outside
编辑:最终我使用 pipework 创建了一个自定义桥接器。并让服务监听网桥 IP。我采用了这种方法,而不是让 MongoDB 和 RabbitMQ 在 docker 桥上监听,因为它提供了更大的灵 active 。
最佳答案
一个简单但相对不安全的方法是使用 --net=host
选项来 docker run
。
此选项使容器使用主机的网络堆栈。然后,您只需使用“localhost”作为主机名即可连接到主机上运行的服务。
这更容易配置,因为您不必将服务配置为接受来自 docker 容器 IP 地址的连接,也不必告诉 docker 容器特定的 IP 地址或主机名来连接到,只是一个港口。
例如,您可以通过运行以下命令对其进行测试,该命令假定您的图像名为 my_image
,您的图像包含 telnet
实用程序,并且您的服务要连接的端口是 25:
docker run --rm -i -t --net=host my_image telnet localhost 25
如果您考虑这样做,请参阅此页面上的安全注意事项:
https://docs.docker.com/articles/networking/
上面写着:
--net=host -- Tells Docker to skip placing the container inside of a separate network stack. In essence, this choice tells Docker to not containerize the container's networking! While container processes will still be confined to their own filesystem and process list and resource limits, a quick ip addr command will show you that, network-wise, they live “outside” in the main Docker host and have full access to its network interfaces. Note that this does not let the container reconfigure the host network stack — that would require --privileged=true — but it does let container processes open low-numbered ports like any other root process. It also allows the container to access local network services like D-bus. This can lead to processes in the container being able to do unexpected things like restart your computer. You should use this option with caution.
https://stackoverflow.com/questions/17770902/