将主机端口转发到docker容器 [英] Forward host port to docker container

查看:217
本文介绍了将主机端口转发到docker容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以让Docker容器访问主机打开的端口?具体来说,我在主机上运行MongoDB和RabbitMQ,我想在Docker容器中运行一个进程来侦听队列,并且(可选地)写入数据库。

Is it possible to have a Docker container access ports opened by the host? Concretely I have MongoDB and RabbitMQ running on the host and I'd like to run a process in a Docker container to listen to the queue and (optionally) write to the database.

我知道我可以从容器转发到主机(通过-p选项),并且我可以连接到外部世界(即互联网) Docker容器,但我不想将RabbitMQ和MongoDB端口从主机暴露给外界。

I know that I can forward from the container to the host (via the -p option) and I have an connection to the outside world (i.e. internet) from within the Docker container but I'd like to not expose the RabbitMQ and MongoDB ports from the host to the outside world.

编辑:一些澄清:

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

我不得不做这个技巧来获取任何互联网连接使用容器:我的防火墙正在阻止从Docker容器到外部的网络连接

I had to do this trick to get any internet connection withing the container: My firewall is blocking network connections from the docker container to outside

编辑:最后,我使用管道工作,并让服务在桥IP上听。我用这种方法,而不是让MongoDB和RabbitMQ在码头桥上听,因为它提供了更多的灵活性。

EDIT: Eventually I went with creating a custom bridge using pipework and having the services listen on the bridge IP's. I went with this approach instead of having MongoDB and RabbitMQ listen on the docker bridge because it gives more flexibility.

推荐答案

您的docker主机向所有容器公开适配器。假设你是最近的ubuntu,你可以运行

Your docker host exposes an adapter to all the containers. Assuming you are on recent ubuntu, you can run

ip addr

这将给您一个网络适配器列表,其中一个将看起来像

This will give you a list of network adapters, one of which will look something like

3: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP
link/ether 22:23:6b:28:6b:e0 brd ff:ff:ff:ff:ff:ff
inet 172.17.42.1/16 scope global docker0
inet6 fe80::a402:65ff:fe86:bba6/64 scope link
   valid_lft forever preferred_lft forever

您将需要告诉兔子/ mongo绑定该IP(172.17.42.1)。之后,您应该可以从容器内打开172.17.42.1的连接。

You will need to tell rabbit/mongo to bind to that IP (172.17.42.1). After that, you should be able to open connections to 172.17.42.1 from within your containers.

这篇关于将主机端口转发到docker容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆