docker-py icon indicating copy to clipboard operation
docker-py copied to clipboard

docker (2.0.2) - Unable to publish ports with containers.run()

Open jamesongithub opened this issue 8 years ago • 4 comments

Seem to be unable to publish ports to the host w/ docker run. Perhaps I'm doing something wrong

        conatiner = client.containers.run(
            image='mongo:3.2.11',
            detach=True,
            name='name',
            network_mode='host',
            ports={
                '{}/tcp'.format(27017): ('127.0.0.1', 30000)
            },
            publish_all_ports=True
        )
            },
            "NetworkMode": "host",
            "PortBindings": {
                "27017/tcp": [
                    {
                        "HostIp": "127.0.0.1",
                        "HostPort": "30000"
                    }
                ]
            },
...
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "e9f4cd55c0cefbdf485733c297a4209d24a427803da1a06c0e1a632d5802f311",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/default",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "",
            "Gateway": "",

jamesongithub avatar Feb 13 '17 22:02 jamesongithub

Any luck with this? I'm having the same issue.

ChrisTimperley avatar Aug 09 '17 17:08 ChrisTimperley

I have a similar problem with docker-py (running on Docker for Mac, but also tried it on Ubuntu 16.04). Basically dockerpy won't show the bindings docker provide when expose_all_ports=True is used as run parameter. I took a look at https://github.com/docker/docker-py/issues/513 and read this guide and did some tests. In order to summarize what I did, I wrote this short notebook: https://gist.github.com/D3f0/e5913d5d3ab8fe7c594fd9d1e6743a9a

Ports are exposed but docker-py won't show them.

D3f0 avatar Sep 04 '17 15:09 D3f0

I found that there's a way to get the assigned ports from Python when you use expose_all_ports=True, there's a way to call inspect and get a dict from docker-py:

container = client.containers.run(image="some_image_with_expose", publish_all_ports=True, detach=True)
client.api.inspect_container(container.id)["NetworkSettings"]["Ports"]

this will returns something like:

{'3000/tcp': [{'HostIp': '0.0.0.0', 'HostPort': '32780'}]}

A not recommended dict comprehension I used in my environment:

{dock_port.split('/')[0]: host_port[0]['HostPort'] for dock_port, host_port in exposed.items()}
# -> {'3000': '32780'}

D3f0 avatar Sep 04 '17 15:09 D3f0

Any updates on this issue? Still facing the same in 2022? Although it is workable with the workaround provided by @D3f0 . But cant we have something official?

sajjad006 avatar Mar 30 '22 17:03 sajjad006