Skip to content

Commit 58a24f9

Browse files
qoomonbsideup
authored andcommitted
only determine default gateway within docker container if docker host differ from default (#648)
1 parent 6a5834e commit 58a24f9

File tree

1 file changed

+21
-16
lines changed

1 file changed

+21
-16
lines changed

core/src/main/java/org/testcontainers/dockerclient/DockerClientConfigUtils.java

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,13 @@ public class DockerClientConfigUtils {
1717
// See https://github.com/docker/docker/blob/a9fa38b1edf30b23cae3eade0be48b3d4b1de14b/daemon/initlayer/setup_unix.go#L25
1818
public static final boolean IN_A_CONTAINER = new File("/.dockerenv").exists();
1919

20+
@Deprecated
2021
@Getter(lazy = true)
21-
private static final Optional<String> detectedDockerHostIp = Optional
22-
.of(IN_A_CONTAINER)
23-
.filter(it -> it)
24-
.map(file -> DockerClientFactory.instance().runInsideDocker(
22+
private static final Optional<String> detectedDockerHostIp = IN_A_CONTAINER ? getDefaultGateway() : Optional.empty();
23+
24+
@Getter(lazy = true)
25+
private static final Optional<String> defaultGateway = Optional
26+
.ofNullable(DockerClientFactory.instance().runInsideDocker(
2527
cmd -> cmd.withCmd("sh", "-c", "ip route|awk '/default/ { print $3 }'"),
2628
(client, id) -> {
2729
try {
@@ -41,18 +43,21 @@ public class DockerClientConfigUtils {
4143
.map(StringUtils::trimToEmpty)
4244
.filter(StringUtils::isNotBlank);
4345

46+
47+
4448
public static String getDockerHostIpAddress(DockerClientConfig config) {
45-
return getDetectedDockerHostIp().orElseGet(() -> {
46-
switch (config.getDockerHost().getScheme()) {
47-
case "http":
48-
case "https":
49-
case "tcp":
50-
return config.getDockerHost().getHost();
51-
case "unix":
52-
return "localhost";
53-
default:
54-
return null;
55-
}
56-
});
49+
switch (config.getDockerHost().getScheme()) {
50+
case "http":
51+
case "https":
52+
case "tcp":
53+
return config.getDockerHost().getHost();
54+
case "unix":
55+
if (IN_A_CONTAINER) {
56+
return getDefaultGateway().orElse("localhost");
57+
}
58+
return "localhost";
59+
default:
60+
return null;
61+
}
5762
}
5863
}

0 commit comments

Comments
 (0)