@@ -78,30 +78,33 @@ def __del__(self):
78
78
pass
79
79
80
80
def get_container_host_ip (self ) -> str :
81
- # https://github.com/testcontainers/testcontainers-go/blob/dd76d1e39c654433a3d80429690d07abcec04424/docker.go#L644
82
- # if os env TC_HOST is set, use it
83
- host = os .environ .get ('TC_HOST' )
84
- if host :
85
- return host
86
-
87
81
# infer from docker host
88
- url = self .get_docker_client ().host ()
89
-
90
- if 'http' in url .scheme or 'tcp' in url .scheme :
91
- return url .hostname
92
- if 'unix' in url .scheme or 'npipe' in url .scheme :
93
- # if testcontainers itself runs in docker, get the newly spawned
94
- # container's IP address from the dockder "bridge" network
95
- if inside_container ():
82
+ host = self .get_docker_client ().host ()
83
+ if not host :
84
+ return "localhost"
85
+
86
+ # check testcontainers itself runs inside docker container
87
+ if inside_container ():
88
+ # If newly spawned container's gateway IP address from the docker
89
+ # "bridge" network is equal to detected host address, we should use
90
+ # container IP address, otherwise fall back to detected host
91
+ # address. Even it's inside container, we need to double check,
92
+ # because docker host might be set to docker:dind, usually in CI/CD environment
93
+ gateway_ip = self .get_docker_client ().gateway_ip (self ._container .id )
94
+
95
+ if gateway_ip == host :
96
96
return self .get_docker_client ().bridge_ip (self ._container .id )
97
- return "localhost"
97
+ return host
98
98
99
99
def get_exposed_port (self , port ) -> str :
100
- url = self .get_docker_client ().host ()
101
- if 'unix' in url .scheme or 'npipe' in url .scheme :
102
- if inside_container ():
100
+ mapped_port = self .get_docker_client ().port (self ._container .id , port )
101
+ if inside_container ():
102
+ gateway_ip = self .get_docker_client ().gateway_ip (self ._container .id )
103
+ host = self .get_docker_client ().host ()
104
+
105
+ if gateway_ip == host :
103
106
return port
104
- return self . get_docker_client (). port ( self . _container . id , port )
107
+ return mapped_port
105
108
106
109
def with_command (self , command : str ) -> 'DockerContainer' :
107
110
self ._command = command
0 commit comments