Skip to content

Commit c778098

Browse files
committed
return docker host address and mapped port if possible
1 parent 10454f1 commit c778098

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

testcontainers/core/container.py

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import os
12
import blindspin
23
import crayons
34
from docker.models.containers import Container
@@ -77,17 +78,28 @@ def __del__(self):
7778
pass
7879

7980
def get_container_host_ip(self) -> str:
80-
# if testcontainers itself runs in docker, get the newly spawned
81-
# container's IP address from the dockder "bridge" network
82-
if inside_container():
83-
return self.get_docker_client().bridge_ip(self._container.id)
81+
# if os env TC_HOST is set, use it
82+
if os.environ.get('TC_HOST') is not None:
83+
return os.environ.get('TC_HOST')
84+
85+
# infer from docker host
86+
url = self.get_docker_client().host()
87+
88+
if 'http' in url.scheme or 'tcp' in url.scheme:
89+
return url.hostname
90+
if 'unix' in url.scheme or 'npipe' in url.scheme:
91+
# if testcontainers itself runs in docker, get the newly spawned
92+
# container's IP address from the dockder "bridge" network
93+
if inside_container():
94+
return self.get_docker_client().bridge_ip(self._container.id)
8495
return "localhost"
8596

8697
def get_exposed_port(self, port) -> str:
87-
if inside_container():
88-
return port
89-
else:
90-
return self.get_docker_client().port(self._container.id, port)
98+
url = self.get_docker_client().host()
99+
if 'unix' in url.scheme or 'npipe' in url.scheme:
100+
if inside_container():
101+
return port
102+
return self.get_docker_client().port(self._container.id, port)
91103

92104
def with_command(self, command: str) -> 'DockerContainer':
93105
self._command = command

0 commit comments

Comments
 (0)