Run an AI agent in a sandbox

To isolate an AI agent, run its commands in an environment that restricts the files it can access, the network connections it can make, and the resources it can consume. A sandbox limits the consequences of an error or a hijacked agent, but it cannot guarantee that data will stay private or that actions within authorized services will be safe.
1. Define the boundaries before starting the agent
Prerequisites: a Linux test machine, a Bash terminal, a working Docker installation, and an image of your agent already prepared and available locally. The image must include its dependencies and a sh interpreter. This tutorial starts after installation: there is no universal command that works for every agent.
The example uses Linux containers and a local Docker Engine. With a remote engine, shared paths refer to the machine running the engine. You will also need to adapt permission handling if you use a different environment.
Start with a narrow task: analyze dummy documents and produce a report in a dedicated folder. Keep credentials, customer data, and business integrations out of this first check. The guide to securing an AI agent can help you define appropriate permissions afterward.
A sandbox enforces technical restrictions. An instruction telling an agent to stay within a folder will not block a command that accesses files outside it.
| Control | Starting configuration | Extension to consider |
|---|---|---|
| Files | Read-only inputs | Editable working copy |
| Network | No external connections | Explicitly allowed destinations |
| Secrets | No credentials | Dedicated access with limited permissions |
| Business actions | No integrations | Drafts submitted for approval |
This gradual approach applies the principle of least privilege. Define the expected result and stopping conditions as well: an agent that gets blocked should not automatically receive more permissions.
2. Prepare disposable data and identify the image
Create a new folder. Avoid copying your home directory or an entire repository into it out of habit. Configuration files, backups, and histories may contain secrets the task does not need.
On the host machine, prepare this directory structure:
mkdir -p sandbox-agent/entree sandbox-agent/sortie
printf '%s\n' 'Document fictif à analyser.' \
> sandbox-agent/entree/exemple.txt
cd sandbox-agent
The input folder will be read-only. The output folder will be writable: treat everything in it as disposable and potentially malicious. The bind mount documentation explains that shared folders are writable by default, so you must explicitly set the read-only restriction.
Next, choose the image of your agent that you have already checked. Avoid a floating reference for a test you want to reproduce: use the digest reference supplied by your registry. The container execution documentation describes how to identify an image by its digest.
The following command asks for that reference without assuming an image name:
read -r -p 'Référence complète de votre image vérifiée : ' AGENT_IMAGE
Check the image’s origin and contents before continuing. A sandbox does not make an unknown image trustworthy.
Do not share the Docker socket, SSH keys, or cloud configuration folders. Also avoid symbolic links in the prepared data: a simple directory structure is easier to review and reduces ambiguity when retrieving results.
3. Start a locked-down environment
The command below is an example configuration to adapt, built using options from the official Docker reference. It opens a terminal in the selected image; it does not assume any particular command for starting your agent.
docker run --rm -it \
--name agent-bac-a-sable \
--pull=never \
--network none \
--read-only \
--user "$(id -u):$(id -g)" \
--cap-drop ALL \
--security-opt no-new-privileges=true \
--memory 1g \
--memory-swap 1g \
--cpus 1 \
--pids-limit 128 \
--tmpfs /tmp:rw,nosuid,nodev,size=256m,mode=1777 \
--mount "type=bind,src=$(pwd)/entree,dst=/entree,readonly" \
--mount "type=bind,src=$(pwd)/sortie,dst=/sortie" \
--workdir /sortie \
--env HOME=/tmp \
--entrypoint sh \
"$AGENT_IMAGE"
The memory, CPU, process, and temporary storage limits are choices for this example, not measured requirements for an agent. Adjust them to the expected workload. They do not cap the size of the output folder on the host or any API bill.
The process runs with your user ID and no additional Linux capabilities. The root filesystem is read-only; necessary writes go to the output folder and temporary storage. The image must support this setup without an administrator account.
Keep the default seccomp profile when it is available. If an error occurs, identify its cause before changing the protection.
With networking disabled, only the loopback interface remains. An agent that depends on a remote API therefore cannot work yet: this step checks its execution environment first.
4. Test blocked operations before the first task
Run these simple checks in the container’s terminal:
id
touch /entree/ecriture-interdite
touch /ecriture-interdite
printf '%s\n' 'sortie autorisée' > /sortie/controle.txt
printf '%s\n' 'temporaire autorisé' > /tmp/controle.txt
test ! -S /var/run/docker.sock && printf '%s\n' 'Socket Docker absent'
Writes to the input folder and the filesystem root should fail. Writes to the output folder and temporary storage should succeed. Also check that the displayed user ID does not belong to the administrator account.
These are targeted functional checks, not a security audit. In particular, the absence of a socket at this location does not prove that every other administration interface is absent.
From another terminal on the host, inspect the actual configuration:
docker inspect agent-bac-a-sable
Check the mounts, network, user, and limits. If your image includes a network diagnostic tool, also attempt a connection to a test destination: it should fail. A missing program is not evidence that a connection was blocked.
Then start your agent using the command documented for your own image. Give it a bounded instruction: read the dummy document and write a report to the output folder. Without a bundled local model, this task will have to wait until the networking step.
Finally, add a dummy document containing a prompt injection that asks the agent to perform a prohibited write. The intended outcome is for the environment to block the operation, even if the agent follows the malicious instruction. Our article on prompt injection explains why this check complements the instructions given to the model.
5. Add only the access the agent needs
To use a remote model, plan a second network configuration. Simply removing the block makes external communication possible; that requires a fresh review of the files and secrets the agent can access.
One architecture to consider keeps execution tools offline and handles model calls in a separate service. That service holds the credentials and forwards only the necessary data. Any data sent to the model still leaves the sandbox, even when the process executing code remains isolated.
If the agent itself needs network access, enforce restrictions through the infrastructure: a mandatory gateway, destination filtering, and blocked direct connections. A proxy configuration variable is not enough if the program can bypass it.
Also distinguish technical permissions from authorization to take business actions. Access to an email service can allow an unwanted message to be sent without anything escaping the container. Prepare drafts in the isolated environment, then require approval outside it before sending.
For connectors, the guide to choosing an MCP server adds another part of this review. A remote server acts with its own credentials: isolating the local terminal does not automatically reduce that server’s permissions.
Finally, treat results as untrusted data. Review changes before incorporating them, and do not run an agent-generated script directly on your workstation. The article on AI agent security covers these other sources of risk.
Common problems
The agent will not start. It may be trying to write its configuration to a protected location or require a named user. Prepare a suitable image, then add only the writable locations you have identified. Do not make the entire root filesystem writable to fix a cache error.
The output files are inaccessible. Check ownership and permissions on the host folder, along with any local security rules. Avoid granting write access to all users.
The process stops during a task. Check its status and error messages before raising the limits. Resource exhaustion may result from a legitimate workload, a loop, or an excessive number of child processes.
The container appears isolated but has broad permissions. Look for additional mounts, business integrations, and administration interfaces. The Docker Engine security documentation explains that containers share kernel mechanisms and that some configurations compromise isolation.
Rootless mode reduces some risks associated with the engine. For potentially hostile code, consider a dedicated, disposable virtual machine with no shared sensitive data.
Checklist before use
Exit the container’s terminal after the test. In this configuration, automatic container removal does not delete the shared folders: inspect their contents and create a clean environment for the next task.
- The supplied data is necessary and contains no unnecessary secrets.
- Prohibited writes fail, and permitted output writes succeed.
- External connections are blocked or explicitly controlled.
- Resource limits and stopping conditions are defined.
- Sensitive actions require approval outside the environment.
- Results will be reviewed before use.
The AI agent security assessment can help you expand this checklist based on the access you actually grant.
Frequently asked questions
Is a container enough to secure an AI agent?
A container provides a layer of isolation whose effectiveness depends on the permissions you grant. For potentially hostile code, also consider a dedicated, disposable virtual machine with no shared folders containing sensitive data.
Can I use a model API without opening access to the entire internet?
Yes, with an architecture that forces communication through a controlled gateway. Filtering must be enforced beyond the agent's reach and account for the destinations it actually needs.
Is a Python virtual environment a sandbox?
A virtual environment separates Python dependencies. It does not create a security boundary around files, network connections, or commands running with your account's permissions.
Should I give the isolated agent my API key?
Avoid passing in a general-purpose key when a gateway can hold the secret and make authorized calls. If a key must enter the environment, dedicate it to that use, restrict its permissions, and plan how to revoke it.