最佳实践
本章汇总 OpenClaw 在生产环境中的最佳实践,涵盖安全配置、性能优化、故障排查等方面。
安全配置
API Key 管理
OpenClaw 支持多种方式管理 API Key,推荐使用环境变量或认证配置文件。
使用环境变量
# 设置环境变量
export ANTHROPIC_API_KEY="sk-xxxxx"
export OPENAI_API_KEY="sk-xxxxx"
# 或在 .env 文件中
ANTHROPIC_API_KEY=sk-xxxxx
OPENAI_API_KEY=sk-xxxxx
使用认证配置文件
OpenClaw 将敏感凭证存储在单独的 auth-profiles.json 文件中:
# 查看认证配置位置
~/.openclaw/auth-profiles.json
在配置中引用环境变量
{
"agents": {
"defaults": {
"model": {
"primary": "anthropic/claude-sonnet-4-6",
"apiKey": "${ANTHROPIC_API_KEY}"
}
}
}
}
环境变量替换规则:
- 格式:
${VAR_NAME}(只匹配大写名称) - 变量不存在时会报错
- 转义:
$${VAR}输出字面量${VAR}
访问控制
Gateway Token
为 Gateway 设置访问令牌,防止未授权访问:
{
"gateway": {
"auth": {
"mode": "token",
"token": "your-secure-token-here"
}
}
}
生成安全 Token:
# 生成随机 Token
openssl rand -hex 32
渠道白名单
限制谁可以通过特定渠道与 Agent 交互:
{
"channels": {
"whatsapp": {
"dmPolicy": "allowlist",
"allowFrom": ["+15555550123", "+15555550124"],
"groupPolicy": "allowlist",
"groupAllowFrom": ["+15555550123"]
},
"telegram": {
"allowFrom": ["123456789"],
"groups": {
"*": { "requireMention": true }
}
}
}
}
DM 访问策略
| 策略 | 行为 |
|---|---|
pairing(默认) | 未知发送者获得一次性配对码,需要所有者批准 |
allowlist | 只允许 allowFrom 列表中的发送者 |
open | 允许所有入站私聊(需要 allowFrom: ["*"]) |
disabled | 忽略所有入站私聊 |
工具权限控制
工具过滤
限制 Agent 可以使用的工具:
{
"tools": {
"allow": ["read", "write", "glob", "grep"],
"deny": ["browser", "exec"]
}
}
提升权限控制
为特定用户启用提升权限:
{
"tools": {
"elevated": {
"enabled": true,
"allowFrom": {
"whatsapp": ["+15555550123"],
"telegram": ["123456789"],
"discord": ["123456789012345678"]
}
}
}
}
沙箱隔离
为不信任的输入启用沙箱:
{
"agents": {
"defaults": {
"sandbox": {
"mode": "non-main",
"scope": "session",
"docker": {
"image": "openclaw-sandbox:bookworm-slim",
"network": "none",
"readOnlyRoot": true
}
}
}
}
}
沙箱模式说明:
| 模式 | 说明 |
|---|---|
off | 禁用沙箱 |
non-main | 非 main 会话在沙箱中运行 |
all | 所有会话都在沙箱中运行 |
多用户 DM 隔离
如果多个用户可以私聊你的 Bot,启用安全 DM 模式:
{
"session": {
"dmScope": "per-channel-peer"
},
"channels": {
"whatsapp": {
"dmPolicy": "allowlist",
"allowFrom": ["+15555550123", "+15555550124"]
}
}
}
这确保不同发送者的 DM 不会共享同一个上下文。
性能优化
模型选择
根据任务选择模型
| 任务类型 | 推荐模型 | 原因 |
|---|---|---|
| 复杂推理 | Claude Opus 4.6 | 推理能力强 |
| 日常对话 | Claude Sonnet 4.6 | 性价比高 |
| 代码开发 | Claude Sonnet 4.6 | 代码能力强 |
| 成本敏感 | 本地模型 (Ollama) | 无 API 费用 |
模型选择原则:
- 将 primary 设置为可用的最强最新一代模型
- 使用 fallbacks 处理成本/延迟敏感的任务
- 对于工具调用或不可信输入,避免使用较旧/较弱的模型
模型配置
{
"agents": {
"defaults": {
"model": {
"primary": "anthropic/claude-sonnet-4-6",
"fallbacks": ["anthropic/claude-opus-4-6", "openai/gpt-5.2"]
}
}
}
}
会话管理
会话作用域
根据使用场景配置会话作用域:
{
"session": {
"scope": "per-sender",
"dmScope": "per-channel-peer",
"reset": {
"mode": "daily",
"atHour": 4,
"idleMinutes": 60
},
"resetTriggers": ["/new", "/reset"]
}
}
作用域说明:
| 作用域 | 说明 |
|---|---|
per-sender | 每个发送者独立会话 |
per-channel-peer | 每个渠道-发送者对独立会话(推荐多用户 DM) |
会话维护
{
"session": {
"maintenance": {
"mode": "warn",
"pruneAfter": "30d",
"maxEntries": 500,
"rotateBytes": "10mb"
}
}
}
并发控制
{
"agents": {
"defaults": {
"maxConcurrent": 3,
"timeoutSeconds": 600
}
}
}
消息队列
配置消息队列处理策略:
{
"routing": {
"queue": {
"mode": "collect",
"debounceMs": 1000,
"cap": 20,
"drop": "summarize"
}
}
}
队列模式说明:
| 模式 | 说明 |
|---|---|
collect | 收集排队消息,当前回合结束后处理 |
steer | 将排队消息注入到当前运行中 |
followup | 类似 collect,但开始新的 Agent 回合 |
心跳配置
心跳用于保持 Agent 活跃和执行定期任务:
{
"agents": {
"defaults": {
"heartbeat": {
"every": "30m",
"prompt": "HEARTBEAT",
"suppressToolErrorWarnings": true,
"isolatedSession": true,
"lightContext": true
}
}
}
}
注意:心跳会运行完整的 Agent 回合,较短的间隔会消耗更多 Token。
日志与监控
日志配置
{
"logging": {
"level": "info",
"file": "/tmp/openclaw/openclaw.log",
"consoleLevel": "info",
"consoleStyle": "pretty",
"redactSensitive": "tools"
}
}
日志级别说明:
| 级别 | 说明 | 使用场景 |
|---|---|---|
error | 错误信息 | 生产环境 |
warn | 警告信息 | 生产环境 |
info | 一般信息 | 生产环境 |
debug | 调试信息 | 开发环境 |
健康检查
# 检查服务状态
openclaw gateway status
# 深度状态检查
openclaw status --deep
# 检查模型连接
openclaw models status
# 完整诊断
openclaw doctor
# 自动修复问题
openclaw doctor --fix
模型状态监控
# 查看模型状态(包含 OAuth 过期警告)
openclaw models status
# 自动化检查(缺失/过期返回退出码 1,即将过期返回 2)
openclaw models status --check
查看日志
# 查看日志
openclaw logs
# 实时跟踪日志
openclaw logs --follow
# 过滤日志
openclaw logs --grep "error"
openclaw logs --level debug
备份与恢复
手动备份
# 备份 OpenClaw 数据目录
tar -czvf openclaw-backup-$(date +%Y%m%d).tar.gz ~/.openclaw
# 备份关键文件
cp -r ~/.openclaw/workspace ~/backup/workspace
cp ~/.openclaw/openclaw.json ~/backup/
cp ~/.openclaw/auth-profiles.json ~/backup/ # 如果存在
定时备份(Cron)
# 添加到 crontab
# 每天凌晨 3 点备份
0 3 * * * tar -czvf /backup/openclaw-$(date +\%Y\%m\%d).tar.gz -C $HOME .openclaw
备份内容
OpenClaw 的关键数据位置:
| 目录/文件 | 说明 |
|---|---|
~/.openclaw/openclaw.json | 主配置文件 |
~/.openclaw/auth-profiles.json | 认证配置 |
~/.openclaw/workspace/ | 工作空间(含记忆文件) |
~/.openclaw/skills/ | 托管技能 |
~/.openclaw/agents/ | Agent 状态和会话 |
恢复操作
# 从备份恢复
tar -xzvf openclaw-backup-20260403.tar.gz -C ~/
# 恢复后重启服务
openclaw gateway restart
故障排查
诊断工具
OpenClaw 提供多个诊断命令:
# 运行诊断
openclaw doctor
# 自动修复问题
openclaw doctor --fix
# 深度诊断
openclaw doctor --deep
# 查看状态
openclaw status --deep
# 查看日志
openclaw logs --follow
服务无法启动
# 1. 检查端口占用
lsof -i :18789
# 2. 检查配置文件格式
openclaw config validate
# 3. 查看日志
openclaw logs --tail 100
# 4. 运行诊断
openclaw doctor --fix
模型调用失败
# 1. 检查模型状态
openclaw models status
# 2. 测试 API Key
openclaw models status --probe
# 3. 检查网络连接
curl -I https://api.anthropic.com
# 4. 查看错误日志
openclaw logs --level error
记忆不生效
# 1. 检查记忆索引状态
openclaw memory status
# 2. 重新索引
openclaw memory index --force
# 3. 检查工作空间配置
openclaw config get agents.defaults.workspace
# 4. 检查嵌入向量提供商
openclaw models status
渠道连接问题
# 1. 检查渠道状态
openclaw channels status
# 2. 深度检查(包括连接探测)
openclaw channels status --probe
# 3. 查看渠道日志
openclaw channels logs --channel telegram
# 4. 重新登录渠道
openclaw channels login --channel whatsapp
配置验证失败
当配置验证失败时,只有诊断命令可用:
# 验证配置
openclaw config validate
# 自动修复
openclaw doctor --fix
# 查看配置 schema
openclaw config schema
生产环境部署
系统要求
| 项目 | 最低要求 | 推荐配置 |
|---|---|---|
| Node.js | 22.14+ LTS | 24.x |
| 内存 | 4 GB | 8 GB 以上 |
| 存储 | 20 GB SSD | 50 GB SSD |
| 网络 | 10 Mbps | 100 Mbps |
Docker 部署
创建 docker-compose.yml:
version: '3.8'
services:
openclaw:
image: openclaw/openclaw:latest
container_name: openclaw
restart: unless-stopped
ports:
- "18789:18789"
volumes:
- ./data:/root/.openclaw
environment:
- TZ=Asia/Shanghai
- ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
command: openclaw gateway
启动服务:
docker-compose up -d
docker-compose logs -f openclaw
配置热加载
Gateway 支持配置热加载,大多数配置更改无需重启:
{
"gateway": {
"reload": {
"mode": "hybrid",
"debounceMs": 300
}
}
}
热加载模式说明:
| 模式 | 行为 |
|---|---|
hybrid(默认) | 安全更改即时热加载,关键更改自动重启 |
hot | 只热加载安全更改,需要重启时输出警告 |
restart | 任何更改都重启 Gateway |
off | 禁用文件监控,更改需手动重启 |
远程访问
Tailscale 集成
{
"gateway": {
"tailscale": {
"mode": "serve"
}
}
}
启动命令:
# 在 Tailscale 网络中提供服务
openclaw gateway --tailscale serve
# 通过 Tailscale Funnel 暴露到公网
openclaw gateway --tailscale funnel
SSH 端口转发
# 在本地电脑执行
ssh -N -L 18789:127.0.0.1:18789 user@server-ip
# 然后访问 http://127.0.0.1:18789
反向代理配置
Nginx 配置示例:
server {
listen 443 ssl http2;
server_name openclaw.your-domain.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
location / {
proxy_pass http://127.0.0.1:18789;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
成本优化
Token 使用优化
合理配置上下文和行为参数:
{
"agents": {
"defaults": {
"timeoutSeconds": 300,
"mediaMaxMb": 5,
"thinkingDefault": "low",
"verboseDefault": "off"
}
}
}
思考模式说明:
| 模式 | Token 消耗 | 适用场景 |
|---|---|---|
high | 高 | 复杂推理任务 |
medium | 中 | 一般任务 |
low | 低 | 简单任务(默认) |
off | 无 | 最小化成本 |
模型回退策略
使用 fallbacks 在主模型不可用或成本过高时自动切换:
{
"agents": {
"defaults": {
"model": {
"primary": "anthropic/claude-sonnet-4-6",
"fallbacks": ["openai/gpt-4o-mini", "deepseek/deepseek-chat"]
}
}
}
}
本地模型
使用 Ollama 运行本地模型,完全免费:
# 安装 Ollama
curl -fsSL https://ollama.com/install.sh | sh
# 拉取模型
ollama pull llama3
# 配置 OpenClaw
{
"agent": {
"workspace": "~/.openclaw/workspace",
"model": {
"primary": "ollama/llama3"
}
},
"models": {
"providers": {
"ollama": {
"baseUrl": "http://127.0.0.1:11434/api",
"api": "ollama"
}
}
}
}
会话重置
配置自动重置避免上下文过长:
{
"session": {
"reset": {
"mode": "daily",
"atHour": 4
},
"resetTriggers": ["/new", "/reset"]
}
}
上下文压缩
当对话历史过长时自动压缩:
{
"agents": {
"defaults": {
"compaction": {
"mode": "default",
"memoryFlush": true
}
}
}
}
压缩模式说明:
| 模式 | 说明 |
|---|---|
default | 标准压缩 |
safeguard | 分块摘要,适用于长历史 |
最佳实践清单
安全检查清单
- API Key 使用环境变量存储
- 配置 Gateway Token 认证
- 配置渠道白名单(
allowFrom) - 群聊设置提及要求(
requireMention) - 多用户 DM 启用
dmScope: "per-channel-peer" - 不可信输入启用沙箱
- 定期检查 OAuth 过期状态
性能检查清单
- 根据任务选择合适的模型
- 配置合理的超时时间
- 配置消息队列策略
- 配置会话自动重置
- 设置合理的并发限制
运维检查清单
- 配置日志记录
- 定期备份数据目录
- 熟悉诊断命令
- 准备故障恢复方案
- 保持版本更新