{"record":{"id":"0218681c0ca96a8c","repo":"unclecode/crawl4ai","slug":"cannot-connect-to-server-str-e","errorCode":null,"errorMessage":"Cannot connect to server: {str(e)}","messagePattern":"Cannot connect to server: (.+?)","errorType":"exception","errorClass":"ConnectionError","httpStatus":null,"severity":"error","filePath":"crawl4ai/docker_client.py","lineNumber":72,"sourceCode":"            response = await self._http_client.post(url, json={\"email\": email})\n            response.raise_for_status()\n            data = response.json()\n            self._token = data[\"access_token\"]\n            self._http_client.headers[\"Authorization\"] = f\"Bearer {self._token}\"\n            self.logger.success(\"Authentication successful\", tag=\"AUTH\")\n        except (httpx.RequestError, httpx.HTTPStatusError) as e:\n            error_msg = f\"Authentication failed: {str(e)}\"\n            self.logger.error(error_msg, tag=\"ERROR\")\n            raise ConnectionError(error_msg)\n\n    async def _check_server(self) -> None:\n        \"\"\"Check if server is reachable, raising an error if not.\"\"\"\n        try:\n            await self._http_client.get(urljoin(self.base_url, \"/health\"))\n            self.logger.success(f\"Connected to {self.base_url}\", tag=\"READY\")\n        except httpx.RequestError as e:\n            self.logger.error(f\"Server unreachable: {str(e)}\", tag=\"ERROR\")\n            raise ConnectionError(f\"Cannot connect to server: {str(e)}\")\n\n    def _prepare_request(\n        self,\n        urls: List[str],\n        browser_config: Optional[BrowserConfig] = None,\n        crawler_config: Optional[CrawlerRunConfig] = None,\n        hooks: Optional[Union[Dict[str, Callable], Dict[str, str]]] = None,\n        hooks_timeout: int = 30\n    ) -> Dict[str, Any]:\n        \"\"\"Prepare request data from configs.\"\"\"\n        if self._token:\n            self._http_client.headers[\"Authorization\"] = f\"Bearer {self._token}\"\n\n        request_data = {\n            \"urls\": urls,\n            \"browser_config\": browser_config.dump() if browser_config else {},\n            \"crawler_config\": crawler_config.dump() if crawler_config else {}\n        }","sourceCodeStart":54,"sourceCodeEnd":90,"githubUrl":"https://github.com/unclecode/crawl4ai/blob/7e801521428ee12509994d39151006f64055ebe3/crawl4ai/docker_client.py#L54-L90","documentation":"Raised by Crawl4aiDockerClient._check_server when the GET {base_url}/health request raises httpx.RequestError — i.e. the request never completed successfully at the network layer. It is wrapped as ConnectionError('Cannot connect to server: ...'), with the httpx detail describing DNS, connection, or TLS failure.","triggerScenarios":"Connecting the docker client while the crawl4ai server container is stopped, starting, or crashed; base_url pointing at an unreachable host/port; DNS resolution failure; a proxy or firewall dropping the connection before HTTP completes.","commonSituations":"Forgetting to docker run / docker compose up the crawl4ai server before using the client; container listening on a port different from base_url; the container crashed on startup — check docker logs; local development where the service binds only to another interface.","solutions":["Start the server container and confirm: curl {base_url}/health returns a success response","Check container status and logs (docker ps, docker logs <container>) to rule out a crash loop","Fix base_url to match the published port mapping (e.g. http://localhost:11235)","Retry connection once the container healthcheck reports healthy"],"exampleFix":"// before\nclient = Crawl4aiDockerClient(base_url=\"http://localhost:9999\")\nawait client.some_call()  # Cannot connect to server\n\n// after\n# run: docker run -p 11235:11235 unclecode/crawl4ai:latest\nclient = Crawl4aiDockerClient(base_url=\"http://localhost:11235\")","handlingStrategy":"validation","validationCode":"import httpx\n\nasync def wait_for_server(base_url: str, attempts: int = 1):\n    try:\n        await httpx.AsyncClient().get(f\"{base_url}/health\", timeout=5)\n    except httpx.HTTPError:\n        raise RuntimeError(f\"crawl4ai server at {base_url} is not up\")\n\nawait wait_for_server(\"http://localhost:11235\")","typeGuard":null,"tryCatchPattern":"try:\n    await client.close() if False else None\n    results = await client.crawl(urls)\nexcept ConnectionError as e:\n    if \"Cannot connect\" in str(e):\n        log.error(\"server down — start the crawl4ai container\")\n    raise","preventionTips":["Start the container with a healthcheck and wait for healthy before connecting","Match base_url to the container's published port","Check docker ps / docker logs first when this error appears"],"tags":["docker-client","network","server-unreachable"],"backgroundTag":null,"analyzedSha":"7e801521428ee12509994d39151006f64055ebe3","analyzedAt":"2026-08-14T20:46:20.673Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}