OpenClaw 支持在 Docker 容器中运行工具,降低 AI 误操作的影响范围。沙箱是可选功能,默认关闭——开启后,exec、read、write 等工具在隔离容器中执行,Gateway 本身仍在宿主机上运行。
沙箱不是完美的安全边界,但能有效限制模型做蠢事时的文件和进程访问范围。
沙箱化的工具
在容器中运行:exec、read、write、edit、apply_patch、process 等文件/执行类工具,以及可选的沙箱浏览器。
不在容器中:Gateway 进程本身;通过 tools.elevated 显式指定在宿主机运行的工具。
三种沙箱模式(mode)
| 模式 | 说明 |
|---|---|
off | 不启用沙箱(默认) |
non-main | 仅非主 Session 使用沙箱(推荐) |
all | 所有 Session 都在容器中运行 |
non-main基于 Session Key(默认main),不是 Agent ID。群组/频道 Session 都是非主 Session,会被沙箱化。
三种容器范围(scope)
| 范围 | 说明 |
|---|---|
session(默认) | 每个 Session 一个独立容器 |
agent | 同一 Agent 的所有 Session 共用一个容器 |
shared | 所有沙箱 Session 共用一个容器 |
工作区访问(workspaceAccess)
| 选项 | 说明 |
|---|---|
none(默认) | 容器内使用独立沙箱工作区(~/.openclaw/sandboxes/) |
ro | 将 Agent 工作区以只读方式挂载到容器的 /agent |
rw | 将 Agent 工作区以读写方式挂载到容器的 /workspace |
最简启用配置
json
{
"agents": {
"defaults": {
"sandbox": {
"mode": "non-main",
"scope": "session",
"workspaceAccess": "none"
}
}
}
}构建沙箱镜像
bash
# 基础镜像(仅核心工具,无 Node)
bash scripts/sandbox-setup.sh
# 功能更完整的镜像(含 curl/jq/nodejs/python3/git)
bash scripts/sandbox-common-setup.sh
# 沙箱浏览器镜像
bash scripts/sandbox-browser-setup.sh使用 common 镜像:
json
{
"agents": {
"defaults": {
"sandbox": {
"docker": {
"image": "openclaw-sandbox-common:bookworm-slim"
}
}
}
}
}默认镜像不含 Node.js。如果 Skill 需要 Node,需自行构建镜像或通过
setupCommand安装(需要网络出口)。
自定义 Bind 挂载
将宿主机目录挂载到容器内:
json
{
"agents": {
"defaults": {
"sandbox": {
"docker": {
"binds": [
"/home/user/source:/source:ro",
"/var/data/myapp:/data:ro"
]
}
}
},
"list": [
{
"id": "build",
"sandbox": {
"docker": {
"binds": ["/mnt/cache:/cache:rw"]
}
}
}
]
}
}全局 binds 和 per-agent binds 会合并(不是替换)。
安全注意:
- 敏感目录(密钥、SSH 等)尽量用
:ro - 禁止挂载
docker.sock、/etc、/proc、/sys、/dev(OpenClaw 自动阻止)
容器初始化命令(setupCommand)
容器创建后只运行一次(不是每次执行都跑):
json
{
"agents": {
"defaults": {
"sandbox": {
"docker": {
"network": "bridge",
"setupCommand": "apt-get update && apt-get install -y ffmpeg"
}
}
}
}
}注意事项:
- 默认网络是
none(无出口),安装包需先设置network: "bridge" readOnlyRoot: true时无法写入,需设为false或用自定义镜像- 需要 root 用户安装软件(省略
user字段或设"0:0")
沙箱浏览器配置
json
{
"agents": {
"defaults": {
"sandbox": {
"browser": {
"autoStart": true,
"network": "openclaw-sandbox-browser",
"allowHostControl": false
}
}
}
}
}autoStart: true:浏览器工具需要时自动启动容器allowHostControl: true:允许沙箱 Session 显式控制宿主机浏览器- 支持 noVNC 观察访问(短效 Token URL,密码在 URL Fragment 中,不写日志)
多 Agent 沙箱独立配置
json
{
"agents": {
"list": [
{
"id": "personal",
"sandbox": { "mode": "off" }
},
{
"id": "family",
"sandbox": { "mode": "all", "scope": "agent" },
"tools": {
"allow": ["read"],
"deny": ["exec", "write", "edit"]
}
}
]
}
}调试沙箱
bash
# 查看当前沙箱配置和工具策略
openclaw sandbox explain工具策略与沙箱的关系
- 工具 allow/deny 策略在沙箱规则之前执行
- 被 deny 的工具,沙箱无法让它重新可用
tools.elevated是显式逃逸机制,让exec在宿主机上运行- 详见:Sandbox vs Tool Policy vs Elevated
原文:Sandboxing - OpenClaw | 来源:OpenClaw 官方文档