Spaces:
Sleeping
title: Docker Sandbox
emoji: π³
colorFrom: blue
colorTo: purple
sdk: docker
pinned: false
license: mit
π³ Docker Sandbox Executor
Secure code execution in isolated Docker containers
Features
β
Isolated execution - Each code run in separate container
β
Resource limits - 256MB RAM, 50% CPU per execution
β
Network disabled - Maximum security
β
Auto-cleanup - Containers destroyed after execution
β
Multiple languages - Python, JavaScript, React, HTML
Architecture
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Hugging Face Space (Docker SDK) β
β β
β ββββββββββββββββββββββββββββββββββββββββββββββββ β
β β FastAPI Server (app_docker.py) β β
β β β β
β β ββββββββββββββββββββββββββββββββββββββββββ β β
β β β Docker Engine (in Space) β β β
β β β β β β
β β β ββββββββββββββββ ββββββββββββββββ β β β
β β β β Python:3.11 β β Node:18 β β β β
β β β β Container β β Container β β β β
β β β β β β β β β β
β β β β β’ 256MB RAM β β β’ 256MB RAM β β β β
β β β β β’ 50% CPU β β β’ 50% CPU β β β β
β β β β β’ No Network β β β’ No Network β β β β
β β β ββββββββββββββββ ββββββββββββββββ β β β
β β ββββββββββββββββββββββββββββββββββββββββββ β β
β ββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Security Features
π‘οΈ Container Isolation
- Each execution runs in a separate Docker container
- Containers are destroyed after execution
- No persistent storage between executions
π« Resource Limits
- Memory: 256MB per container
- CPU: 50% of one core
- Timeout: 30 seconds default
- Network: Disabled (network_mode="none")
π Security Constraints
- No root access in containers
- No file system persistence
- No network access
- Automatic cleanup after execution
Hugging Face Space Configuration
Required Space Settings
1. SDK
sdk: docker
2. Dockerfile.sandbox
Use the provided Dockerfile.sandbox which includes:
- Python 3.11 base
- Node.js for React/JavaScript
- Docker-in-Docker (DinD) support
- Non-root user execution
3. Requirements
fastapi
uvicorn[standard]
docker
pydantic
Deployment Steps
Step 1: Create Hugging Face Space
# Create new space with Docker SDK
# Name: your-docker-sandbox
# SDK: Docker
Step 2: Upload Files
python deploy_docker_space.py
Or manually:
# Clone your space
git clone https://huggingface.co/spaces/YOUR_USERNAME/your-docker-sandbox
cd your-docker-sandbox
# Copy files
cp Dockerfile.sandbox Dockerfile
cp app_docker.py app.py
cp requirements.txt .
# Add README
cp README_DOCKER.md README.md
# Commit and push
git add .
git commit -m "Deploy Docker sandbox"
git push
Step 3: Enable Docker in Space Settings
- Go to Space Settings
- Under "Advanced", enable "Docker SDK"
- Set "Timeout" to 60+ seconds
- Save settings
API Usage
Endpoint
POST https://YOUR_USERNAME-your-docker-sandbox.hf.space/execute
Request Format
{
"language": "python",
"code": "print('Hello from Docker!')",
"timeout": 30
}
Supported Languages
python- Python 3.11 in Alpine containerjavascript- Node.js 18 in Alpine containerreact- Client-side React (no container needed)html- Pure HTML (no container needed)
Response Format
{
"status": "success",
"preview_url": "data:text/html;base64,...",
"terminal_view_url": "data:text/html;base64,...",
"execution_time": 0.234,
"docker_enabled": true
}
Example: Python Code Execution
PowerShell
$apiUrl = "https://YOUR_USERNAME-your-docker-sandbox.hf.space/execute"
$code = @"
import sys
print(f'Python {sys.version}')
print('Running in Docker container!')
for i in range(5):
print(f'Count: {i}')
"@
$body = @{
language = "python"
code = $code
timeout = 30
} | ConvertTo-Json
$response = Invoke-RestMethod -Uri $apiUrl -Method Post -Body $body -ContentType "application/json"
# Display terminal output
$terminalHtml = "<html><body><iframe src='$($response.terminal_view_url)' style='width:100%;height:100vh;border:none;'></iframe></body></html>"
$terminalHtml | Out-File -FilePath "docker_terminal.html"
Start-Process "docker_terminal.html"
JavaScript (Node.js)
const apiUrl = "https://YOUR_USERNAME-your-docker-sandbox.hf.space/execute";
const code = `
console.log('Node.js in Docker!');
console.log('Environment:', process.version);
const data = [1, 2, 3, 4, 5];
console.log('Sum:', data.reduce((a, b) => a + b, 0));
`;
fetch(apiUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
language: 'javascript',
code: code,
timeout: 30
})
})
.then(res => res.json())
.then(data => {
console.log('Execution time:', data.execution_time);
// Open terminal view
const iframe = document.createElement('iframe');
iframe.src = data.terminal_view_url;
iframe.style = 'width:100%;height:100vh;border:none;';
document.body.appendChild(iframe);
});
React Example
const reactCode = `
const { useState } = React;
function Counter() {
const [count, setCount] = useState(0);
return (
<div style={{ padding: '40px', textAlign: 'center', fontFamily: 'Arial' }}>
<h1 style={{ fontSize: '48px', color: '#667eea' }}>Counter: {count}</h1>
<button
onClick={() => setCount(count + 1)}
style={{
padding: '15px 30px',
fontSize: '20px',
background: '#667eea',
color: 'white',
border: 'none',
borderRadius: '10px',
cursor: 'pointer',
margin: '10px'
}}
>
Increment
</button>
<button
onClick={() => setCount(count - 1)}
style={{
padding: '15px 30px',
fontSize: '20px',
background: '#764ba2',
color: 'white',
border: 'none',
borderRadius: '10px',
cursor: 'pointer',
margin: '10px'
}}
>
Decrement
</button>
</div>
);
}
ReactDOM.render(<Counter />, document.getElementById('root'));
`;
fetch(apiUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
language: 'react',
code: reactCode
})
})
.then(res => res.json())
.then(data => {
// React runs client-side, so preview_url contains the full app
window.open(data.preview_url, '_blank');
});
Advantages of Docker Sandbox
β vs Regular Hugging Face Spaces
- Complete Isolation - Each execution is fully isolated
- Resource Control - Strict memory and CPU limits
- No Contamination - Containers destroyed after use
- Multiple Runtimes - Python, Node, Ruby, etc. in separate containers
- Security - No network, no persistence, no escape
β vs Local Sandboxie
- Cloud-Native - No local installation needed
- Always Available - 24/7 API access
- Scalable - Handles multiple concurrent requests
- Platform Independent - Works from any device
β vs Process-Based Execution
- Better Isolation - Container vs process boundaries
- Cleaner Cleanup - No orphaned processes
- Reproducible - Same environment every time
- Safer - Can't access host filesystem
Monitoring
Health Check
curl https://YOUR_USERNAME-your-docker-sandbox.hf.space/health
Response:
{
"status": "healthy",
"docker_available": true
}
Container Stats
The Docker executor automatically:
- Removes containers after execution
- Logs container lifecycle events
- Tracks resource usage
- Enforces timeouts
Troubleshooting
"Docker not available"
Solution: Ensure Space is using Docker SDK:
- Space Settings β SDK β Select "Docker"
- Wait for rebuild
- Check
/healthendpoint
Execution Timeout
Solution: Increase timeout in request:
{
"language": "python",
"code": "...",
"timeout": 60
}
Container Memory Error
Solution: Optimize code or contact HF support for higher limits
Network Errors in Container
Expected: Containers have network_mode="none" for security
- React/HTML work because they run client-side
- Python/JavaScript run server-side without network
Performance
Typical Execution Times
- Python simple: ~0.5-1s (container startup + execution)
- JavaScript simple: ~0.6-1.2s
- React: ~0.1s (client-side, no container)
- HTML: ~0.05s (client-side, no container)
Cold Start
First execution may take 2-5 seconds to pull Docker images.
Best Practices
1. Choose Right Language
- Use React/HTML for UI apps (faster, client-side)
- Use Python/JavaScript for computation (secure, isolated)
2. Optimize Code
- Keep execution time under 10 seconds
- Avoid heavy computations in containers
- Use React for interactive UIs
3. Handle Errors
try {
const response = await fetch(apiUrl, { ... });
const data = await response.json();
if (data.status === 'error') {
console.error('Execution failed');
}
} catch (error) {
console.error('API error:', error);
}
Future Enhancements
- Multi-language containers (Go, Rust, Ruby)
- Custom Docker images
- Volume mounting for data
- WebSocket for real-time output
- GPU support for ML workloads
License
MIT License - Feel free to use and modify!
Questions? Open an issue or discussion on the Space!