Created
February 19, 2024 07:40
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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