HMM / README.md
Speedofmastery's picture
Auto-commit: README.md updated
54c9eed
|
raw
history blame
10.9 kB
metadata
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

  1. Go to Space Settings
  2. Under "Advanced", enable "Docker SDK"
  3. Set "Timeout" to 60+ seconds
  4. 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 container
  • javascript - Node.js 18 in Alpine container
  • react - 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

  1. Complete Isolation - Each execution is fully isolated
  2. Resource Control - Strict memory and CPU limits
  3. No Contamination - Containers destroyed after use
  4. Multiple Runtimes - Python, Node, Ruby, etc. in separate containers
  5. Security - No network, no persistence, no escape

βœ… vs Local Sandboxie

  1. Cloud-Native - No local installation needed
  2. Always Available - 24/7 API access
  3. Scalable - Handles multiple concurrent requests
  4. Platform Independent - Works from any device

βœ… vs Process-Based Execution

  1. Better Isolation - Container vs process boundaries
  2. Cleaner Cleanup - No orphaned processes
  3. Reproducible - Same environment every time
  4. 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:

  1. Space Settings β†’ SDK β†’ Select "Docker"
  2. Wait for rebuild
  3. Check /health endpoint

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!