Get started with Alibaba's open-source general sandbox platform in just 10 minutes to create your first isolated execution environment.
Difficulty: βββββ | Duration: 10 minutes | Outcome: Master the core usage of OpenSandbox and quickly build an isolated execution environment.
Target Audience
- Backend developers with 1-3 years of experience
- Engineers looking to add secure code execution capabilities to AI Agents
- Technicians interested in sandbox technology
Core Dependencies
- Python 3.10+
- Docker Desktop
opensandbox- Python SDKopensandbox-server- Sandbox serviceopensandbox-code-interpreter- Code interpreter
# Install dependencies
uv pip install opensandbox opensandbox-server opensandbox-code-interpreter
TIP
It is recommended to use uv as the package manager, although pip can also be used as a substitute.
Project Structure
OpenSandbox/
βββ sdks/ # Multi-language SDKs
β βββ sandbox/python/ # Basic sandbox SDK
β βββ code-interpreter/ # Code interpreter SDK
βββ server/ # Sandbox lifecycle management service
βββ examples/ # Integration examples (Claude Code, Playwright, etc.)
βββ components/ # Core components (ingress, egress)
βββ specs/ # API specification definitions
1. Start the Sandbox Service
After installation, start the local sandbox service with a single command:
# Initialize configuration file (optional, can skip if using default configuration)
opensandbox-server init-config ~/.sandbox.toml --example docker
# Start the service
opensandbox-server
The service listens by default on http://localhost:8080, ready for local development and testing without additional configurations.
WARNING
It is recommended to deploy in a production environment using Kubernetes. See "Advanced Directions" below for more details.
2. Create Your First Sandbox
import asyncio
from opensandbox import Sandbox
from opensandbox.config import ConnectionConfig
async def main():
# Connect to the local service (defaults to localhost:8080 if domain is not configured)
config = ConnectionConfig()
# Create a sandbox with the specified image
sandbox = await Sandbox.create(
"ubuntu:latest",
connection_config=config
)
async with sandbox:
# Execute a command
result = await sandbox.commands.run("echo 'Hello OpenSandbox!'")
print(result.logs.stdout[0].text) # Hello OpenSandbox!
# Clean up resources
await sandbox.kill()
asyncio.run(main())
The core process consists of three steps: Create β Execute β Clean Up.
3. File Operations
The sandbox has complete file system support, enabling writing, reading, searching, and deleting files:
from opensandbox.models import WriteEntry
async def file_operations():
# Write a file
await sandbox.files.write_files([
WriteEntry(
path="/tmp/demo.txt",
data="Hello from sandbox!",
mode=644
)
])
# Read a file
content = await sandbox.files.read_file("/tmp/demo.txt")
print(content) # Hello from sandbox!
# Search for files
files = await sandbox.files.search(
path="/tmp",
pattern="*.txt"
)
for f in files:
print(f"Found: {f.path}")
The mode parameter of WriteEntry supports octal permission settings, for example, 644 and 755.
4. Sandbox Lifecycle Management
Once created, the sandbox automatically manages its lifecycle, supporting renewal, pause, and resume:
from datetime import timedelta
# Renewal: Reset expiration time
await sandbox.renew(timedelta(minutes=30))
# Pause: Suspend all processes
await sandbox.pause()
# Resume: Recover from pause state
resumed = await Sandbox.resume(
sandbox_id=sandbox.id,
connection_config=config
)
# Check the current status
info = await sandbox.get_info()
print(f"State: {info.status.state}") # RUNNING, PAUSED, TERMINATED
TIP
The sandbox automatically expires after 10 minutes by default, so remember to set an appropriate timeout based on your actual needs.
5. Building a Code Interpreter
If you need to implement a code interpreter functionality similar to ChatGPT, OpenSandbox provides a ready-to-use SDK:
import asyncio
from datetime import timedelta
from code_interpreter import CodeInterpreter, SupportedLanguage
from opensandbox import Sandbox
async def main():
# Create sandbox specifying the code-interpreter image
sandbox = await Sandbox.create(
"opensandbox/code-interpreter:v1.0.1",
entrypoint=["/opt/opensandbox/code-interpreter.sh"],
timeout=timedelta(minutes=10),
)
async with sandbox:
# Create a code interpreter
interpreter = await CodeInterpreter.create(sandbox)
# Execute Python code
result = await interpreter.codes.run(
"""
import sys
print(sys.version)
# Simple data processing
data = [1, 2, 3, 4, 5]
result = sum(data)
result
""",
language=SupportedLanguage.PYTHON,
)
# Print execution results
print(result.result[0].text) # 15
print(result.logs.stdout[0].text) # 3.11.14
await sandbox.kill()
asyncio.run(main())
The CodeInterpreter handles code execution, result return, and error handling automatically; you just need to call codes.run().
6. Frequently Asked Questions
Q1: Connection Timeout
# Increase the timeout duration
config = ConnectionConfig(
request_timeout=timedelta(seconds=60)
)
Q2: Image Pull Failure
Check whether the Docker image repository is functioning properly:
docker pull ubuntu:latest
It is recommended to configure image accelerators for users in China.
Q3: Permission Issues
By default, commands executed in the sandbox run with root permissions, but if you need a specific user:
sandbox = await Sandbox.create(
"ubuntu:latest",
entrypoint=["su", "-", "ubuntu", "-c", "tail -f /dev/null"]
)
Q4: Limited Network Access
You can configure network policies when creating a sandbox:
from opensandbox.models.sandboxes import NetworkPolicy, NetworkRule
sandbox = await Sandbox.create(
"python:3.11",
network_policy=NetworkPolicy(
defaultAction="deny",
egress=[
NetworkRule(action="allow", target="pypi.org"),
NetworkRule(action="allow", target="*.github.com"),
]
)
)
Q5: How to View Sandbox Logs
# Get detailed information about the sandbox
info = await sandbox.get_info()
print(info.status)
Q6: How to Use Synchronous Mode
If async/await is inconvenient, the SDK also provides a synchronous version:
from opensandbox import SandboxSync
sandbox = SandboxSync.create("ubuntu:latest")
with sandbox:
result = sandbox.commands.run("echo 'sync mode'")
print(result.logs.stdout[0].text)
7. Advanced Directions
Kubernetes Deployment
It is recommended to deploy in production environments using Kubernetes, with the official Helm Chart provided:
helm repo add opensandbox https://alibaba.github.io/opensandbox-charts
helm install opensandbox opensandbox/opensandbox
See further details at kubernetes-sigs/agent-sandbox.
Multi-Language SDK
OpenSandbox supports not just Python but also offers SDKs in various languages:
- Java/Kotlin:
opensandbox-sdk - JavaScript/TypeScript:
@alibaba-group/opensandbox - C#/.NET:
Alibaba.OpenSandbox
Network Policies
- Ingress: Inbound traffic gateway, supports multiple routing strategies.
- Egress: Outbound traffic control, allows fine-grained management of sandbox network access.
Integration Examples
The official documentation provides a wealth of integration examples:
- Integration with Claude Code
- Automation with Playwright browsers
- Web Environment for VS Code
- Reinforcement Learning Training Environments
Refer to the examples/ directory for more.
Conclusion
In this article, we introduced OpenSandbox, covering service startup, sandbox creation, command execution, file operations, and building a Code Interpreter. The core APIs are quite a few:
Sandbox.create()- Create a sandboxsandbox.commands.run()- Execute commandssandbox.files.write_files() / read_file()- File operationssandbox.kill()- Clean up resources
For more complex scenarios (multi-sandbox management, custom health checks, streaming output), refer to the official SDK documentation for further exploration.
If you have questions, feel free to leave a comment. See you in the next issue!
This document is based on OpenSandbox v1.0.1. Official repository: https://github.com/alibaba/OpenSandbox