1

I am using docker-py to build an image and create a container. The container should include port bindings. The idea is that I will have multiple clients accessing the image and be able to open multiple containers. As such, I want the port to increment every time a new container is created, for example: container1 port:5000 ; container2 port:5001 ; etc...

How would I go about implementing this function in python?

Thanks

User588233
  • 481
  • 2
  • 5
  • 16

1 Answers1

0

In fact, during build stage, the Dockerfile only exposes container's internal port.

When you run a new container, then you create a mapping between a Docker host port and the container exposed port.

So you just have to increment your run port mapping when invoking container creation API:

import docker
docker_client = docker.Client(version="1.18", base_url="unix:///var/run/docker.sock")

def create_new_container(port):
    my_port_mappings = {}
    my_port_mappings[5000] = port

    host_config = docker_client.create_host_config(
        port_bindings=my_port_mappings
    )

    container = docker_client.create_container(
        image="my_image",
        detach=True,
        ports=my_port_mappings.keys(),
        name=container_name,
        host_config=host_config)

create_container(5000)
create_container(5001)
create_container(5002)
create_container(5003)
Fabien Balageas
  • 624
  • 5
  • 6