【问题标题】:What is the equivalent command for docker port CONTAINER in docker-pydocker-py 中 docker port CONTAINER 的等效命令是什么
【发布时间】:2020-07-11 23:54:17
【问题描述】:

我尝试使用 docker-py 自动化 docker 服务器。需要使用 python 检查主机 URL 是否正在 ping。因此,我需要在 python 中为docker port container 提供一个等效命令
docker port container_id

import docker
client = docker.from_env()
print(client.port('c03ebfb53a7d', 80))

【问题讨论】:

  • 试试port
  • 这是您的建议吗? client = docker.from_env() print(client.port('c03ebfb53a7d', 80))
  • 基于源码,是的。
  • 但它返回 'DockerClient' 对象没有属性 'port'
  • 能给个demo吗

标签: python docker dockerpy


【解决方案1】:

当通过docker.DockerClient(base_url='unix://var/run/docker.sock')docker.from_env()实例化DockerClient对象时,在构造函数APIClient object is instantiated内部:

def __init__(self, *args, **kwargs):
    self.api = APIClient(*args, **kwargs)

APIClient itself is inheriting a bunch of classes:

class APIClient(
    requests.Session,
    BuildApiMixin,
    ConfigApiMixin,
    ContainerApiMixin,
    DaemonApiMixin,
    ExecApiMixin,
    ImageApiMixin,
    NetworkApiMixin,
    PluginApiMixin,
    SecretApiMixin,
    ServiceApiMixin,
    SwarmApiMixin,
    VolumeApiMixin)

它继承的一个类是ContainerApiMixin,它公开了与容器交互的方法,类似于docker container CLI。

如您所见,您可以通过 CLI 执行的所有操作都可以通过 DockerClient 对象内的 api 对象访问。

所以,你的问题的答案是:

client.api.port('<container_id>', <port>)

资源source code

【讨论】:

  • 除此之外,我还需要验证URL是否可达。我
  • 你的意思是像this这样的东西吗?还是有什么不同?
  • host=cli.port(id, 80) port=host[0]['HostPort'] ip=host[0]['HostIp'] server_ip=ip+':'+port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) rep = os.system('ping ' + server_ip) if rep == 0: print ('server is up') else: print ('server is down')
  • 我需要检查它是否可达这是我的最终目的
  • 代码未显示任何语法错误。但它总是显示服务器错误
猜你喜欢
  • 2020-07-10
  • 1970-01-01
  • 2013-07-20
  • 1970-01-01
  • 1970-01-01
  • 2015-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多