本地部署完整指南
🎯 部署前准备
系统要求检查
# 检查系统版本
uname -a
# 检查资源使用情况
free -h
df -h
# 检查端口占用
netstat -tlnp | grep :3000
环境变量配置
# 创建环境配置文件
cat > .env << EOF
# 基础配置
NODE_ENV=production
PORT=3000
# 飞书配置
FEISHU_APP_ID=your_app_id
FEISHU_APP_SECRET=your_app_secret
# 数据库配置
DATABASE_URL=sqlite://./data/openclaw.db
# 日志配置
LOG_LEVEL=info
LOG_FILE=./logs/openclaw.log
# 安全配置
JWT_SECRET=your_jwt_secret_here
ENCRYPTION_KEY=your_encryption_key_here
EOF
🚀 部署方式选择
方式一:Docker 部署(推荐)
1. Docker Compose 配置
# docker-compose.yml
version: '3.8'
services:
openclaw:
image: openclaw/openclaw:latest
container_name: openclaw-bot
restart: unless-stopped
ports:
- "3000:3000"
environment:
- NODE_ENV=production
- FEISHU_APP_ID=${FEISHU_APP_ID}
- FEISHU_APP_SECRET=${FEISHU_APP_SECRET}
- DATABASE_URL=sqlite:///app/data/openclaw.db
volumes:
- ./data:/app/data
- ./logs:/app/logs
- ./config:/app/config
networks:
- openclaw-network
nginx:
image: nginx:alpine
container_name: openclaw-proxy
restart: unless-stopped
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
- ./ssl:/etc/nginx/ssl
depends_on:
- openclaw
networks:
- openclaw-network
networks:
openclaw-network:
driver: bridge
2. 启动部署
# 构建并启动服务
docker-compose up -d
# 查看服务状态
docker-compose ps
# 查看日志
docker-compose logs -f openclaw
方式二:传统部署
1. 项目初始化
# 创建项目目录
mkdir -p /opt/openclaw/{data,logs,config}
cd /opt/openclaw
# 初始化项目
npm init -y
npm install openclaw
# 创建启动脚本
cat > start.sh << 'EOF'
#!/bin/bash
cd /opt/openclaw
source .env
exec node node_modules/.bin/openclaw gateway
EOF
chmod +x start.sh
2. 系统服务配置
# 创建 systemd 服务文件
sudo tee /etc/systemd/system/openclaw.service << EOF
[Unit]
Description=OpenClaw AI Bot Service
After=network.target
[Service]
Type=simple
User=openclaw
WorkingDirectory=/opt/openclaw
EnvironmentFile=/opt/openclaw/.env
ExecStart=/opt/openclaw/start.sh
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
EOF
# 启用并启动服务
sudo systemctl daemon-reload
sudo systemctl enable openclaw
sudo systemctl start openclaw
⚙️ 配置文件详解
主配置文件
# config/production.yaml
server:
port: 3000
host: 0.0.0.0
ssl:
enabled: false # 生产环境建议启用 HTTPS
database:
type: sqlite
url: ./data/openclaw.db
pool:
min: 2
max: 10
cache:
type: redis
host: localhost
port: 6379
ttl: 3600
logging:
level: info
format: json
transports:
- type: file
filename: ./logs/app.log
maxsize: 100mb
maxfiles: 5
- type: console
level: error
plugins:
autoUpdate: false
registry: https://registry.npmjs.org
飞书通道配置
# config/channels/feishu.yaml
feishu:
enabled: true
appId: ${FEISHU_APP_ID}
appSecret: ${FEISHU_APP_SECRET}
domain: "feishu"
connectionMode: "websocket"
# 消息策略
dmPolicy: "pairing"
groupPolicy: "allowlist"
requireMention: true
# 性能配置
rateLimit:
requestsPerSecond: 10
burst: 20
timeout: 30000
# 白名单配置
allowlist:
users:
- "user_id_1"
- "user_id_2"
groups:
- "group_id_1"
- "group_id_2"
🔧 反向代理配置
Nginx 配置
# nginx.conf
events {
worker_connections 1024;
}
http {
upstream openclaw_backend {
server localhost:3000;
}
server {
listen 80;
server_name your-domain.com;
# 重定向到 HTTPS
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
server_name your-domain.com;
# SSL 配置
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;
# 安全头
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
location / {
proxy_pass http://openclaw_backend;
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;
proxy_read_timeout 300s;
proxy_connect_timeout 75s;
}
# 健康检查端点
location /health {
proxy_pass http://openclaw_backend/health;
}
}
}
Apache 配置
<VirtualHost *:80>
ServerName your-domain.com
Redirect permanent / https://your-domain.com/
</VirtualHost>
<VirtualHost *:443>
ServerName your-domain.com
SSLEngine on
SSLCertificateFile /path/to/cert.pem
SSLCertificateKeyFile /path/to/key.pem
ProxyPreserveHost On
ProxyPass / http://localhost:3000/
ProxyPassReverse / http://localhost:3000/
# 安全头
Header always set X-Frame-Options DENY
Header always set X-Content-Type-Options nosniff
</VirtualHost>
📊 监控告警配置
健康检查端点
// health-check.js
const express = require('express');
const app = express();
app.get('/health', async (req, res) => {
try {
// 检查各项服务状态
const checks = {
database: await checkDatabase(),
feishu: await checkFeishuConnection(),
disk: checkDiskSpace(),
memory: checkMemoryUsage()
};
const isHealthy = Object.values(checks).every(check => check.status === 'ok');
res.status(isHealthy ? 200 : 503).json({
status: isHealthy ? 'healthy' : 'unhealthy',
timestamp: new Date().toISOString(),
checks
});
} catch (error) {
res.status(500).json({
status: 'error',
error: error.message
});
}
});
Prometheus 监控配置
# prometheus.yml
global:
scrape_interval: 15s
scrape_configs:
- job_name: 'openclaw'
static_configs:
- targets: ['localhost:3000']
metrics_path: '/metrics'
Grafana 仪表板配置
{
"dashboard": {
"title": "OpenClaw 监控面板",
"panels": [
{
"title": "消息处理速率",
"type": "graph",
"targets": [
"rate(openclaw_messages_processed_total[5m])"
]
},
{
"title": "错误率",
"type": "gauge",
"targets": [
"rate(openclaw_errors_total[5m]) / rate(openclaw_requests_total[5m])"
]
}
]
}
}
🛡️ 安全加固
防火墙配置
# UFW 防火墙配置
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow ssh
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
# 只允许特定 IP 访问管理接口
sudo ufw allow from 192.168.1.0/24 to any port 3000
应用安全配置
# security.yaml
security:
rateLimiting:
global:
maxRequests: 1000
windowMs: 900000 # 15分钟
perIp:
maxRequests: 100
windowMs: 900000
cors:
origin: ["https://your-domain.com"]
credentials: true
helmet:
contentSecurityPolicy: true
xssFilter: true
noSniff: true
frameguard: { action: "deny" }
authentication:
jwt:
secret: ${JWT_SECRET}
expiresIn: "24h"
备份策略
#!/bin/bash
# backup.sh
BACKUP_DIR="/backup/openclaw"
DATE=$(date +%Y%m%d_%H%M%S)
# 创建备份目录
mkdir -p $BACKUP_DIR/$DATE
# 备份数据库
sqlite3 /opt/openclaw/data/openclaw.db ".backup $BACKUP_DIR/$DATE/database.db"
# 备份配置文件
cp -r /opt/openclaw/config $BACKUP_DIR/$DATE/
# 备份日志(最近7天)
find /opt/openclaw/logs -name "*.log" -mtime -7 -exec cp {} $BACKUP_DIR/$DATE/logs/ \;
# 压缩备份
tar -czf $BACKUP_DIR/openclaw_backup_$DATE.tar.gz -C $BACKUP_DIR $DATE
# 删除旧备份(保留30天)
find $BACKUP_DIR -name "openclaw_backup_*.tar.gz" -mtime +30 -delete
# 验证备份完整性
if tar -tzf $BACKUP_DIR/openclaw_backup_$DATE.tar.gz > /dev/null 2>&1; then
echo "Backup completed successfully: $BACKUP_DIR/openclaw_backup_$DATE.tar.gz"
else
echo "Backup verification failed!"
exit 1
fi
🚨 故障排除
常见问题诊断
1. 服务启动失败
# 检查端口占用
lsof -i :3000
# 查看详细错误日志
journalctl -u openclaw -f
# 检查环境变量
printenv | grep FEISHU
2. 飞书连接问题
# 测试网络连通性
curl -v https://open.feishu.cn
# 验证 App 凭证
openclaw config:validate
# 检查权限配置
openclaw gateway:permissions
3. 性能问题排查
# 系统资源监控
htop
iotop
iftop
# Node.js 性能分析
node --inspect-brk app.js
# 数据库查询分析
sqlite3 data/openclaw.db "EXPLAIN QUERY PLAN SELECT * FROM messages LIMIT 10;"
日志分析脚本
#!/bin/bash
# log-analyzer.sh
LOG_FILE="/opt/openclaw/logs/app.log"
# 错误统计
echo "=== 错误统计 ==="
grep -i "error\|fail" $LOG_FILE | wc -l
# 按小时统计请求数
echo "=== 每小时请求数 ==="
awk '{print $2}' $LOG_FILE | cut -d: -f1 | sort | uniq -c
# 响应时间分析
echo "=== 响应时间分析 ==="
grep "duration" $LOG_FILE | awk '{print $NF}' | \
awk '{sum+=$1; count++; if($1>max) max=$1} END {print "Average:", sum/count, "Max:", max}'
📈 性能优化
数据库优化
-- 创建索引
CREATE INDEX idx_messages_timestamp ON messages(created_at);
CREATE INDEX idx_messages_user_id ON messages(user_id);
-- 定期清理旧数据
DELETE FROM messages WHERE created_at < datetime('now', '-30 days');
VACUUM;
缓存策略
# redis-config.yaml
redis:
host: localhost
port: 6379
password: ${REDIS_PASSWORD}
caches:
- name: "user_sessions"
ttl: 3600
- name: "api_responses"
ttl: 1800
- name: "feishu_tokens"
ttl: 7200
负载均衡配置
# haproxy.cfg
frontend openclaw_frontend
bind *:80
mode http
default_backend openclaw_backend
backend openclaw_backend
mode http
balance roundrobin
server openclaw1 192.168.1.10:3000 check
server openclaw2 192.168.1.11:3000 check
server openclaw3 192.168.1.12:3000 check
✅ 部署检查清单
部署完成后请逐一检查:
基础配置
- 环境变量配置正确
- 配置文件语法正确
- 数据库连接正常
- 日志目录权限正确
服务运行
- 服务正常启动
- 端口监听正常
- 健康检查通过
- 飞书连接建立
安全配置
- 防火墙规则设置
- SSL 证书配置
- 访问控制生效
- 备份策略执行
监控告警
- 日志收集正常
- 性能监控启用
- 告警规则配置
- 通知渠道测试
📚 后续维护
日常维护脚本
#!/bin/bash
# maintenance.sh
# 日志轮转
logrotate /etc/logrotate.d/openclaw
# 数据库维护
sqlite3 /opt/openclaw/data/openclaw.db "VACUUM;"
sqlite3 /opt/openclaw/data/openclaw.db "ANALYZE;"
# 清理临时文件
find /tmp -name "openclaw*" -mtime +1 -delete
# 系统更新检查
apt update && apt list --upgradable | grep openclaw
升级流程
# 1. 备份当前版本
sudo systemctl stop openclaw
./backup.sh
# 2. 更新应用
npm update openclaw
# 3. 验证配置
openclaw config:validate
# 4. 启动服务
sudo systemctl start openclaw
# 5. 监控运行状态
watch -n 5 'systemctl status openclaw'
部署只是开始,持续的监控和维护同样重要