跳到正文
DEV Community· AI Release·· 4 小時前AI 評分68

如何在 Docker 中隔離 AI 編碼智能體並限制權限

Running an AI coding agent in Docker: isolation, permissions, safety

AI 導讀

AI Release 的教學示範如何在 Docker 中隔離 AI 編碼智能體,並以非 root 使用者、唯讀檔案系統及網絡和掛載限制收緊權限。教學提供建置、啟動和驗證命令,並建議只掛載一個所需目錄,按工作需要設定網絡及資源限制。Docker 容器仍與主機共用核心;面對真正具敵意的程式碼,可額外使用 rootless mode 或 user namespaces。

正文

Agents do more than chat. They run shell commands, read files, and hit APIs — and if you start one from your home directory, it inherits your SSH keys, your cloud credentials, and your entire filesystem along with them. I still want a coding agent around; I just don't want it holding the keys to my machine.

The recipe below puts the agent inside a Docker container (the isolated, disposable box that packages an app together with its dependencies) and then tightens that box: a non-root user, a read-only root filesystem, every Linux capability dropped, and no network unless the job genuinely needs one. It applies to anything that ships a CLI or a Python entry point, on Docker Engine 24+ or Docker Desktop 4.x across Linux, macOS, and Windows with WSL2.

What you need before you start

  • Docker Engine 24+ or Docker Desktop 4.x — confirm with docker --version.
  • A terminal. On Windows, work inside WSL2 so Linux containers run natively.
  • About 2 GB of free disk: a slim Python base image plus the agent's dependencies land roughly there.
  • An API key for your model provider, kept in a .env file rather than baked into the image.
  • The agent's code or CLI — a main.py, or a package you install with pip.
  • Docker Compose v2, but only if you also want a local model running in a second container.
  • Basic shell skills: cd, ls, chmod.

Start with a sanity check: docker run --rm hello-world should print a message beginning with Hello from Docker! and exit with code 0. That proves the daemon is up and your user is allowed to talk to it.

Next, create the project folder and the secrets file:

mkdir -p ~/agent-sandbox/workspace && cd ~/agent-sandbox
printf 'LLM_API_KEY=sk-your-key-here\n' > .env
chmod 600 .env

ls -la should now show .env as -rw-------. Only your user can read it, and since the file lives outside the image, the key never becomes a permanent build layer.

Build an image that runs as a normal user

FROM python:3.12-slim
RUN useradd -m -u 1000 agent && mkdir /workspace && chown agent /workspace
WORKDIR /app
COPY --chown=agent requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY --chown=agent . .
USER agent
CMD ["python", "main.py"]

USER agent is the line that matters: the process runs as UID 1000 instead of root, so if it slips out of its own code path it still can't rewrite system files. Also put .env and *.key into .dockerignore so secrets can't be copied in by accident.

Then build it:

docker build -t my-agent:0.1 .

The final line should read Successfully tagged my-agent:0.1. The tag gives you a fixed name to reference later, and because pip install is cached, rebuilds are fast.

Start it with the hardened flags

docker run --rm -it --name agent \
  --user 1000:1000 \
  --read-only \
  --tmpfs /tmp:rw,noexec,nosuid,size=64m \
  --cap-drop=ALL \
  --security-opt no-new-privileges \
  --memory=2g --cpus=1.5 --pids-limit=256 \
  --network=none \
  -v "$PWD/workspace:/workspace:rw" \
  --env-file .env \
  my-agent:0.1

You should see your agent's prompt or its first log line. What each flag buys you:

  • --read-only makes the container's own filesystem unwritable, so the agent can't modify its code.
  • --tmpfs /tmp hands it a small scratch area in RAM that disappears on exit, and noexec blocks running binaries from it.
  • --cap-drop=ALL removes every Linux capability (a fine-grained root privilege such as CAP_NET_RAW), so even a compromised process can't sniff traffic.
  • --pids-limit=256 stops fork bombs — scripts that spawn processes until the host dies.
  • --memory and --cpus cap resource use.
  • --network=none cuts the container off from the internet entirely.

Prove the sandbox from inside

Don't take the flags on faith. At the agent's prompt, type id and then touch /test.

id should print uid=1000(agent) gid=1000, and touch /test should fail with Read-only file system. If that write succeeds, your --read-only flag didn't apply and something is wrong with the invocation.

Now test that writes land only where you allowed them: touch /workspace/hello.txt && ls -l /workspace. The file appears inside, and on the host it shows up in ~/agent-sandbox/workspace. That's the bind mount working — everything outside that one link stays invisible to the agent.

While a task runs, watch it from a second terminal with docker logs -f agent, then shut it down. docker rm -f agent clears the rest; combined with --rm and a fresh image per run, nothing the agent did survives.

Give the network and mounts only what's needed

If the agent calls a cloud model, swap --network=none for --network=bridge and re-run; the API call should return a model response instead of timing out. The default bridge gives outbound access without publishing any ports, so nothing reaches in from outside.

If you run a local model instead, keep none and put both containers on a private user-defined network created with docker network create agent-net.

Reference material deserves the same treatment. Mount docs read-only:

-v "$PWD/docs:/workspace/docs:ro"

The agent can cat /workspace/docs/policy.txt, but rm on it fails — and that restriction is enforced by the kernel, not by the agent's good behaviour.

Fixing the three failures that come up most

Permission denied when writing to the mounted folder. Your container UID (1000) doesn't own the host folder. Check the numeric owner with ls -ln ~/agent-sandbox/workspace, align it with sudo chown -R 1000:1000 ~/agent-sandbox/workspace, then restart with --user $(id -u):$(id -g) so the container matches your host user. If files suddenly appear owned by root, you dropped the --user flag — put it back.

Connection refused or getaddrinfo EAI_AGAIN after setting --network=none. That's exactly what none means: no network stack at all. Decide what the agent actually needs. Cloud model? Switch to --network=bridge and keep the key in .env. Local model? Keep none and join both containers to the private agent-net network.

The container exits immediately with exec format error or a missing entrypoint. Your CMD doesn't match the architecture or the installed command. Check with docker run --rm my-agent:0.1 python --version; if that fails, the base image or the pip install step is broken. Also confirm your .py file is copied into /app and that WORKDIR /app appears before CMD.

Pre-flight checklist, and what Docker is not

Before trusting the setup with anything real:

  • [ ] .env is listed in .dockerignore and has mode 600
  • [ ] The container runs as a non-root UID (verified with id)
  • [ ] --read-only is set and touch /test fails
  • [ ] --cap-drop=ALL and no-new-privileges are both present
  • [ ] Exactly one host folder is mounted, and it's the least privileged one possible
  • [ ] Memory, CPU, and PID limits are set
  • [ ] The image is rebuilt from scratch before each production run

One honest caveat: a container is isolation, not a virtual machine. Containers share the host kernel, so a kernel bug can still be an escape route. Treat Docker as strong friction — and for genuinely hostile code, add rootless mode or user namespaces on top.

That's the whole idea: an agent with just enough room to do its job and no room to do anything else. Start with --network=none, mount one folder, run as UID 1000, and only widen the box when a task fails without it. It takes two extra minutes per run and removes the scenario where your coding assistant quietly reads your SSH keys.

This article was originally published on AI Release — https://ai-release.org. More guides like this land in the channel at https://t.me/ai_release1.

來源:DEV Community · dev.to