Build a Sandboxed AI Agent on Ubuntu Using Docker/gVisor
You are running an AI agent on your Linux server. It pulls code from an LLM, writes it to disk, executes it. Maybe it has access to your SSH keys, your cloud credentials, your database. The agent runs in a Docker container, so you are safe—right?
Not quite. Default Docker uses runc, which shares the host kernel. A kernel exploit, a misconfigured capability, a malicious package with a container escape payload—one breakout and the attacker has root on your host. This is not theoretical. CVE-2019-5736 (runc container escape) and CVE-2022-0811 (CRI-O escape) both allowed full host compromise from inside a container.
AI agents amplify this risk. They execute arbitrary code generated by an LLM. That code can include ptrace attacks, /proc enumeration, kernel module loading attempts, or supply-chain exploits hidden in dependencies. OWASP LLM Top 10 lists “Insecure Plugin Design” and “Excessive Agency” as top risks—both directly relevant when an agent can run code.
This post shows you how to run AI agents in Docker with gVisor (the runsc runtime), which intercepts every syscall in userspace instead of passing it to the host kernel. Combined with rootless Docker, you get defense in depth: even if the agent escapes the container, it lands in an unprivileged user namespace—not root on your host.
We will build a working sandboxed AI agent on Ubuntu 24.04, verify the isolation, and measure the performance cost. All commands tested on Ubuntu 24.04 LTS with Docker 27.x and gVisor 2024-10.
Why Default Docker Is Not Enough for AI Agents
Docker default isolation relies on Linux namespaces (PID, network, mount, UTS, IPC, cgroup) and seccomp-bpf syscall filtering. This stops casual mistakes but not determined attackers.
The Threat Model for AI Agents
An AI agent typically:
- Runs as root inside the container (many base images default to root)
- Has broad filesystem access to read/write project files
- Executes
pip install,npm install, orcargo buildon untrusted dependencies - May need network access to call APIs (OpenAI, Anthropic, local LLMs)
- Often mounts the host Docker socket (
/var/run/docker.sock) for “docker-out-of-docker” patterns—this is game over for isolation
A container escape here does not just leak data—it gives the attacker a persistent foothold on your build server, CI runner, or developer workstation.
What Namespaces Do Not Protect
Namespaces isolate visibility, not execution. The container still makes raw syscalls to the host kernel. If there is a vulnerability in the kernel syscall handler (and there have been many), the container triggers it directly.
Seccomp helps but is a blocklist, not an allowlist. The default Docker seccomp profile blocks ~44 syscalls out of 300+. The rest—including ptrace, bpf, clone with dangerous flags—are allowed.
How gVisor Works (Without the Marketing)
gVisor implements a Linux kernel in userspace (written in Go). Your container makes syscalls to gVisor kernel (called Sentry), which validates and emulates them. Only gVisor itself talks to the host kernel—through a minimal, audited interface.
Syscall Interception vs VM Isolation
gVisor (Sentry): Intercepts syscalls in userspace. No hardware virtualization required. ~5-15% overhead. Supports most Linux syscalls but not all.
Kata Containers / Firecracker: Run each container in a lightweight VM. Hardware-enforced isolation. Higher overhead (memory, boot time). Near-complete syscall compatibility.
For AI agents on developer machines or CI runners, gVisor hits the sweet spot: strong isolation, no nested virtualization needed (works in cloud VMs), low enough overhead for interactive use.
gVisor vs Kata Containers vs Firecracker
| Property | gVisor (runsc) | Kata Containers | Firecracker |
|---|---|---|---|
| Isolation boundary | Userspace kernel | Lightweight VM | MicroVM |
| Hardware virt required | No | Yes | Yes |
| Boot time | ~ms | ~1-2s | ~125ms |
| Memory overhead | ~20-50MB | ~50-100MB | ~5-10MB |
| Syscall compatibility | ~95% | ~100% | ~100% |
| GPU support | Experimental | Yes | Limited |
For this tutorial, we use gVisor because it runs anywhere Docker runs—including inside other VMs (GitHub Actions, GitLab CI, cloud VMs without nested virt).
Prerequisites: Ubuntu 24.04, Docker, Rootless Setup
Tested environment:
- Ubuntu 24.04 LTS (fresh VM or clean host)
- Docker Engine 27.x (installed via Docker apt repo)
- User with sudo access (for initial setup only)
We will use rootless Docker so the Docker daemon itself runs as your user—not root. Combined with gVisor, this means: container escape → gVisor Sentry (unprivileged) → rootless Docker daemon (your user) → host kernel. Three boundaries to cross.
Step 1: Install Docker (Rootless Mode)
# Install Docker official apt repository
sudo apt-get update
sudo apt-get install -y ca-certificates curl gnupg
sudo install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
sudo chmod a+r /etc/apt/keyrings/docker.gpg
echo "deb [arch=arm64 signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu "noble" stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update
sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
Now enable rootless mode for your user:
# Run as your NON-ROOT user (not sudo)
dockerd-rootless-setuptool.sh install
# Add to your shell profile (~/.bashrc or ~/.zshrc)
export PATH=/usr/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
export DOCKER_HOST=unix:///run/user/1001/docker.sock
# Reload shell
source ~/.bashrc
# Verify rootless Docker works
docker run --rm hello-world
Checkpoint: docker info | grep -i rootless should show “rootless” in the output. If you see permission errors, log out and back in, or run newgrp docker.
Installing and Configuring gVisor (runsc)
Step 2: Install runsc
# Download latest runsc (check https://github.com/google/gvisor/releases for latest)
curl -fsSL https://storage.googleapis.com/gvisor/releases/release/latest/runsc -o runsc
chmod +x runsc
sudo mv runsc /usr/local/bin/
# Verify installation
runsc --version
# Expected: runsc version 2024-10-... (or similar date-based version)
Step 3: Configure Docker to Use runsc Runtime
Create or edit Docker daemon configuration:
# For rootless Docker, config is in ~/.config/docker/daemon.json
mkdir -p ~/.config/docker
cat > ~/.config/docker/daemon.json << 'EOF'
{
"runtimes": {
"runsc": {
"path": "/usr/local/bin/runsc",
"runtimeArgs": [
"--network=host",
"--platform=ptrace"
]
}
},
"default-runtime": "runc"
}
EOF
# Restart rootless Docker daemon
systemctl --user restart docker
Note on --platform=ptrace: gVisor has two platform backends: ptrace (default, uses ptrace syscall for interception) and kvm (uses KVM for hardware acceleration). ptrace works everywhere including nested VMs. kvm is faster but requires /dev/kvm access. We use ptrace for maximum compatibility.
Step 4: Verify runsc Works
# Test the runtime
docker run --rm --runtime=runsc alpine:3.20 echo "gVisor works"
# Expected output: "gVisor works"
# You should also see a brief pause (~100-300ms) on first run as Sentry starts
Checkpoint: Run docker info | grep -A5 Runtimes — you should see runsc listed alongside runc.
Building the Sandboxed AI Agent Container
Now we build a container for an AI agent. The key principles:
- Run as non-root user (UID 1000)
- Drop all capabilities
- Read-only root filesystem where possible
- Resource limits (CPU, memory, pids)
- No host network, no privileged ports
Step 5: Create the Dockerfile
# Dockerfile.ai-agent
FROM python:3.12-slim-bookworm
# Create non-root user
RUN groupadd -r -g 1000 agent && useradd -r -u 1000 -g agent -m -s /bin/bash agent
# Install system dependencies (as root, then drop privileges)
RUN apt-get update && apt-get install -y --no-install-recommends git curl ca-certificates && rm -rf /var/lib/apt/lists/*
# Set up working directory
WORKDIR /home/agent/workspace
RUN chown agent:agent /home/agent/workspace
# Switch to non-root user
USER agent
# Install Python dependencies (as agent user)
# Example: a minimal agent framework
COPY --chown=agent:agent requirements.txt .
RUN pip install --user --no-cache-dir -r requirements.txt
# Copy agent code
COPY --chown=agent:agent agent.py .
# Default command
CMD ["python", "agent.py"]
requirements.txt example:
openai>=1.0.0
anthropic>=0.25.0
pydantic>=2.0
python-dotenv>=1.0
agent.py (minimal example — replace with your actual agent):
#!/usr/bin/env python3
"""
Minimal AI agent that executes code in a sandboxed environment.
This is a DEMONSTRATION - replace with your actual agent logic.
"""
import os
import sys
import subprocess
import tempfile
from pathlib import Path
def run_code_safely(code: str, timeout: int = 30) -> dict:
"""Execute Python code in a restricted subprocess."""
with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
f.write(code)
script_path = f.name
try:
# Run with restricted environment
result = subprocess.run(
[sys.executable, script_path],
capture_output=True,
text=True,
timeout=timeout,
env={
'PATH': '/usr/local/bin:/usr/bin:/bin',
'HOME': '/home/agent',
'USER': 'agent',
# Explicitly NOT passing through host env vars
},
# These limits require runsc --platform=ptrace (default)
# In gVisor, these are enforced by Sentry
)
return {
'stdout': result.stdout,
'stderr': result.stderr,
'returncode': result.returncode,
'timed_out': False
}
except subprocess.TimeoutExpired:
return {'stdout': '', 'stderr': 'Execution timed out', 'returncode': -1, 'timed_out': True}
finally:
Path(script_path).unlink(missing_ok=True)
def main():
print("Sandboxed AI Agent starting...")
print(f"Running as UID: {os.getuid()}, GID: {os.getgid()}")
print(f"Python: {sys.version}")
# Example: agent receives code from LLM and executes it
test_code = '''
import os
import sys
print(f"Inside sandbox - UID: {os.getuid()}")
print(f"Can read /etc/passwd: {os.path.exists('/etc/passwd')}")
print(f"Can write to /tmp: {os.access('/tmp', os.W_OK)}")
try:
with open('/etc/shadow', 'r') as f:
print("ERROR: Could read /etc/shadow!")
except PermissionError:
print("Correctly denied: /etc/shadow")
'''
result = run_code_safely(test_code)
print(f"Exit code: {result['returncode']}")
print(f"Output:\n{result['stdout']}")
if result['stderr']:
print(f"Errors:\n{result['stderr']}")
if __name__ == '__main__':
main()
Step 6: Build and Run with gVisor
# Build the image
docker build -f Dockerfile.ai-agent -t sandboxed-ai-agent .
# Run with gVisor runtime + security hardening
docker run --rm --runtime=runsc --user 1000:1000 --cap-drop=ALL --security-opt no-new-privileges:true --read-only --tmpfs /tmp:noexec,nosuid,size=100m --tmpfs /home/agent/workspace:rw,noexec,nosuid,size=500m --memory=2g --cpus=2 --pids-limit=100 --network=none sandboxed-ai-agent
Let us break down each flag:
| Flag | Purpose |
|---|---|
--runtime=runsc |
Use gVisor instead of runc |
--user 1000:1000 |
Run as non-root (matches Dockerfile USER) |
--cap-drop=ALL |
Drop all Linux capabilities |
--security-opt no-new-privileges:true |
Prevent privilege escalation via setuid/binaries |
--read-only |
Mount root filesystem read-only |
--tmpfs /tmp:noexec,nosuid |
Writable /tmp but no exec, no setuid |
--memory=2g --cpus=2 |
Resource limits (prevent DoS) |
--pids-limit=100 |
Limit processes (prevent fork bombs) |
--network=none |
No network access (add --network bridge if needed) |
Expected output:
Sandboxed AI Agent starting...
Running as UID: 1000, GID: 1000
Python: 3.12.7 (main, Oct 2 2024, 14:12:34) [GCC 13.3.0]
Inside sandbox - UID: 1000
Can read /etc/passwd: True
Can write to /tmp: True
Correctly denied: /etc/shadow
Exit code: 0
Output:
Inside sandbox - UID: 1000
Can read /etc/passwd: True
Can write to /tmp: True
Correctly denied: /etc/shadow
Verifying Isolation: What the Agent Can and Cannot Do
The container runs. But is it actually isolated? Let us test.
Test 1: Filesystem Access
# Try to read host files from inside container
docker run --rm --runtime=runsc --user 1000:1000 --cap-drop=ALL --security-opt no-new-privileges:true --read-only --tmpfs /tmp:noexec,nosuid sandboxed-ai-agent python3 -c "
import os
# These should work (world-readable)
print('/etc/passwd:', os.path.exists('/etc/passwd'))
print('/etc/hosts:', os.path.exists('/etc/hosts'))
# These should fail
for path in ['/etc/shadow', '/root/.ssh/id_rsa', '/home/youruser/.aws/credentials']:
try:
open(path).read()
print(f'ERROR: Could read {path}')
except PermissionError:
print(f'Correctly blocked: {path}')
except FileNotFoundError:
print(f'Not present: {path}')
"
Result: Host /etc/shadow, SSH keys, and AWS credentials are unreadable. The container sees a minimal filesystem provided by gVisor—not your actual host filesystem.
Test 2: Network Isolation
# With --network=none, no network interfaces except loopback
docker run --rm --runtime=runsc --network=none alpine:3.20 ip addr show
# Expected: only 'lo' interface, no eth0
# Try to connect out (should fail)
docker run --rm --runtime=runsc --network=none alpine:3.20 wget -qO- http://httpbin.org/ip || echo "Blocked as expected"
If your agent needs API access (OpenAI, Anthropic), use --network=bridge (default) instead of --network=none, and consider egress filtering at the host firewall level.
Test 3: Kernel Exploit Mitigation
gVisor blocks syscalls it does not implement. Let us verify:
# Try a syscall gVisor does not support (e.g., ptrace, kexec_load)
docker run --rm --runtime=runsc --user 1000:1000 --cap-drop=ALL alpine:3.20 sh -c "
apk add --no-cache strace >/dev/null 2>&1
strace -e trace=ptrace true 2>&1 | head -5
"
Expected: ptrace returns ENOSYS (function not implemented). The host kernel never sees the syscall—gVisor Sentry intercepts and denies it.
Test 4: Process Namespace Isolation
# Host: run this in another terminal
ps aux | grep -E '(agent|python)' | grep -v grep
# Container: check what processes it sees
docker run --rm --runtime=runsc --user 1000:1000 alpine:3.20 ps aux
The container sees only its own processes (PID 1 = its init). Host processes are invisible.
Performance Trade-offs and Limitations
Benchmark Expectations
Based on gVisor published benchmarks and our testing:
| Workload | Overhead vs runc | Notes |
|---|---|---|
| CPU-bound (compute, ML inference) | ~5-10% | Minimal syscall traffic |
| I/O-bound (file reads/writes) | ~10-20% | Each read/write goes through Sentry |
| Syscall-heavy (strace, compilers, builds) | ~15-30% | Many syscalls = more interception |
| Network-heavy | ~5-15% | Depends on packet size/frequency |
| Container startup | +100-300ms | Sentry initialization |
For AI agents (mostly CPU + some file I/O), expect ~10% overhead. The security gain far outweighs this cost.
Compatibility Gaps
gVisor does not implement every Linux syscall. Known gaps as of 2024-10:
ptrace— Not supported. Debuggers,strace, some profilers won't work inside.- Some
io_uringoperations — Partial support. - Kernel module loading — Intentionally blocked (
init_module,finit_module). - Some filesystem operations —
fanotify, certainioctls. - eBPF — Not supported inside gVisor (would defeat the purpose).
If your agent needs these, you have two options:
- Use
--platform=kvm(requires/dev/kvmaccess, not available in nested VMs) - Switch to Kata Containers (full VM, supports everything)
Rootless Docker Limitations
Rootless Docker maps your user to root inside the container via user namespaces. This means:
- Files created as root in container = owned by your user on host
ping,traceroutedon't work (no CAP_NET_RAW)- Port binding < 1024 requires
sysctl net.ipv4.ip_unprivileged_port_start=0 - Some filesystems (NFS, CIFS) have permission mapping issues
For AI agents, these are acceptable trade-offs. The agent runs as UID 1000 anyway.
When Not to Use This Approach
This setup is not appropriate for:
- High-security multi-tenant environments — Use Kata Containers/Firecracker with hardware virtualization. gVisor userspace kernel has a larger attack surface than a VMM.
- Workloads requiring
ptraceor eBPF — Debuggers, profilers, tracing tools won't work. - GPU-accelerated ML workloads — gVisor GPU support is experimental. Use Kata + NVIDIA Container Toolkit or bare-metal with proper isolation.
- Kernel development — You need the real kernel.
It is appropriate for:
- Developer workstations running local AI agents
- CI/CD runners executing untrusted code
- Single-tenant servers hosting multiple agents
- Any environment where nested virtualization is unavailable
Conclusion
We have built a sandboxed AI agent using Docker + gVisor + rootless mode on Ubuntu 24.04. The isolation stack:
- Application level: Non-root user, dropped capabilities, read-only rootfs, resource limits
- Container runtime: gVisor intercepts syscalls in userspace (Sentry)
- Daemon level: Rootless Docker runs as your user, not root
An attacker escaping the agent code execution hits gVisor syscall filter. Escaping gVisor lands them in your user namespace—not root. Three meaningful boundaries.
Next steps for production:
- Add Trivy scanning to your build pipeline
- Use Distroless base images (no shell, no package manager)
- Implement egress firewall rules (allow only API endpoints your agent needs)
- Monitor gVisor logs (
journalctl --user -u docker) for denied syscalls - Consider OPA Gatekeeper for Kubernetes deployments
FAQ
Does gVisor work with GPU acceleration?
Experimental support via nvidia-container-toolkit and --platform=kvm. Not recommended for production yet. For GPU workloads, use Kata Containers with NVIDIA support or run on bare metal with proper device isolation.
Can I use this in production?
Yes. Google uses gVisor in production for Cloud Run and Cloud Functions. It is battle-tested at massive scale.
What about rootless Podman instead of Docker?
Podman + gVisor works similarly (podman run --runtime=runsc). Podman daemonless architecture avoids the rootless Docker daemon complexity. Both are valid; Docker has broader ecosystem tooling.
How do I debug issues inside the gVisor container?
Since strace and ptrace don't work, use:
- Application-level logging (structured logs to stdout)
docker logsfor container output- gVisor debug logs:
runsc --debug --debug-log=/tmp/runsc.log - Build a debug variant of your image with debugging tools installed
Does this protect against prompt injection?
No. This protects the host from the agent executed code. Prompt injection (where the LLM is tricked into malicious behavior) is an application-layer problem—address it with input validation, output parsing, and capability restrictions in your agent framework.