AI Agent Sandboxing

Set up a safe, isolated development environment where AI agents can work on your codebase without risking your machine, secrets, or production systems.

Developers + teams20 minute readReviewed July 24, 2026

Why Sandboxing Matters for AI Agents

AI agents that edit code, run commands, or install packages introduce risks that go beyond normal human developer mistakes. A confident but incorrect instruction can delete files, overwrite configuration, install malicious packages, leak secrets into logs, or break production. Sandboxing contains these risks by giving the agent a controlled environment that is separated from your machine, your credentials, and your production systems.

Accidental data exposure

An agent writes a secret key to a log file, commits it, or sends it to an external API during a debugging step.

Unintended system changes

Running a package installer or system command can modify shared libraries, change permissions, or alter host configuration.

Supply-chain risk

Installing an unvetted package from the internet inside your development environment can introduce backdoors that persist across sessions.

Production drift

Changes made directly on a production server or shared development machine can break other developers' workflows or introduce inconsistent state.

Core principle: an AI agent should never have direct access to your host machine, your production systems, or your real credentials. Every agent session should run inside a bounded, disposable environment with the minimum permissions required for the task.

Docker: The Foundation

Docker containers provide process isolation, filesystem boundaries, and resource limits in a portable package. For AI agent workflows, containers are the most practical sandbox because they are reproducible, version-controlled, and easy to destroy and recreate.

Key Docker concepts for sandboxing

ConceptWhat it doesWhy it matters for AI agents
ContainerIsolated process with its own filesystem, network, and PID namespaceAgent actions cannot escape to the host machine
ImageRead-only template that defines the environmentEnsures every agent session starts from a known, audited state
VolumePersistent data stored outside the containerAllows shared workspace while keeping the container ephemeral
Network isolationContainers can be isolated from each other and the hostPrevents agents from reaching internal services or the internet unintentionally
User namespaceRuns processes as a non-root userReduces the impact of container escape or privilege escalation

Quick start: creating a sandbox

Without sandboxing
# Agent runs commands directly on your machine npm install express python -m http.server 8080 rm -rf node_modules
With sandboxing
# Agent runs inside a container docker run -it -v $(pwd):/app -w /app node:20-alpine \ npm install express docker run -it -v $(pwd):/app -w /app python:3.12-slim \ python -m http.server 8080 docker run -it -v $(pwd):/app -w /app node:20-alpine \ rm -rf node_modules

Writing a Dockerfile for AI Agents

A Dockerfile defines your development environment as code. When AI agents read and work with your project, they can build and use this file to create a consistent sandbox. The Dockerfile should be explicit, minimal, and designed for reproducibility.

Example: Dockerfile for a static site project

Vague base image
# Bad: pulls the latest tag, includes unnecessary tools FROM ubuntu RUN apt-get update && apt-get install -y python3 WORKDIR /app COPY . . CMD ["python3", "-m", "http.server", "8080"]
Explicit, minimal image
# Good: pinned version, small base, non-root user FROM python:3.12-slim@sha256:EXAMPLE_DIGEST WORKDIR /app COPY . . RUN groupadd -r appuser && useradd -r -g appuser appuser USER appuser EXPOSE 8080 CMD ["python3", "-m", "http.server", "8080"]

Best practices for agent-facing Dockerfiles

  • Pin your base image with a specific version tag or SHA256 digest. Agents should not pull "latest" because it can change without warning.
  • Use slim or alpine variants to reduce the attack surface and build time. Fewer pre-installed tools mean fewer accidental capabilities.
  • Create a non-root user and switch to it with USER. Even inside a container, running as root gives an agent unnecessary power.
  • Pin installed package versions where possible. Use exact version numbers in apt, pip, or npm installs.
  • Separate build steps using multi-stage builds if needed. Keep build tools out of the final image.
  • Document the environment with comments explaining why each layer exists. Agents that read the Dockerfile should understand the intent.
  • Include a .dockerignore file to prevent secrets, credentials, node_modules, and build artifacts from entering the container.

Example .dockerignore

Recommended .dockerignore
node_modules .env *.key *.pem .git .env.local dist build *.log .DS_Store coverage

Docker Compose for Multi-Service Projects

Most projects involve more than one service: a web server, a database, a cache, or an API. Docker Compose lets you define the entire environment in a single file that AI agents can read, modify, and rebuild.

Example: docker-compose.yml for a static site with a database

docker-compose.yml
version: "3.9" services: web: build: . ports: - "8080:8080" volumes: - ./public_html:/app:cached environment: - NODE_ENV=development networks: - app-network read_only: true tmpfs: - /tmp db: image: postgres:16-alpine environment: POSTGRES_DB: app_db POSTGRES_USER: app_user POSTGRES_PASSWORD_FILE: /run/secrets/db_password volumes: - db-data:/var/lib/postgresql/data networks: - app-network read_only: true networks: app-network: driver: bridge volumes: db-data:

Compose security features for agent sandboxes

  • read_only: true prevents containers from writing to their own filesystem, limiting what an agent can change at runtime.
  • tmpfs mounts give agents a temporary write area for logs and caches that disappears when the container stops.
  • Secrets management via Docker secrets keeps credentials out of environment variables and compose files.
  • Network isolation via custom bridge networks prevents containers from reaching the host network.
  • Resource limits using deploy.resources prevent runaway processes from consuming all host memory or CPU.

Example with resource limits

Adding resource limits
services: web: build: . deploy: resources: limits: cpus: "1.0" memory: 512M pids: 100 reservations: cpus: "0.25" memory: 128M

Git Workflow with Agent Access

Git provides a safety net for AI agent work. Every change is tracked, reversible, and reviewable. When AI agents modify your codebase, use Git to contain their work in branches and require human review before merging.

Recommended agent workflow

1

Create an agent branch

Start every agent session on a fresh branch named for the task: agent/fix-login-bug or agent/add-landing-page. Never let an agent commit to main or develop.

2

Commit small, atomic changes

Encourage the agent to commit frequently with descriptive messages. This makes it easy to undo a specific change if something goes wrong.

3

Review before merging

Always review the agent's changes with git diff or a pull request before merging. An agent can make technically correct changes that are wrong for your project.

4

Use pre-commit hooks

Add linting, formatting, and secret-scanning hooks that run automatically on every commit. This catches mistakes before they reach the branch history.

5

Keep a CHANGELOG

Maintain a changelog that the agent reads before making changes. This helps the agent understand what has recently changed and avoid conflicts.

Example pre-commit hook for secret scanning

.git/hooks/pre-commit
#!/bin/bash # Block commits containing common secret patterns if git diff --cached --diff-filter=ACM | \ grep -qE '(api_key|secret|password|token)\s*=\s*["\x27][^"\x27]{8,}'; then echo "ERROR: Possible secret detected in staged files." echo "Review and remove secrets before committing." exit 1 fi exit 0

Secrets and Environment Isolation

AI agents can read files, run commands, and generate output that may accidentally include secrets. Protect credentials using layered isolation.

RiskDefenseAgent-specific concern
Secrets in source codeUse environment variables, secret managers, or Docker secrets. Never commit credentials.An agent may be asked to "fix the database connection" and accidentally paste a real key into a prompt or file.
Secrets in logsConfigure log rotation and redaction. Use structured logging that separates data from metadata.An agent running debug commands may dump environment variables or connection strings to stdout.
Secrets in Docker imagesNever use ENV or ADD/COPY for secrets. Use build secrets or runtime secrets.An agent building an image may accidentally include a .env file in the image layer.
Secrets in promptsNever paste real credentials into an AI prompt. Use placeholders like [DB_PASSWORD].This is the most common and most dangerous risk. Train agents and users to redact before prompting.

Golden rule: if an AI agent asks you to read a file that contains secrets, the agent should receive a redacted version. Never provide real API keys, passwords, or tokens to an AI agent session.

Network Isolation

Network controls determine what an AI agent can reach from inside the sandbox. By default, containers have internet access, which may be too permissive for agent work.

Network strategies

Full internet access

Default Docker behavior. Suitable for agents that need to install packages or fetch documentation. Add rate limiting and monitoring.

Internal network only

Use Docker networks to allow agent access to internal services (database, cache) while blocking internet. Good for agents working on internal tooling.

Fully isolated

No network access. Suitable for agents that only edit static files or run local builds. Prevents any outbound data exfiltration.

Proxy-controlled

All outbound traffic goes through a proxy that enforces allowlists, logging, and content filtering. Best for enterprise environments.

Example: isolated network in Docker Compose

No external network access
services: web: build: . networks: - isolated extra_hosts: - "host.docker.internal:host-gateway" networks: isolated: internal: true

Agent Safety Practices

Beyond the technical infrastructure, establish operational practices that keep AI agent work safe and auditable.

  • Define an agent permissions policy that specifies what each agent can and cannot do: which files to edit, which commands to run, which services to access.
  • Use a manifest file (e.g., agent-workspace.json) that describes the project structure, available commands, and agent capabilities. Agents can read this to understand their boundaries.
  • Run agents in ephemeral containers that are destroyed after each task. This prevents state accumulation and reduces the impact of mistakes.
  • Log all agent actions including commands run, files read, and files written. Store logs outside the container for audit purposes.
  • Set time and resource budgets per agent session. An agent that runs too long or uses too much memory may be stuck in a loop or behaving unexpectedly.
  • Require human approval for destructive actions such as deleting files, modifying production configuration, or running database migrations.
  • Test agent output before deploying even if the agent says "tests pass." Run your own validation, review the diff, and verify the behavior in staging.

Example: agent workspace manifest

agent-workspace.json
{ "project": "Chiang Rai AI Think Tank", "root": "/app", "allowed_commands": ["python3", "npm", "git", "cat", "grep"], "forbidden_commands": ["rm -rf", "sudo", "docker"], "editable_files": ["*.html", "*.css", "*.js", "*.php"], "protected_files": ["Dockerfile", "docker-compose.yml", ".env"], "max_session_minutes": 30, "max_memory_mb": 512 }

Practice: Set Up Your First Agent Sandbox

  1. Create a new project directory and initialize a Git repository.
  2. Write a simple Dockerfile for your project's runtime language (Python, Node.js, etc.).
  3. Create a .dockerignore file that excludes secrets, node_modules, and build artifacts.
  4. Build the image and run a container with your source code mounted as a volume.
  5. Test that the agent can read and edit files inside the container without affecting your host.
  6. Add a pre-commit hook that scans for secrets.
  7. Write an agent-workspace.json manifest describing your project boundaries.

Continue learning