{"record":{"id":"78cc9dd7d62151be","repo":"microsoft/autogen","slug":"container-is-not-running-must-first-be-started-wi","errorCode":null,"errorMessage":"Container is not running. Must first be started with either start or a context manager.","messagePattern":"Container is not running\\. Must first be started with either start or a context manager\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"python/packages/autogen-ext/src/autogen_ext/code_executors/docker/_docker_code_executor.py","lineNumber":294,"sourceCode":"\n        # Attempt to load the function file to check for syntax errors, imports etc.\n        exec_result = await self._execute_code_dont_check_setup(\n            [CodeBlock(code=func_file_content, language=\"python\")], cancellation_token\n        )\n\n        if exec_result.exit_code != 0:\n            raise ValueError(f\"Functions failed to load: {exec_result.output}\")\n\n        self._setup_functions_complete = True\n\n    async def _kill_running_command(self, command: List[str]) -> None:\n        if self._container is None or not self._running:\n            return\n        await asyncio.to_thread(self._container.exec_run, [\"pkill\", \"-f\", \" \".join(command)])\n\n    async def _execute_command(self, command: List[str], cancellation_token: CancellationToken) -> Tuple[str, int]:\n        if self._container is None or not self._running:\n            raise ValueError(\"Container is not running. Must first be started with either start or a context manager.\")\n\n        exec_task = asyncio.create_task(asyncio.to_thread(self._container.exec_run, command))\n        cancellation_token.link_future(exec_task)\n\n        # Wait for the exec task to finish.\n        try:\n            result = await exec_task\n            exit_code = result.exit_code\n            output = result.output.decode(\"utf-8\")\n            if exit_code == 124:\n                output += \"\\n Timeout\"\n            return output, exit_code\n        except asyncio.CancelledError:\n            # Schedule a task to kill the running command in the background.\n            if self._loop and not self._loop.is_closed():\n                try:\n                    logging.debug(f\"Scheduling kill command via run_coroutine_threadsafe on loop {self._loop!r}\")\n                    future: ConcurrentFuture[None] = asyncio.run_coroutine_threadsafe(","sourceCodeStart":276,"sourceCodeEnd":312,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/python/packages/autogen-ext/src/autogen_ext/code_executors/docker/_docker_code_executor.py#L276-L312","documentation":"Raised by DockerCommandLineCodeExecutor._execute_command when an exec is attempted while the executor's container is None or the _running flag is False. In practice it means execute_code_blocks was called before start()/entering the context manager, or after stop() — but the usual public entry point execute_code_blocks auto-starts, so hitting this from user code indicates a stopped/failed executor or direct use of internals.","triggerScenarios":"Calling internal methods (_execute_command, _execute_code_dont_check_setup) without a running container; calling execute_code_blocks after stop() completed (executor not restarted); a container that died between start and execution leaving _running stale. Note the executor used as a context manager (`async with ... as executor`) starts automatically.","commonSituations":"Keeping a module-level executor and reusing it across requests after a shutdown hook stopped it; a previous container crash combined with the flag not being reset; calling restart() before ever starting, which hits the same guard.","solutions":["Use the executor as an async context manager so lifecycle is handled: `async with DockerCommandLineCodeExecutor() as e: await e.execute_code_blocks(...)`","If managing manually, call `await executor.start()` after construction and again after stop() before executing code","After Docker daemon outages, recreate the executor rather than reusing a stopped instance","Avoid calling private _execute_* methods directly; go through execute_code_blocks"],"exampleFix":"# before\nexecutor = DockerCommandLineCodeExecutor()\nresult = await executor.execute_code_blocks(blocks, ct)  # not started\n\n# after\nasync with DockerCommandLineCodeExecutor() as executor:\n    result = await executor.execute_code_blocks(blocks, ct)","handlingStrategy":"validation","validationCode":"null","typeGuard":"def executor_ready(executor) -> bool:\n    return executor._container is not None and executor._running","tryCatchPattern":"try:\n    result = await executor.execute_code_blocks(blocks, ct)\nexcept ValueError as e:\n    if \"not running\" in str(e):\n        await executor.start()\n        result = await executor.execute_code_blocks(blocks, ct)","preventionTips":["Always use `async with DockerCommandLineCodeExecutor() as executor:` so the container lifecycle is correct by construction","Never reuse an executor after stop(); create a fresh instance","Do not call private _execute_* methods from user code"],"tags":["docker","lifecycle","state","container"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}