跳到主要内容

最佳实践

本章汇总 OpenClaw 在生产环境中的最佳实践,涵盖安全配置、性能优化、故障排查等方面。

安全配置

API Key 管理

不要硬编码 API Key

// ❌ 错误做法
const config = {
model: {
api_key: "sk-xxxxx"
}
};

// ✅ 正确做法:使用环境变量
const config = {
model: {
api_key: process.env.MODEL_API_KEY
}
};

使用环境变量

# 设置环境变量
export MODEL_API_KEY="sk-xxxxx"

# 或在 .env 文件中
MODEL_API_KEY=sk-xxxxx

配置文件权限

# 设置配置文件权限
chmod 600 ~/.openclaw/config.json

# 确保只有所有者可读写
ls -la ~/.openclaw/config.json
# -rw------- 1 user user 1024 Mar 26 10:00 config.json

访问控制

Gateway Token

{
"gateway": {
"token": "your-secure-token-here",
"tokenExpiry": 86400000
}
}

生成安全 Token:

# 生成随机 Token
openssl rand -hex 32

渠道白名单

{
"channels": {
"telegram": {
"allowedUsers": ["USER_ID_1", "USER_ID_2"],
"allowedChats": ["CHAT_ID_1", "CHAT_ID_2"]
}
}
}

速率限制

{
"gateway": {
"rateLimit": {
"enabled": true,
"maxRequests": 100,
"windowMs": 60000,
"skipFailedRequests": false
}
}
}

权限隔离

最小权限原则

{
"permissions": {
"filesystem": {
"enabled": true,
"allowedPaths": ["/home/user/documents"],
"deniedPaths": ["/etc", "/root", "/.ssh"],
"readOnly": false
},
"execute": {
"enabled": true,
"allowedCommands": ["git", "npm", "node", "python3"],
"deniedCommands": ["rm -rf", "sudo", "chmod 777"],
"requireConfirmation": ["rm", "mv"]
},
"network": {
"enabled": true,
"allowedDomains": ["api.example.com", "github.com"],
"deniedDomains": [],
"blockPrivateIPs": true
}
}
}

敏感操作确认

{
"security": {
"confirmBeforeAction": true,
"sensitiveActions": [
"file_delete",
"execute_command",
"send_email",
"network_post"
]
}
}

网络安全

HTTPS 配置

{
"gateway": {
"https": {
"enabled": true,
"cert": "/path/to/cert.pem",
"key": "/path/to/key.pem"
}
}
}

CORS 配置

{
"gateway": {
"cors": {
"enabled": true,
"origins": ["https://your-domain.com"],
"methods": ["GET", "POST"],
"credentials": true
}
}
}

反向代理配置

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;
}
}

性能优化

模型选择

根据任务选择模型

任务类型推荐模型原因
复杂推理Claude Opus / GPT-4推理能力强
日常对话Claude Sonnet / GPT-3.5性价比高
代码开发DeepSeek Coder代码能力强
成本敏感本地模型无 API 费用

模型配置

{
"models": {
"primary": {
"provider": "claude",
"model": "claude-3-sonnet",
"maxTokens": 4096,
"temperature": 0.7
},
"fallback": {
"provider": "deepseek",
"model": "deepseek-chat",
"enabled": true
}
}
}

记忆优化

记忆压缩

{
"memory": {
"compressionThreshold": 8192,
"autoCompress": true,
"compressAfter": 7
}
}

记忆分层

# MEMORY.md 结构建议

## 核心信息(每次加载)
- 用户基本信息
- 关键偏好
- 重要规则

## 次要信息(按需加载)
- 历史记录摘要
- 临时配置

## 归档信息(不加载)
- 已完成的任务
- 过时的信息

并发控制

{
"concurrency": {
"maxConcurrentTasks": 5,
"maxConcurrentAgents": 3,
"queueSize": 100,
"timeout": 300000
}
}

缓存配置

{
"cache": {
"enabled": true,
"ttl": 3600,
"maxSize": "100MB",
"strategies": {
"model": "memory",
"skill": "disk",
"memory": "disk"
}
}
}

日志与监控

日志配置

{
"logging": {
"level": "info",
"format": "json",
"outputs": ["console", "file"],
"file": {
"path": "/var/log/openclaw/app.log",
"maxSize": "100MB",
"maxFiles": 10,
"compress": true
}
}
}

日志级别

级别说明使用场景
error错误信息生产环境
warn警告信息生产环境
info一般信息生产环境
debug调试信息开发环境
trace详细追踪问题排查

健康检查

# 检查服务状态
openclaw gateway status

# 检查模型连接
openclaw diagnose model

# 检查网络
openclaw diagnose network

# 完整诊断
openclaw diagnose --all

Prometheus 指标

{
"metrics": {
"enabled": true,
"port": 9090,
"path": "/metrics"
}
}

可用指标:

  • openclaw_requests_total:总请求数
  • openclaw_request_duration_seconds:请求耗时
  • openclaw_model_tokens_total:Token 使用量
  • openclaw_agent_active_count:活跃 Agent 数
  • openclaw_error_total:错误总数

备份与恢复

自动备份

# 创建备份
openclaw backup create --output backup-$(date +%Y%m%d).tar.gz

# 定时备份(Cron)
# 每天凌晨 3 点备份
0 3 * * * openclaw backup create --output /backup/openclaw-$(date +\%Y\%m\%d).tar.gz

备份内容

backup.tar.gz
├── config.json # 配置文件
├── memory/ # 记忆文件
│ ├── MEMORY.md
│ ├── SOUL.md
│ └── HEARTBEAT.md
├── skills/ # 自定义技能
└── workspaces/ # Agent 工作空间

恢复操作

# 从备份恢复
openclaw backup restore backup-20260326.tar.gz

# 恢复后重启服务
openclaw gateway restart

故障排查

常见问题诊断流程

问题发生

检查服务状态

查看日志

分析错误信息

定位问题原因

应用解决方案

验证修复结果

服务无法启动

# 1. 检查端口占用
lsof -i :18789

# 2. 检查配置文件
openclaw config validate

# 3. 检查日志
openclaw logs --tail 100

# 4. 尝试重置配置
openclaw config reset

模型调用失败

# 1. 检查 API Key
openclaw config show model.api_key

# 2. 测试模型连接
openclaw diagnose model

# 3. 检查网络
curl -I https://api.anthropic.com

# 4. 查看错误日志
openclaw logs --level error --grep "model"

记忆不生效

# 1. 验证记忆文件
openclaw memory validate

# 2. 检查文件路径
openclaw config show memory.path

# 3. 查看记忆内容
openclaw memory show

# 4. 重新加载
openclaw memory reload

性能问题

# 1. 检查资源使用
top -p $(pgrep -f openclaw)

# 2. 检查并发数
openclaw status --concurrency

# 3. 检查缓存命中率
openclaw cache stats

# 4. 分析慢请求
openclaw logs --grep "slow"

生产环境部署

系统要求

项目最低要求推荐配置
CPU2 核4 核以上
内存4 GB8 GB 以上
存储20 GB SSD50 GB SSD
网络10 Mbps100 Mbps

Docker 生产配置

version: '3.8'

services:
openclaw:
image: openclaw/openclaw:stable
container_name: openclaw
restart: always
ports:
- "18789:18789"
- "9090:9090"
volumes:
- ./data:/root/.openclaw
- ./logs:/var/log/openclaw
environment:
- TZ=Asia/Shanghai
- OPENCLAW_LOG_LEVEL=info
- MODEL_API_KEY=${MODEL_API_KEY}
deploy:
resources:
limits:
cpus: '2'
memory: 4G
reservations:
cpus: '1'
memory: 2G
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:18789/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
logging:
driver: "json-file"
options:
max-size: "100m"
max-file: "10"

高可用配置

                    ┌─────────────┐
│ Nginx │
│ 负载均衡 │
└──────┬──────┘

┌───────────────┼───────────────┐
│ │ │
▼ ▼ ▼
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ OpenClaw │ │ OpenClaw │ │ OpenClaw │
│ Instance 1 │ │ Instance 2 │ │ Instance 3 │
└─────────────┘ └─────────────┘ └─────────────┘
│ │ │
└───────────────┼───────────────┘

┌──────┴──────┐
│ Redis │
│ 共享状态 │
└─────────────┘

监控告警

{
"alerting": {
"enabled": true,
"rules": [
{
"name": "high_error_rate",
"condition": "error_rate > 0.05",
"duration": "5m",
"channels": ["telegram", "email"]
},
{
"name": "service_down",
"condition": "health_check_failed",
"duration": "1m",
"channels": ["telegram"]
},
{
"name": "high_latency",
"condition": "p99_latency > 5000",
"duration": "5m",
"channels": ["telegram"]
}
]
}
}

成本优化

Token 使用优化

{
"model": {
"maxTokens": 2048,
"temperature": 0.7,
"stream": true
},
"memory": {
"maxContextLength": 4000,
"summarizeThreshold": 2000
}
}

模型降级策略

{
"modelFallback": {
"enabled": true,
"rules": [
{
"condition": "tokens > 8000",
"fallback": "gpt-3.5-turbo"
},
{
"condition": "simple_task",
"fallback": "deepseek-chat"
}
]
}
}

本地模型

{
"models": {
"local": {
"provider": "ollama",
"model": "llama3",
"baseUrl": "http://localhost:11434"
}
}
}

最佳实践清单

安全检查清单

  • API Key 使用环境变量存储
  • 配置文件权限设置为 600
  • 启用 Gateway Token 认证
  • 配置渠道白名单
  • 启用速率限制
  • 配置 HTTPS
  • 设置敏感操作确认
  • 定期更新依赖

性能检查清单

  • 根据任务选择合适的模型
  • 启用记忆压缩
  • 配置合理的并发限制
  • 启用缓存
  • 配置日志轮转
  • 设置合理的超时时间

运维检查清单

  • 配置自动备份
  • 启用健康检查
  • 配置监控指标
  • 设置告警规则
  • 准备故障恢复方案
  • 定期检查日志
  • 保持版本更新

参考资源