@haram

Docker Sandbox Integration — Preventing Dangerous Code Execution by Local AI Agents
What happens if you let an AI agent you created execute arbitrary Python code on your PC without restrictions? You could be exposed to the risk of 'agent hijacking,' where the agent—tricked by malicious prompts or external instructions—steals sensitive files or executes destructive system commands.
In this post, we’ll explore how to easily set up a local isolation layer using Docker, allowing you to experiment with AI to your heart's content while keeping your precious PC completely secure.
Why are Python's built-in guardrails insufficient?
When building AI agents, a common mistake is to implement guardrails by checking text within Python code, such as "do not use certain libraries" or "do not execute dangerous commands."
However, Python is an incredibly flexible and dynamic language, making these limitations extremely easy to bypass. There are endless creative ways to exploit class inheritance structures or leverage runtime weaknesses. Just like closing a room's door while leaving a "forbidden" note on the wall, this approach cannot stop clever workarounds.
This threat, where an AI agent is tricked by malicious prompts into executing arbitrary commands on a user's PC, is called Agent Hijacking (OWASP ASI05). Once this shield is breached, it can lead to devastating consequences, such as deletion of project files in the local directory or the exfiltration of core secrets like API keys or SSH keys.
Ultimately, what we need is not warnings that can be blocked by a few lines of code, but a 'locked playground' where an agent can play freely without ever being able to escape. Even if malicious code is executed, it must be contained within the isolated environment, unable to touch your actual computer. Docker is the perfect solution for providing this robust, physical fence in a local development environment.
5 Key Settings for Creating a Secure Docker Sandbox
Simply running a Docker container isn't enough for peace of mind. Default Docker settings can still leave subtle gaps that allow the container to peek at host system resources or consume excessive hardware. To turn your agent's environment into a safe sandbox, you must firmly lock the doors leading outside.
Here are 5 of the most effective security locks that you can specify in the Python Docker SDK or configuration files.
- 네트워크 차단 (
network_mode='none'): 컨테이너 안에서 실행되는 코드가 인터넷에 접속하는 길을 원천 봉쇄합니다. 내 중요한 정보를 외부 서버로 유출하지 못하도록 사방을 높은 벽으로 막아두는 역할을 합니다. - 읽기 전용 파일시스템 (
read_only=True): 컨테이너 내부의 핵심 시스템을 얼려둡니다. 대신 임시 작업 공간은 메모리 위에 아주 작게 만들어 주는tmpfs설정을 더해, 칠판에 낙서만 할 수 있고 벽 자체는 부수지 못하게 만듭니다. - 모든 특권 해제 (
cap_drop=['ALL']): 컨테이너가 가질 수 있는 강력한 시스템 관리 권한을 모두 빼앗아 버립니다. 여기에security_opt옵션을 더하면 에이전트가 어떤 꼼수를 쓰더라도 관리자 권한을 새로 얻어낼 수 없습니다. - 비루트 사용자 실행 (
user='1000:1000'): 최고 관리자인 루트가 아니라 권한이 거의 없는 일반 사용자로 코드를 실행하게 만듭니다. 이중 자물쇠를 채워 혹시 모를 시스템 침입에 대비하는 조치입니다. - 리소스 한계 설정 (
mem_limit='256m'): 메모리와 CPU 사용량에 명확한 한계를 설정합니다. 코드가 무한 루프에 빠져 폭주하더라도 내 실제 컴퓨터가 멈추거나 느려지지 않도록 차단기를 내리는 것입니다.
Combining these 5 locks effectively eliminates almost any risk of a local agent damaging your computer.
Easier Integration: Mastra Framework and Code Sandbox MCP
Manually coding the complex Docker settings mentioned above can be quite tedious for developers. Fortunately, the AI ecosystem now includes smart tools that handle these security isolation tasks for you.
The most prominent tool is Mastra, a TypeScript-based AI agent framework. By utilizing the @mastra/docker package, you can safely create and control local Docker containers with just a few lines of code. Rules like memory limits or network blocking can also be defined intuitively within configuration files.
// Mastra의 DockerSandbox 설정 예시
import { DockerSandbox } from '@mastra/docker';
const sandbox = new DockerSandbox({
image: 'python:3.11-slim',
containerConfig: {
networkDisabled: true,
HostConfig: {
Memory: 256 * 1024 * 1024, // 256MB 제한
NanoCpus: 1000000000, // 1 CPU 코어 제한
},
},
});For developers directly using LLM clients like Claude or Gemini, integrating the 'Code Sandbox MCP' from the Model Context Protocol (MCP) ecosystem is another excellent choice. This tool automatically manages the lifecycle of Docker containers in the background, executing agent-generated code in an isolated space and returning only the results. Since it eliminates the need to write complex container management code, it's highly useful in the early stages of service development.
Secure Agent Development, Start with a Local Sandbox
Establishing an isolation layer using Docker in your local environment is the most critical first step in AI agent security.
While production-grade service operations may require more robust virtualization solutions, the Docker settings introduced today provide an excellent shield for personal experiments on your PC. Keep your computer secure while building freer and smarter AI agents!