Mapping

Motivation

The docker.models.containers.Container object provides a convenient way to map ports between a container and the host machine.

Options

  • ports(): This method returns a dictionary of port mappings for a container. The keys are the ports exposed by the container, and the values are a list of tuples. Each tuple represents a mapping between a container port and a host port. This is the main way to map ports in docker-py.

    • Example:

      from docker import from_env
                client = from_env()
                container = client.containers.run('nginx', detach=True, ports={'80/tcp': 8080})
                # Retrieve the port mappings 
                port_mappings = container.ports()
                print(port_mappings)
                

      The output would look like this:

      {'80/tcp': [('0.0.0.0', '8080')]} 
                
  • expose_ports(ports=None): This method allows you to specify which ports the container should expose. This is a crucial step in defining what ports can be accessed from the host machine.

    • Example:

      from docker import from_env
                client = from_env()
                container = client.containers.create('nginx', expose_ports={'80/tcp': None}, detach=True)
                print(container.attrs['Config']['ExposedPorts'])
                

      The output would look like this:

      {'80/tcp': {}} 
                

Example

from docker import from_env
          client = from_env()
          
          # Create a container, exposing port 80
          container = client.containers.create('nginx', expose_ports={'80/tcp': None}, detach=True)
          
          # Start the container
          container.start()
          
          # Get the port mappings 
          port_mappings = container.ports()
          
          # Find the host port mapped to the container's port 80
          for container_port, mappings in port_mappings.items():
              for host_ip, host_port in mappings:
                  if container_port == '80/tcp':
                      print(f"Container port 80 mapped to host port {host_port} on {host_ip}") 
          
          # Stop the container
          container.stop()
          

Source