Skip to content

ExecutionContainer

A context manager for managing the lifecycle of a Docker container used for code execution.

It handles the creation, port mapping, volume binding, and cleanup of the container.

Parameters:

Name Type Description Default
tag str

Tag of the Docker image to use (defaults to gradion-ai/ipybox)

DEFAULT_TAG
binds dict[str, str] | None

Mapping of host paths to container paths for volume mounting. Host paths may be relative or absolute. Container paths must be relative and are created as subdirectories of /app in the container.

None
env dict[str, str] | None

Environment variables to set in the container

None
port int | None

Host port to map to the container's executor port. If not provided, a random port will be allocated.

None
show_pull_progress bool

Whether to show progress when pulling the Docker image.

True

Attributes:

Name Type Description
port int

Host port mapped to the container's executor port. This port is dynamically allocated when the container is started.

Example
from ipybox import ExecutionClient, ExecutionContainer

binds = {"/host/path": "example/path"}
env = {"API_KEY": "secret"}

async with ExecutionContainer(binds=binds, env=env) as container:
    async with ExecutionClient(host="localhost", port=container.port) as client:
        result = await client.execute("print('Hello, world!')")
        print(result.text)

Hello, world!

Source code in ipybox/container.py
def __init__(
    self,
    tag: str = DEFAULT_TAG,
    binds: dict[str, str] | None = None,
    env: dict[str, str] | None = None,
    port: int | None = None,
    show_pull_progress: bool = True,
):
    self.tag = tag
    self.binds = binds or {}
    self.env = env or {}
    self.show_pull_progress = show_pull_progress

    self._docker = None
    self._container = None
    self._port = port

port property

port: int

The host port mapped to the container's executor port.

This port is dynamically allocated when the container is started unless explicitly provided.

Raises:

Type Description
RuntimeError

If the container is not running

kill async

kill()

Kill and remove the Docker container.

Source code in ipybox/container.py
async def kill(self):
    """
    Kill and remove the Docker container.
    """
    if self._container:
        await self._container.kill()

    if self._docker:
        await self._docker.close()

run async

run()

Create and start the Docker container.

Source code in ipybox/container.py
async def run(self):
    """
    Create and start the Docker container.
    """
    self._docker = Docker()
    self._container = await self._run()