pythondockerdockerpy

What is the equivalent command for docker port CONTAINER in docker-py


I trying to automate a docker server using docker-py. Need to check whether the host URL is pinging or not using python. Hence I need an equivalent command in python for docker port container.
docker port container_id

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

Solution

  • When instantiating DockerClient object whether through docker.DockerClient(base_url='unix://var/run/docker.sock') or docker.from_env(), inside constructor 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)
    

    One of the classes it inherits is ContainerApiMixin that exposes methods for interacting with containers, similar to docker container CLI.

    As you can see, everything you can do through CLI is accessible through api object inside DockerClient object.

    So, the answer to your question is:

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

    Resource: source code