|
22 | 22 | from typing import TYPE_CHECKING, Any, Callable, Optional, TypeVar, Union, cast |
23 | 23 |
|
24 | 24 | import docker |
| 25 | +from docker.context import ContextAPI |
25 | 26 | from docker.models.containers import Container, ContainerCollection |
26 | 27 | from docker.models.images import Image, ImageCollection |
27 | 28 | from typing_extensions import ParamSpec |
@@ -320,12 +321,33 @@ def get_container_inspect_info(self, container_id: str) -> "ContainerInspectInfo |
320 | 321 |
|
321 | 322 |
|
322 | 323 | 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() |
324 | 325 | if host: |
325 | 326 | return _sanitize_docker_host(host) |
326 | 327 | return None |
327 | 328 |
|
328 | 329 |
|
| 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 | + |
329 | 351 | def get_docker_host_hostname() -> Optional[str]: |
330 | 352 | """Extract the remote hostname from an SSH-based DOCKER_HOST. |
331 | 353 |
|
|
0 commit comments