diff --git a/core/src/main/java/org/testcontainers/dockerclient/DockerClientConfigUtils.java b/core/src/main/java/org/testcontainers/dockerclient/DockerClientConfigUtils.java index 7206a7e1452..ffaa119c698 100644 --- a/core/src/main/java/org/testcontainers/dockerclient/DockerClientConfigUtils.java +++ b/core/src/main/java/org/testcontainers/dockerclient/DockerClientConfigUtils.java @@ -6,7 +6,11 @@ import org.testcontainers.DockerClientFactory; import java.io.File; +import java.io.IOException; import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.Optional; import java.util.concurrent.TimeUnit; @@ -14,7 +18,39 @@ public class DockerClientConfigUtils { // See https://github.com/docker/docker/blob/a9fa38b1edf30b23cae3eade0be48b3d4b1de14b/daemon/initlayer/setup_unix.go#L25 - public static final boolean IN_A_CONTAINER = new File("/.dockerenv").exists(); + public static final boolean IN_A_CONTAINER = detectInContainer(); + + private static boolean detectInContainer() { + // Common indicators for being inside a containerized environment: + // - Docker: /.dockerenv + // - Podman / container tools: /run/.containerenv + // - Kubernetes: presence of KUBERNETES_SERVICE_HOST + // - cgroup hints: entries containing docker/kubepods/containerd/podman + if (new File("/.dockerenv").exists()) { + return true; + } + if (new File("/run/.containerenv").exists()) { + return true; + } + if (System.getenv("KUBERNETES_SERVICE_HOST") != null) { + return true; + } + try { + byte[] content = Files.readAllBytes(Paths.get("/proc/1/cgroup")); + String cgroup = new String(content, StandardCharsets.UTF_8).toLowerCase(); + if ( + cgroup.contains("docker") || + cgroup.contains("kubepods") || + cgroup.contains("containerd") || + cgroup.contains("podman") + ) { + return true; + } + } catch (IOException ignored) { + // ignore and fall back to false + } + return false; + } @Getter(lazy = true) private static final Optional defaultGateway = Optional