0Pricing
AI Agents · Lesson

Docker-Based Agent Sandboxes

Spinning up disposable containers for agent-generated code execution.

Docker-Based Agent Sandboxes is a free AI Agents lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Agents learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Agents Need Sandboxes

When an agent executes code written by an LLM, that code is untrusted. It may attempt to read sensitive files, establish outbound connections, or consume unlimited resources.

A sandbox isolates code execution so damage is contained regardless of what the code does.

Docker as a Sandbox Layer

Docker containers provide lightweight OS-level isolation. Each code snippet runs inside a fresh container with explicit resource caps and network restrictions.

The docker Python SDK lets you spin up and destroy containers programmatically from inside your agent.

import docker

client = docker.from_env()
print(client.version()['Version'])

Basic Container Run

client.containers.run() starts a container, executes a command, and returns the output as bytes. Setting auto_remove=True cleans up the container after it exits.

import docker

client = docker.from_env()

output = client.containers.run(
    'python:3.12-slim',
    'python -c "print(2 + 2)"',
    auto_remove=True
)

print(output.decode())  # '4'

Memory and CPU Limits

Without limits, a rogue script can exhaust host memory. Pass mem_limit and nano_cpus to cap resource usage.

If the process exceeds mem_limit, the container is OOM-killed and an exception is raised.

output = client.containers.run(
    'python:3.12-slim',
    'python -c "x = [0]*10**8"',   # tries to allocate ~800 MB
    mem_limit='256m',
    nano_cpus=1_000_000_000,        # 1 CPU
    auto_remove=True
)
# Raises docker.errors.ContainerError if OOM-killed

Disabling the Network

Setting network_disabled=True prevents the container from making any outbound or inbound network calls — even DNS lookups fail. This stops data exfiltration and command-and-control callbacks.

output = client.containers.run(
    'python:3.12-slim',
    'python -c "import urllib.request; urllib.request.urlopen(\"http://example.com\")"',
    network_disabled=True,
    auto_remove=True
)
# Raises ContainerError: network unreachable

Execution Timeout

An infinite loop inside the sandbox would block your agent forever. Pass a timeout (seconds) to containers.run() so Docker kills the container after the deadline.

import docker
from docker.errors import ContainerError

client = docker.from_env()

try:
    output = client.containers.run(
        'python:3.12-slim',
        'python -c "while True: pass"',
        mem_limit='256m',
        network_disabled=True,
        auto_remove=True,
        timeout=30
    )
except Exception as e:
    print(f'Sandbox timeout or error: {e}')

Full Sandbox Helper Function

Wrapping all settings into a reusable function makes it easy to call from agent tools. Return both stdout and a status flag so the agent can act on failures.

import docker

client = docker.from_env()

def run_in_sandbox(code: str, timeout: int = 30) -> dict:
    cmd = f'python -c "{code.replace(chr(34), chr(39))}"'
    try:
        out = client.containers.run(
            'python:3.12-slim',
            cmd,
            mem_limit='256m',
            nano_cpus=500_000_000,
            network_disabled=True,
            auto_remove=True,
            timeout=timeout
        )
        return {'success': True, 'output': out.decode()}
    except Exception as e:
        return {'success': False, 'error': str(e)}

Mounting a Temporary Workspace

If the code needs to read input files or write output files, mount a temporary host directory into the container. Use volumes with mode 'rw' for the workspace and nothing else.

import tempfile, os

with tempfile.TemporaryDirectory() as tmpdir:
    # Write input data
    with open(os.path.join(tmpdir, 'data.txt'), 'w') as f:
        f.write('hello sandbox')

    output = client.containers.run(
        'python:3.12-slim',
        'python -c "print(open(\"/workspace/data.txt\").read())"',
        volumes={tmpdir: {'bind': '/workspace', 'mode': 'rw'}},
        mem_limit='256m',
        network_disabled=True,
        auto_remove=True
    )
    print(output.decode())

Read-Only Filesystem

Set read_only=True to mount the container's root filesystem as read-only. The code can only write to explicitly mounted volumes. This prevents writes to /etc, /usr, or other sensitive paths inside the image.

import tempfile

with tempfile.TemporaryDirectory() as tmpdir:
    output = client.containers.run(
        'python:3.12-slim',
        'python -c "open(\"/output/result.txt\",\"w\").write(str(1+1))"',
        volumes={tmpdir: {'bind': '/output', 'mode': 'rw'}},
        read_only=True,
        mem_limit='256m',
        network_disabled=True,
        auto_remove=True
    )
    print(open(f'{tmpdir}/result.txt').read())  # '2'

Integrating Sandbox into an Agent Tool

Register the sandbox runner as a tool the LLM can call. The agent generates code, the tool executes it in isolation, and the output flows back to the next reasoning step.

tools = [
    {
        'type': 'function',
        'function': {
            'name': 'execute_python',
            'description': 'Run a Python snippet in an isolated Docker sandbox.',
            'parameters': {
                'type': 'object',
                'properties': {
                    'code': {'type': 'string', 'description': 'Python code to execute.'}
                },
                'required': ['code']
            }
        }
    }
]

def handle_tool_call(name, args):
    if name == 'execute_python':
        return run_in_sandbox(args['code'])

Error Handling and Cleanup

Containers can fail to start if the Docker daemon is not running, or if the image is not cached. Always handle docker.errors.DockerException and ensure containers are cleaned up even on exceptions.

from docker.errors import DockerException, ImageNotFound

def safe_run(code: str) -> dict:
    try:
        return run_in_sandbox(code)
    except ImageNotFound:
        # Pull the image first
        client.images.pull('python:3.12-slim')
        return run_in_sandbox(code)
    except DockerException as e:
        return {'success': False, 'error': f'Docker unavailable: {e}'}
    except Exception as e:
        return {'success': False, 'error': str(e)}

Which sandbox setting is most important for preventing data exfiltration?

An agent sandbox must prevent the executed code from sending stolen data to an external server. Which Docker parameter directly blocks outbound network access?

Docker Sandbox Recap

Docker-based sandboxes give agents a safe execution environment by combining memory and CPU limits, network isolation, execution timeouts, and read-only filesystems.

Wrap these settings in a reusable helper and expose it as an agent tool to let the LLM safely run generated code without risk to the host system.

Frequently asked questions

Is the “Docker-Based Agent Sandboxes” lesson free?

Yes — the full text of “Docker-Based Agent Sandboxes” is free to read here on the web, and the AI Agents course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Agents course, upgrade to CoddyKit PRO.

What will I learn in “Docker-Based Agent Sandboxes”?

Spinning up disposable containers for agent-generated code execution. You practise AI Agents with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start AI Agents?

No prior experience is required. AI Agents on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Docker-Based Agent Sandboxes” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this AI Agents lesson?

Yes. Every AI Agents lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Docker-Based Agent Sandboxes
  2. VM Isolation for High-Security Code Agents
  3. E2B and Cloud Sandbox Services
  4. Security Policies for Code Execution
← Back to AI Agents