简体   繁体   English

在 docker-py 中暴露网络上的端口

[英]Exposing ports on a network in docker-py

Using the Python docker client docker-py , how do you create a container which is attached to a specific network, and exposes a specific port?使用 Python docker 客户端docker-py ,您如何创建一个附加到特定网络并公开特定端口的容器?

Ie the compose file may look like this:即撰写文件可能如下所示:

  foo:
    ...
    expose:
      - "1234"
    networks:
      - my-network

We expose a port within my-network, without mapping it to the host.我们在 my-network 中公开一个端口,而不将其映射到主机。

Using docker-py's high level containers.run method only allows for Port Mappings (ie publishing ports externally) with it's ports kwarg, rather than simply exposing the port internally.使用 docker-py 的高级container.run方法只允许使用它的ports kwarg 进行端口映射(即在外部发布端口),而不是简单地在内部公开端口。
docker-py's low-level create_container method doesn't accept a simple network name to use. docker-py 的低级 create_container 方法不接受使用简单的网络名称。

How can the above compose file be replicated using docker-py?如何使用 docker-py 复制上述 compose 文件?

Thanks谢谢

"Expose" as a verb hasn't meant much since Docker introduced multiple named Docker-internal networks.自从 Docker 引入了多个命名的 Docker 内部网络以来,“暴露”作为动词并没有多大意义。 You can delete this setting from your docker-compose.yml file and it won't affect anything;你可以从你docker-compose.yml文件中删除这个设置,它不会影响任何东西; other services on the same network will still be able to reach yours.同一网络上的其他服务仍然可以访问您的服务。 That is, it should be enough to run也就是说,它应该足以运行

client.containers.run('my-image', network: 'my-network')

From what I can tell the docker-py library never supported this option (even during the time when --link was the only way to connect containers, manual --expose was never that useful).据我所知,docker-py 库从未支持此选项(即使在--link是连接容器的唯一方法的时候,手动--expose也从来没有那么有用)。 docker/docker-py#2242 asks a similar question, with a similar answer. docker/docker-py#2242提出了一个类似的问题,并给出了类似的答案。

正如您在此处看到的,您可以传递主机 ip,而无需主机端口,这将使您的愿望成真。

docker.utils.create_host_config(port_bindings={1111: ('127.0.0.1',)})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM