Skip to content

Attribute "ports" on Container Does Not Include Ports #2681

@ClaytonNorthey92

Description

@ClaytonNorthey92

I am running a (postgres) container using the Docker Python SDK.

I am trying to bind a random host port to port 5432 in the container. According to the documentation:

None, to assign a random host port. For example, {'2222/tcp': None}.

This is my setup:

import docker


if __name__ == '__main__':
    client = docker.from_env()
    container = client.containers.run('postgres:9.6', None,
        detach=True,
        ports= {
            '5432/tcp': None # bind to a random port
        },
        network_mode='bridge',
        environment={
            'POSTGRES_PASSWORD': 'password'
        },
    )

    print(container.attrs['NetworkSettings'])
    print(container.ports)

The output from the print statements:

{'Bridge': '', 'SandboxID': '', 'HairpinMode': False, 'LinkLocalIPv6Address': '', 'LinkLocalIPv6PrefixLen': 0, 'Ports': {}, 'SandboxKey': '', 'SecondaryIPAddresses': None, 'SecondaryIPv6Addresses': None, 'EndpointID': '', 'Gateway': '', 'GlobalIPv6Address': '', 'GlobalIPv6PrefixLen': 0, 'IPAddress': '', 'IPPrefixLen': 0, 'IPv6Gateway': '', 'MacAddress': '', 'Networks': {'bridge': {'IPAMConfig': None, 'Links': None, 'Aliases': None, 'NetworkID': '', 'EndpointID': '', 'Gateway': '', 'IPAddress': '', 'IPPrefixLen': 0, 'IPv6Gateway': '', 'GlobalIPv6Address': '', 'GlobalIPv6PrefixLen': 0, 'MacAddress': '', 'DriverOpts': None}}}
{}

According to this pull request the .ports property should have the mapped port.

Python version:

Python 3.7.9

Docker SDK version:

Name: docker
Version: 4.3.1

And I can verify that the container indeed does have a bound port:

$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                     NAMES
e97a2bb377fb        postgres:9.6        "docker-entrypoint.s…"   3 seconds ago       Up 3 seconds        0.0.0.0:32780->5432/tcp   stupefied_hellman

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions