如何从Docker容器获取主机上映射的端口? [英] How to get the mapped port on host from a docker container?

查看:657
本文介绍了如何从Docker容器获取主机上映射的端口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在不同的主机上的一些docker容器中运行一个任务。我已经编写了一个管理应用程序来管理容器(启动任务,停止任务,获取状态等)。一旦容器启动,它将向经理发送一个http请求,其地址和端口,所以管理者将知道如何管理容器。

I want to run a task in some docker containers on different hosts. And I have written a manager app to manage the containers(start task, stop task, get status, etc...) . Once a container is started, it will send an http request to the manager with its address and port, so the manager will know how to manage the container.

由于可能在同一主机上运行多个容器,它们将被映射到不同的端口。要在我的经理注册一个容器,我必须知道每个容器映射到哪个端口。

Since there may be more than one containers running on a same host, they would be mapped to different ports. To register a container on my manager, I have to know which port each container is mapped to.

如何获取码头集装箱?

How can I get the mapped port inside a docker container?

这里有一个解决方案如何知道docker容器的主机映射端口?但是如果使用-P运行容器,则不适用。由于这个问题是在1年多前提出的,所以我想知道在Docker中添加一个新功能可以解决这个问题。

There's an solution here How do I know mapped port of host from docker container? . But it's not applicable if I run container with -P. Since this question is asked more than 1 year ago, I'm wondering maybe there's a new feature added to docker to solve this problem.

推荐答案


一旦容器启动,它将向管理员发送一个http请求,其地址和端口

Once a container is started, it will send an http request to the manager with its address and port

这不会工作。从一个容器里面你不能知道一个容器端口映射到哪个码头主机端口。

This isn't going to be working. From inside a container you cannot figure out to which docker host port a container port is mapped to.

我可以考虑哪些工作,最接近你的描述是使容器打开与管理器的websocket连接。这样的连接将允许您的管理器和容器之间的两种方式通信,同时仍然通过HTTP。

What I can think about which would work and be the closest to what you describe is making the container open a websocket connection to the manager. Such a connection would allow two ways communication between your manager and container while still being over HTTP.

您尝试实现的内容称为服务发现。已经有适用于Docker的服务发现工具。

What you are trying to achieve is called service discovery. There are already tools for service discovery that work with Docker. You should pick one of them instead of trying to make your own.

请参阅:

  • etcd
  • consul
  • zookeeper

如果你真的想实现你的服务发现系统的一个方法是让您的经理使用 docker事件 命令(或其中一个码头客户端图书馆)。这将使您的经理能够收到容器创建/删除的通知,无需在容器侧进行。

If you really want to implement your service discovery system, one way to go is to have your manager use the docker event command (or one of the docker client librairies). This would enable your manager to get notified of containers creations/deletions with nothing to do on the container side.

然后查询docker主机以确定映射的端口通过 码头港口

Then query the docker host to figure out the ports that are mapped to your containers with docker port.

这篇关于如何从Docker容器获取主机上映射的端口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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