Skip to content

Commit a073701

Browse files
committed
feat(core): auto-detect DOCKER_HOST from current docker context
1 parent 1fadb40 commit a073701

2 files changed

Lines changed: 24 additions & 1 deletion

File tree

core/testcontainers/core/docker_client.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
from typing import TYPE_CHECKING, Any, Callable, Optional, TypeVar, Union, cast
2323

2424
import docker
25+
from docker.context import ContextAPI
2526
from docker.models.containers import Container, ContainerCollection
2627
from docker.models.images import Image, ImageCollection
2728
from typing_extensions import ParamSpec
@@ -320,12 +321,33 @@ def get_container_inspect_info(self, container_id: str) -> "ContainerInspectInfo
320321

321322

322323
def get_docker_host() -> Optional[str]:
323-
host = c.tc_properties_get_tc_host() or os.getenv("DOCKER_HOST")
324+
host = c.tc_properties_get_tc_host() or os.getenv("DOCKER_HOST") or _get_docker_host_from_context()
324325
if host:
325326
return _sanitize_docker_host(host)
326327
return None
327328

328329

330+
def _get_docker_host_from_context() -> Optional[str]:
331+
"""
332+
Look up the docker host from the current docker context (e.g. as set by``docker context use``).
333+
This allows users with a remote docker host configured via docker contexts to use testcontainers
334+
without having to additionally export ``DOCKER_HOST``.
335+
"""
336+
try:
337+
context = ContextAPI.get_current_context()
338+
except Exception as e:
339+
LOGGER.debug(f"failed to read current docker context: {e}")
340+
return None
341+
if context is None:
342+
return None
343+
host = context.Host
344+
# The default context points at the local unix socket / named pipe; let
345+
# docker-py fall back to its own defaults in that case.
346+
if not host or context.Name == "default":
347+
return None
348+
return cast("str", host)
349+
350+
329351
def get_docker_host_hostname() -> Optional[str]:
330352
"""Extract the remote hostname from an SSH-based DOCKER_HOST.
331353

core/tests/test_docker_client.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,7 @@ def test_get_docker_host_hostname(monkeypatch: pytest.MonkeyPatch, docker_host:
338338
from testcontainers.core.docker_client import get_docker_host_hostname
339339

340340
monkeypatch.setattr(c, "tc_properties_get_tc_host", lambda: None)
341+
monkeypatch.setattr("testcontainers.core.docker_client._get_docker_host_from_context", lambda: None)
341342
if docker_host:
342343
monkeypatch.setenv("DOCKER_HOST", docker_host)
343344
else:

0 commit comments

Comments
 (0)