Skip to content

Instantly share code, notes, and snippets.

@andgineer
Created February 19, 2024 07:40
Show Gist options
  • Save andgineer/159e19f606819abd092065da02b719bc to your computer and use it in GitHub Desktop.
Save andgineer/159e19f606819abd092065da02b719bc to your computer and use it in GitHub Desktop.
Dynamically allocate available port. Just excersice - better use DockerContainer ability to do it itself
import socket
from testcontainers.core.container import DockerContainer
class DynamicPortDockerContainer(DockerContainer):
def bind_available_port(self, container_port: int) -> int:
"""Find an available port on the host machine and bind it to the `container_port`.
Return bound host port number.
"""
# todo: on container start if port was occupied retry?
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 0)) # Bind to an available port provided by the OS
host_port = s.getsockname()[1] # Retrieve the port number
s.close() # Close the socket
# (!) does not reserve the port till container start
self.with_bind_ports(container_port, host_port)
return host_port
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment