Tickd.ai
← The Tickd Guide

Tutorials & Guides

How to Build a Local Docker Sandbox in Python to Safely Execute LLM-Generated Code

Letting an LLM run arbitrary code on your machine is a recipe for disaster. Here is how to build a lightweight, local Docker sandbox to safely execute generated Python scripts.

Updated 11/8/2026

Building an AI agent that writes its own code is an exhilarating milestone. But the moment you realise you are about to run a subprocess.run() on code written by a probabilistic token-generator is the moment your stomach drops. You do not hand a toddler a loaded nail gun, and you certainly do not give an LLM unrestricted access to your terminal.

Whether you are building with /platforms/claude or /platforms/openai, executing generated code locally is a massive security bottleneck. If the model hallucinates a destructive bash command, or gets hit with an injection attack, your local files are toast.

To make your agentic workflows actually useful—and to understand what makes these loops safely tick—you need an isolated playground. Here is how to build a lightweight, local-first Docker sandbox in Python that spins up, executes untrusted code, returns the output, and self-destructs without exposing your host machine.

Why Standard Isolation Tools Fall Short

Many developers start by trying to sanitise LLM output with regular expressions, blocking keywords like os.system or shutil.rmtree. This is a fool's errand. Python is incredibly dynamic; an LLM (or a malicious prompt injector) can easily bypass basic filters using getattr(), base64 encoding, or rot13 obfuscation.

Virtual environments (venv) do not help either—they isolate dependencies, not system access.

Our solution must meet three criteria: 1. Hard Isolation: The code must run in an environment with no access to your host system's environment variables, sensitive files, or local network. 2. Resource Constraints: We must cap execution time, memory, and CPU usage so an infinite loop doesn't melt your machine. 3. Low Latency: Spin-up time needs to be fast enough to keep your agent's loops snappy.

Which AI should I use for this?

Tickd is independent and not affiliated with any AI company.

The Architecture

Our sandbox tool will use the official Python docker SDK to talk to your local Docker daemon. The flow is straightforward: 1. Write the LLM-generated Python code to a temporary, isolated file. 2. Spin up a container using a minimal Python base image (like python:3.11-slim). 3. Mount the temporary file into the container as a read-only volume. 4. Execute the script under a strict time limit and resource cap. 5. Capture stdout, stderr, and the exit code, then gracefully destroy the container.

Step 1: Setting Up Your Environment

First, make sure you have Docker running locally. If you do not have it, install Docker Desktop (or Docker Engine on Linux).

Next, install the required Python libraries on your host machine:

`bash pip install docker pydantic `

Step 2: Coding the Sandbox Wrapper

Create a file named sandbox.py. We will use Pydantic to structure our execution results, ensuring clean types when passing data back to your main application or agent architecture. Refer to our guides on /platforms/claude/articles for how to parse these structured objects back into your LLM chain.

`python import os import tempfile import docker from pydantic import BaseModel from typing import Optional

class SandboxResult(BaseModel): stdout: str stderr: str exit_code: int timeout_triggered: bool

class LocalSandbox: def __init__(self, image: str = "python:3.11-slim"): self.client = docker.from_env() self.image = image # Ensure the image is available locally to prevent slow first runs try: self.client.images.get(self.image) except docker.errors.ImageNotFound: print(f"Pulling base image {self.image}... This may take a minute.") self.client.images.pull(self.image)

def execute(self, code: str, timeout_seconds: int = 5, memory_limit: str = "128m") -> SandboxResult: # Write code to a temporary file on the host with tempfile.NamedTemporaryFile(suffix=".py", delete=False) as temp_file: temp_file.write(code.encode("utf-8")) temp_file_path = temp_file.name

container = None stdout = "" stderr = "" exit_code = -1 timeout_triggered = False

try: # Define container configurations # We mount the single temp file to /app/run.py in read-only mode volumes = {temp_file_path: {"bind": "/app/run.py", "mode": "ro"}} container = self.client.containers.create( image=self.image, command="python /app/run.py", volumes=volumes, network_mode="none", # No internet access mem_limit=memory_limit, nano_cpus=1000000000, # Cap at 1 CPU core detach=True )

container.start()

Wait for execution with a timeout try: result = container.wait(timeout=timeout_seconds) exit_code = result.get("StatusCode", 0) stdout = container.logs(stdout=True, stderr=False).decode("utf-8") stderr = container.logs(stdout=False, stderr=True).decode("utf-8") except docker.errors.ContainerError as ce: stderr = str(ce) except Exception as e: # This handles timeout exceptions thrown by container.wait() timeout_triggered = True container.kill() stderr = f"Execution exceeded timeout limit of {timeout_seconds}s."

finally: # Clean up the container if container: try: container.remove(force=True) except Exception: pass # Clean up the temporary file on the host if os.path.exists(temp_file_path): os.remove(temp_file_path)

return SandboxResult( stdout=stdout, stderr=stderr, exit_code=exit_code, timeout_triggered=timeout_triggered ) `

Step 3: Testing the Sandbox

Let's write a quick script to test both benign execution and potentially malicious actions.

`python if __name__ == "__main__": sandbox = LocalSandbox()

Test 1: Benign arithmetic script good_code = """ results = [x * 2 for x in range(5)] print(f"Calculation complete: {results}") """ print("--- Running Good Code ---") res_good = sandbox.execute(good_code) print(f"Exit Code: {res_good.exit_code}") print(f"Stdout: {res_good.stdout.strip()}") print(f"Stderr: {res_good.stderr.strip()}")

Test 2: Malicious code trying to read system environment variables bad_code = """ import os # Try to read the host system files or environment try: # Since network is 'none', this will fail silently or throw import urllib.request urllib.request.urlopen('https://example.com', timeout=1) except Exception as e: print(f"Network blocked successfully: {e}") """ print("\n--- Running Host Isolation Test ---") res_bad = sandbox.execute(bad_code) print(f"Exit Code: {res_bad.exit_code}") print(f"Stdout: {res_bad.stdout.strip()}") print(f"Stderr: {res_bad.stderr.strip()}")

Test 3: Infinite loop resource cap loop_code = """ import time print("Starting loop...") while True: pass """ print("\n--- Running Infinite Loop Test ---") res_loop = sandbox.execute(loop_code, timeout_seconds=2) print(f"Timeout Triggered: {res_loop.timeout_triggered}") print(f"Stdout: {res_loop.stdout.strip()}") print(f"Stderr: {res_loop.stderr.strip()}") ```

How This Sandbox Protects You

  • Zero Network Access: By setting network_mode="none", the running container cannot send pingbacks, leak sensitive tokens to external servers, or download external payloads.
  • No Local Access: The only thing mounted to the container is a single, temporary Python file with read-only rights (mode="ro"). Even if the script executes os.listdir('/'), it only sees the clean Docker environment.
  • Memory & CPU Caps: If your LLM gets stuck in an infinite loop or tries to run a fork bomb, the nano_cpus and mem_limit constraints ensure your host operating system remains stable and responsive.

Taking It Further

If your AI agents need access to specific local packages, you can build a custom Docker image with those libraries pre-installed (e.g., numpy, pandas, or requests) and pass that image name to the LocalSandbox constructor.

With this sandboxed runner integrated into your dev workflow, you can confidently hand the steering wheel to Claude or GPT, knowing your local hard drive is locked safely behind a containerised firewall.

pythondockersecurityai-agentstutorials

Keep going

Build something with the prompt generator, decode the jargon in the glossary, or compare the tools on our platform deep-dives.