From 31691859994183caddb44381fc3dbe8a0476fee5 Mon Sep 17 00:00:00 2001 From: "Gan, Jimmy" Date: Tue, 31 Mar 2026 11:57:14 +0800 Subject: [PATCH] fix: use lazy initialization for Docker client to prevent hanging in test environment --- dashboard/backend/routers/docker_router.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/dashboard/backend/routers/docker_router.py b/dashboard/backend/routers/docker_router.py index 45e475e..25fe88e 100644 --- a/dashboard/backend/routers/docker_router.py +++ b/dashboard/backend/routers/docker_router.py @@ -4,11 +4,20 @@ from config import DOCKER_HOST from rbac import require_admin router = APIRouter() -client = docker.DockerClient(base_url=DOCKER_HOST) + +_client = None + +def get_docker_client(): + """Get or create Docker client (lazy initialization).""" + global _client + if _client is None: + _client = docker.DockerClient(base_url=DOCKER_HOST) + return _client @router.get("/containers") def list_containers(): + client = get_docker_client() return [ { "id": c.short_id, @@ -26,6 +35,7 @@ def list_containers(): def container_action(container_id: str, action: str): if action not in ("start", "stop", "restart"): return {"error": "invalid action"} + client = get_docker_client() c = client.containers.get(container_id) getattr(c, action)() return {"ok": True} @@ -33,5 +43,6 @@ def container_action(container_id: str, action: str): @router.get("/containers/{container_id}/logs") def container_logs(container_id: str, tail: int = Query(200, le=10000)): + client = get_docker_client() c = client.containers.get(container_id) return {"logs": c.logs(tail=tail, timestamps=True).decode(errors="replace")}