microsoft/autogen · critical · RuntimeError

Unexpected error while connecting to Docker: {str(e)}

Error message

Unexpected error while connecting to Docker: {str(e)}

What it means

Generic wrapper raised when docker.from_env() throws something other than the known DockerException/FileNotFoundError case while DockerCommandLineCodeExecutor.start() tries to build a Docker client. The original exception is chained via 'from e', so the message embeds the underlying error text (permissions, TLS config, socket errors, etc.).

Source

Thrown at python/packages/autogen-ext/src/autogen_ext/code_executors/docker/_docker_code_executor.py:515

        This method sets the working environment variables, connects to Docker and starts the code executor.
        If no working directory was provided to the code executor, it creates a temporary directory and sets it as the code executor working directory.
        """

        if self._work_dir is None and self._temp_dir is None:
            self._temp_dir = tempfile.TemporaryDirectory()
            self._temp_dir_path = Path(self._temp_dir.name)
            self._temp_dir_path.mkdir(exist_ok=True)

        # Start a container from the image, read to exec commands later
        try:
            client = docker.from_env()
        except DockerException as e:
            if "FileNotFoundError" in str(e):
                raise RuntimeError("Failed to connect to Docker. Please ensure Docker is installed and running.") from e
            raise
        except Exception as e:
            raise RuntimeError(f"Unexpected error while connecting to Docker: {str(e)}") from e

        # Check if the image exists
        try:
            await asyncio.to_thread(client.images.get, self._image)
        except ImageNotFound:
            # TODO logger
            logging.info(f"Pulling image {self._image}...")
            # Let the docker exception escape if this fails.
            await asyncio.to_thread(client.images.pull, self._image)

        # Prepare the command (if needed)
        shell_command = "/bin/sh"
        command = ["-c", f"{(self._init_command)};exec {shell_command}"] if self._init_command else None

        # Check if a container with the same name already exists and remove it
        try:
            existing_container = await asyncio.to_thread(client.containers.get, self.container_name)
            await asyncio.to_thread(existing_container.remove, force=True)

View on GitHub (pinned to 027ecf0a37)

Solutions

  1. Read the embedded {str(e)} text to identify the root cause, then fix that (permissions, DOCKER_HOST, TLS config).
  2. If the message mentions permissions on a Unix socket: sudo usermod -aG docker $USER, log out/in, verify with docker ps.
  3. Unset or correct DOCKER_HOST / DOCKER_TLS_VERIFY / DOCKER_CERT_PATH environment variables and test with docker version.
  4. Upgrade/reinstall the docker Python package so it matches your daemon version (pip install -U docker).

Example fix

# before
await executor.start()
# RuntimeError: Unexpected error while connecting to Docker: PermissionError(.../docker.sock)

# after
# on the shell, before running the app:
#   sudo usermod -aG docker $USER && newgrp docker
#   docker ps   # verify access
await executor.start()
Defensive patterns

Strategy: try-catch

Validate before calling

import subprocess

def docker_daemon_reachable() -> bool:
    return subprocess.run(["docker", "info"], capture_output=True).returncode == 0

Try / catch

try:
    await executor.start()
except RuntimeError as e:
    print(f"Docker client failed: {e} | root cause: {e.__cause__!r}")
    raise

Prevention

When it happens

Trigger: Calling await executor.start() when from_env() raises an unexpected exception, e.g. PermissionError on /var/run/docker.sock (not always wrapped as DockerException with FileNotFoundError), malformed DOCKER_HOST/TLS settings in ~/.docker/config.json, or docker-py version incompatibilities.

Common situations: Unix permission denied on the Docker socket, DOCKER_HOST=tcp://... pointing at a dead endpoint, corrupt TLS certificates in docker config, corporate proxies intercepting the socket, mismatched docker-py versions after upgrading packages.

Related errors


AI-assisted analysis of microsoft/autogen@027ecf0a37 (2026-08-15). Data as JSON: /api/errors/4cde8710a0e1561d. Report an issue: GitHub.