Skip to content
3 changes: 3 additions & 0 deletions CHANGES/811.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Add support for Docker context endpoints.
Read files such as ~/.docker/context/meta.json and set the socket.
DOCKER_CONTEXT will be prioritized if it is set.
21 changes: 21 additions & 0 deletions aiodocker/docker.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ def __init__(
docker_host = url # rename
if docker_host is None:
docker_host = os.environ.get("DOCKER_HOST", None)
if docker_host is None:
docker_host = self._get_docker_context_host()
if docker_host is None:
for sockpath in _sock_search_paths:
if sockpath.is_socket():
Expand Down Expand Up @@ -380,3 +382,22 @@ def _docker_machine_ssl_context() -> ssl.SSLContext:
certfile=str(certs_path2 / "cert.pem"), keyfile=str(certs_path2 / "key.pem")
)
return context

@staticmethod
def _get_docker_context_host() -> Optional[str]:
current_context_name = os.environ.get("DOCKER_CONTEXT", None)
if current_context_name is None:
try:
docker_config_path = Path.home() / ".docker" / "config.json"
docker_config = json.loads(docker_config_path.read_bytes())
except IOError:
return None
current_context_name = docker_config.get("currentContext", "default")

for meta_path in (Path.home() / ".docker" / "contexts" / "meta").glob(
"*/meta.json"
):
context_data = json.loads(meta_path.read_bytes())
if context_data["Name"] == current_context_name:
return context_data["Endpoints"]["docker"]["Host"]
return None