OpenClaw 高級配置指南:Nginx 反向代理、性能優化與最佳實踐
當您熟悉了 OpenClaw 的基礎操作並在 VPS 上成功通過 Docker 部署後,本教程將帶您深入探索高級功能與優化技巧,從而發揮出 OpenClaw 的最大潛能,構建企業級的 AI 智能體平臺。
目錄
1. 使用 Nginx / 1Panel 綁定獨立域名
為了方便訪問、提升安全性並支持 API 調用,我們強烈建議為您的 OpenClaw 綁定一個獨立的域名,並開啟 HTTPS 加密。
為什麼需要域名和 HTTPS?
- 🔒 安全性:HTTPS 加密傳輸,防止數據被竊聽或篡改
- 🌐 易用性:域名比 IP 地址更容易記憶和分享
- 📱 移動端支持:某些移動應用要求 HTTPS 連接
- 🔑 API 集成:第三方服務通常要求 HTTPS 端點
- 📊 SEO 優化:搜索引擎優先索引 HTTPS 網站
- ✅ 瀏覽器信任:避免瀏覽器的"不安全"警告
方法一:直接使用 Nginx 配置反向代理
如果您熟悉 Nginx 原生配置,這是最靈活的方式。
1.1 安裝 Nginx
# Ubuntu/Debian
sudo apt update
sudo apt install nginx -y
# 啟動 Nginx
sudo systemctl start nginx
sudo systemctl enable nginx
# 驗證安裝
nginx -v
# 期望輸出:nginx version: nginx/1.x.x1.2 創建 Nginx 配置文件
在 /etc/nginx/sites-available 目錄中新建配置文件:
sudo nano /etc/nginx/sites-available/openclaw添加以下配置內容:
# HTTP 服務器塊(用於重定向到 HTTPS)
server {
listen 80;
listen [::]:80;
server_name claw.yourdomain.com; # 替換為您的域名
# Let's Encrypt 驗證路徑
location /.well-known/acme-challenge/ {
root /var/www/certbot;
}
# 其他所有請求重定向到 HTTPS
location / {
return 301 https://$server_name$request_uri;
}
}
# HTTPS 服務器塊
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name claw.yourdomain.com; # 替換為您的域名
# SSL 證書路徑(稍後由 certbot 自動配置)
ssl_certificate /etc/letsencrypt/live/claw.yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/claw.yourdomain.com/privkey.pem;
# SSL 優化配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_session_tickets off;
# 安全頭
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# 客戶端請求大小限制(根據需求調整)
client_max_body_size 50M;
# 反向代理配置
location / {
proxy_pass http://127.0.0.1:8080; # 轉發到本地 Docker 映射端口
proxy_http_version 1.1;
# WebSocket 支持(如果需要)
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;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Port $server_port;
# 超時設置
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 緩衝設置
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
proxy_busy_buffers_size 8k;
}
# 靜態文件緩存優化
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
proxy_pass http://127.0.0.1:8080;
expires 30d;
add_header Cache-Control "public, immutable";
access_log off;
}
# 健康檢查端點(可選)
location /health {
proxy_pass http://127.0.0.1:8080/health;
access_log off;
}
}1.3 啟用配置
# 創建符號鏈接到 sites-enabled
sudo ln -s /etc/nginx/sites-available/openclaw /etc/nginx/sites-enabled/
# 測試配置文件語法
sudo nginx -t
# 如果測試通過,重新加載 Nginx
sudo systemctl reload nginx1.4 申請並配置 SSL 證書
使用 Certbot 自動申請 Let's Encrypt 免費證書:
# 安裝 Certbot 和 Nginx 插件
sudo apt install certbot python3-certbot-nginx -y
# 創建 certbot 驗證目錄
sudo mkdir -p /var/www/certbot
# 申請證書(交互式)
sudo certbot --nginx -d claw.yourdomain.com
# 或者非交互式(適合腳本)
sudo certbot --nginx -d claw.yourdomain.com --non-interactive --agree-tos --email your-email@example.comCertbot 會自動:
- 驗證域名所有權
- 申請 SSL 證書
- 修改 Nginx 配置以使用證書
- 設置自動續期
1.5 驗證 HTTPS 配置
# 測試 SSL 配置
sudo nginx -t
# 重新加載 Nginx
sudo systemctl reload nginx
# 訪問 https://claw.yourdomain.com 驗證
# 使用在線工具測試 SSL 等級
# https://www.ssllabs.com/ssltest/1.6 設置證書自動續期
Let's Encrypt 證書有效期為 90 天,Certbot 會自動設置續期任務:
# 查看定時任務
sudo crontab -l
# 應該看到類似內容:
# 0 */12 * * * certbot renew --quiet
# 手動測試續期(不會實際續期,僅模擬)
sudo certbot renew --dry-run
# 查看續期日誌
sudo cat /var/log/letsencrypt/letsencrypt.log方法二:使用 1Panel 等可視化面板管理
對於不熟悉命令行操作的用戶,我們強烈推薦新手使用 1Panel 控制面板來管理,它提供了圖形化界面,讓配置變得簡單直觀。
2.1 安裝 1Panel(如果尚未安裝)
# 一鍵安裝 1Panel
curl -sSL https://resource.fit2cloud.com/1panel/package/quick_start.sh -o quick_start.sh && sudo bash quick_start.sh💡 提示:如果您還未安裝 1Panel,請參考我們全站的「1Panel 面板安裝指南」。
2.2 配置反向代理
登錄 1Panel 控制面板
- 訪問
https://your-server-ip:port - 使用管理員賬戶登錄
- 訪問
創建網站
- 在左側菜單找到 「網站」 → 「創建網站」
- 選擇 「反向代理」 類型
填寫配置信息
主域名:claw.yourdomain.com 目標 URL:127.0.0.1:8080 代號:openclaw(自動生成)啟用 HTTPS
- 勾選 「申請 HTTPS 證書」
- 選擇 Let's Encrypt
- 輸入郵箱地址
- 點擊「確定」
高級配置(可選)
- 點擊「高級配置」標籤
- 可以自定義:
- 緩存策略
- 請求限制
- 安全頭
- WebSocket 支持
完成
- 點擊「確定」按鈕
- 等待證書申請完成(通常 1-2 分鐘)
- 訪問
https://claw.yourdomain.com驗證
2.3 1Panel 的優勢
- ✅ 圖形化界面:無需編寫配置文件
- ✅ 一鍵 HTTPS:自動申請和續期證書
- ✅ 實時監控:查看網站流量和性能
- ✅ 備份管理:定期自動備份配置
- ✅ 日誌查看:方便的日誌瀏覽和搜索
- ✅ 安全防護:內置 WAF 和防 CC 攻擊
方法三:使用 Caddy(現代化替代方案)
Caddy 是一個現代化的 Web 服務器,默認自動啟用 HTTPS,配置更簡潔。
3.1 安裝 Caddy
# 添加 Caddy 官方倉庫
sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list
# 安裝 Caddy
sudo apt update
sudo apt install caddy -y3.2 配置 Caddyfile
sudo nano /etc/caddy/Caddyfile添加以下內容:
claw.yourdomain.com {
# 自動 HTTPS(無需額外配置)
# 反向代理
reverse_proxy 127.0.0.1:8080 {
header_up Host {host}
header_up X-Real-IP {remote}
header_up X-Forwarded-For {remote}
header_up X-Forwarded-Proto {scheme}
}
# 安全頭
header {
Strict-Transport-Security "max-age=31536000;"
X-Frame-Options "SAMEORIGIN"
X-Content-Type-Options "nosniff"
X-XSS-Protection "1; mode=block"
}
# 日誌
log {
output file /var/log/caddy/openclaw.log
format json
}
}3.3 啟動 Caddy
# 測試配置
caddy validate
# 重啟 Caddy
sudo systemctl restart caddy
sudo systemctl enable caddy
# 查看日誌
sudo journalctl -u caddy -fCaddy 的優勢:
- 🚀 自動 HTTPS:無需手動配置證書
- 📝 簡潔配置:配置文件更易讀
- 🔄 自動重載:配置更改自動生效
- 📊 內置指標:提供 Prometheus 指標
2. 配置 HTTPS 與 SSL 證書
2.1 SSL 證書類型對比
| 證書類型 | 驗證級別 | 適用場景 | 價格 |
|---|---|---|---|
| DV (Domain Validation) | 域名驗證 | 個人網站、博客 | 免費-$$ |
| OV (Organization Validation) | 組織驗證 | 企業網站 | $$-$$$ |
| EV (Extended Validation) | 擴展驗證 | 金融、電商 | $$$-$$$$ |
| 通配符證書 | 域名驗證 | 多子域名 | $$-$$$ |
對於 OpenClaw,DV 證書(如 Let's Encrypt)完全足夠。
2.2 手動配置 SSL 證書(不使用 Certbot)
如果您已有 SSL 證書文件:
server {
listen 443 ssl http2;
server_name claw.yourdomain.com;
ssl_certificate /path/to/your/certificate.crt;
ssl_certificate_key /path/to/your/private.key;
# 如果使用證書鏈
ssl_trusted_certificate /path/to/chain.pem;
# ... 其他配置
}2.3 SSL 安全最佳實踐
# 只允許安全的協議和加密套件
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers off;
# 啟用 OCSP Stapling
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
# DH 參數(增強安全性)
# 生成命令:openssl dhparam -out /etc/nginx/ssl/dhparam.pem 2048
ssl_dhparam /etc/nginx/ssl/dhparam.pem;
# HSTS(HTTP Strict Transport Security)
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;2.4 測試 SSL 配置
使用以下工具測試您的 SSL 配置:
- SSL Labs - 全面的 SSL 測試
- Security Headers - 檢查安全頭
- Mozilla Observatory - 綜合安全評估
目標評級:A 或 A+
3. 自定義快捷指令與工作流
OpenClaw 的強大之處在於其靈活的自動化能力。通過自定義快捷指令和工作流,您可以實現複雜的業務邏輯。
3.1 工作流基礎概念
工作流(Workflow)由以下組件構成:
觸發器 (Trigger) → 條件 (Condition) → 動作 (Action) → 結果 (Result)常見觸發器:
- ⏰ 定時任務(Cron)
- 📨 收到消息
- 📧 收到郵件
- 🔄 API 調用
- 📁 文件變化
- 🌐 網頁更新
常見動作:
- 📤 發送消息
- 📝 創建文檔
- 🗄️ 數據庫操作
- 🌐 HTTP 請求
- 📊 生成報告
- 🔔 發送通知
3.2 配置文件格式
OpenClaw 的工作流配置採用 YAML 或 JSON 格式。以下是幾個實用示例:
示例 1:每日晨報自動生成
# config/workflows/daily-report.yaml
workflow:
name: "每日晨報"
description: "每天早上 8 點生成併發送晨報"
trigger:
type: cron
schedule: "0 8 * * *" # 每天 8:00
timezone: "Asia/Shanghai"
steps:
- name: "獲取天氣信息"
action: http_request
params:
url: "https://api.weather.com/v1/current"
method: GET
headers:
Authorization: "Bearer ${WEATHER_API_KEY}"
query:
city: "Beijing"
output: weather_data
- name: "獲取新聞摘要"
action: ai_generate
params:
model: "gpt-4-turbo"
prompt: |
請總結今天的科技新聞,包括:
1. AI 領域重要進展
2. 重大產品發佈
3. 行業趨勢分析
限制在 500 字以內。
output: news_summary
- name: "獲取股票行情"
action: http_request
params:
url: "https://api.finance.com/v1/stocks"
method: GET
query:
symbols: "AAPL,GOOGL,MSFT"
output: stock_data
- name: "生成晨報"
action: template_render
params:
template: |
📰 每日晨報 - {{ date }}
🌤️ 天氣:{{ weather_data.temperature }}°C, {{ weather_data.condition }}
📈 股市概覽:
- AAPL: {{ stock_data.AAPL.price }} ({{ stock_data.AAPL.change }}%)
- GOOGL: {{ stock_data.GOOGL.price }} ({{ stock_data.GOOGL.change }}%)
- MSFT: {{ stock_data.MSFT.price }} ({{ stock_data.MSFT.change }}%)
📝 科技新聞:
{{ news_summary }}
---
由 OpenClaw 自動生成
output: report_content
- name: "發送到 Telegram"
action: send_message
params:
platform: telegram
chat_id: "${TELEGRAM_CHAT_ID}"
message: "{{ report_content }}"
parse_mode: markdown
- name: "保存到文件"
action: write_file
params:
path: "/app/data/reports/daily-{{ date }}.md"
content: "{{ report_content }}"示例 2:網站監控與告警
# config/workflows/website-monitor.yaml
workflow:
name: "網站監控"
description: "每 5 分鐘檢查網站可用性,異常時發送告警"
trigger:
type: cron
schedule: "*/5 * * * *" # 每 5 分鐘
steps:
- name: "檢查網站狀態"
action: http_request
params:
url: "https://your-website.com"
method: GET
timeout: 10
expected_status: 200
output: check_result
on_error:
- name: "發送告警"
action: send_message
params:
platform: telegram
chat_id: "${ADMIN_CHAT_ID}"
message: |
🚨 網站告警
網站:https://your-website.com
狀態:{{ check_result.status_code }}
時間:{{ now }}
錯誤:{{ check_result.error }}
priority: high
- name: "記錄日誌"
action: write_log
params:
level: error
message: "Website down: {{ check_result.error }}"
- name: "嘗試重啟服務"
action: execute_command
params:
command: "docker restart openclaw"
timeout: 30示例 3:社交媒體自動發佈
# config/workflows/social-media-post.yaml
workflow:
name: "社交媒體自動發佈"
description: "從 RSS 訂閱獲取文章,自動發佈到多個平臺"
trigger:
type: rss_feed
url: "https://your-blog.com/feed.xml"
interval: 3600 # 每小時檢查一次
steps:
- name: "獲取最新文章"
action: parse_rss
params:
feed_url: "${RSS_FEED_URL}"
max_items: 5
output: articles
- name: "過濾已發佈"
action: filter
params:
input: "{{ articles }}"
condition: "item.published > last_check_time"
output: new_articles
- name: "生成社交媒體文案"
action: ai_generate
params:
model: "claude-3-sonnet"
prompt: |
請將以下文章標題和摘要改寫成適合 Twitter 的簡短文案:
標題:{{ article.title }}
摘要:{{ article.summary }}
要求:
- 長度不超過 280 字符
- 包含 2-3 個相關 hashtag
- 語氣活潑有趣
- 結尾添加文章鏈接
output: social_text
- name: "發佈到 Twitter"
action: post_to_twitter
params:
text: "{{ social_text }}"
media: "{{ article.image }}"
credentials:
api_key: "${TWITTER_API_KEY}"
api_secret: "${TWITTER_API_SECRET}"
access_token: "${TWITTER_ACCESS_TOKEN}"
access_secret: "${TWITTER_ACCESS_SECRET}"
- name: "發佈到 LinkedIn"
action: post_to_linkedin
params:
title: "{{ article.title }}"
content: "{{ article.summary }}"
url: "{{ article.link }}"
credentials:
access_token: "${LINKEDIN_ACCESS_TOKEN}"
- name: "記錄發佈歷史"
action: write_to_database
params:
table: "social_posts"
data:
article_id: "{{ article.id }}"
platforms: ["twitter", "linkedin"]
published_at: "{{ now }}"示例 4:JSON 格式的自定義命令
如果您更喜歡 JSON 格式:
{
"commands": [
{
"name": "auto-report",
"trigger": "cron",
"schedule": "0 8 * * *",
"timezone": "Asia/Shanghai",
"action": "generate_report",
"parameters": {
"target": "yesterday_metrics",
"format": "pdf",
"recipients": ["admin@example.com"],
"include_charts": true
},
"retry": {
"max_attempts": 3,
"delay_seconds": 60
}
},
{
"name": "backup-database",
"trigger": "cron",
"schedule": "0 2 * * 0",
"action": "execute_command",
"parameters": {
"command": "pg_dump -U openclaw openclaw > /backups/db-$(date +%Y%m%d).sql",
"timeout": 300
},
"notifications": {
"on_success": {
"platform": "telegram",
"message": "✅ 數據庫備份成功"
},
"on_failure": {
"platform": "telegram",
"message": "❌ 數據庫備份失敗:{{ error }}",
"priority": "high"
}
}
},
{
"name": "clean-old-logs",
"trigger": "cron",
"schedule": "0 3 1 * *",
"action": "cleanup",
"parameters": {
"directory": "/app/logs",
"pattern": "*.log",
"older_than_days": 30,
"dry_run": false
}
}
]
}3.3 高級工作流特性
條件分支
steps:
- name: "檢查溫度"
action: get_weather
output: weather
- name: "條件判斷"
action: conditional
conditions:
- if: "{{ weather.temperature }} > 30"
then:
- action: send_message
params:
message: "🌡️ 高溫預警!今天氣溫高達 {{ weather.temperature }}°C"
- if: "{{ weather.temperature }} < 10"
then:
- action: send_message
params:
message: "🥶 低溫提醒!注意保暖,今天氣溫 {{ weather.temperature }}°C"
- else:
- action: send_message
params:
message: "🌤️ 今天天氣宜人,氣溫 {{ weather.temperature }}°C"並行執行
steps:
- name: "並行獲取數據"
action: parallel
tasks:
- name: "獲取天氣"
action: get_weather
output: weather
- name: "獲取新聞"
action: get_news
output: news
- name: "獲取股票"
action: get_stocks
output: stocks
- name: "整合數據"
action: merge_data
params:
sources: ["weather", "news", "stocks"]錯誤處理
steps:
- name: "主要任務"
action: complex_task
on_error:
strategy: "retry"
max_retries: 3
retry_delay: 30
fallback:
- name: "備用方案"
action: alternative_task
- name: "通知管理員"
action: send_alert
params:
message: "主要任務失敗,已啟用備用方案"3.4 工作流管理命令
# 列出所有工作流
docker exec -it openclaw openclaw workflow list
# 查看工作流詳情
docker exec -it openclaw openclaw workflow show daily-report
# 手動觸發工作流
docker exec -it openclaw openclaw workflow run daily-report
# 禁用工作流
docker exec -it openclaw openclaw workflow disable daily-report
# 啟用工作流
docker exec -it openclaw openclaw workflow enable daily-report
# 刪除工作流
docker exec -it openclaw openclaw workflow delete old-workflow
# 導入工作流
docker exec -it openclaw openclaw workflow import /path/to/workflow.yaml
# 導出工作流
docker exec -it openclaw openclaw workflow export daily-report > daily-report.yaml4. 多任務併發調度與性能優化
如果您的 VPS 性能強勁(如 4核 8G 以上),可以通過調整配置來顯著提升 OpenClaw 的處理能力。
4.1 調整併發限制
編輯 docker-compose.yml 文件,增加環境變量參數:
services:
openclaw:
# ... 其他配置 ...
environment:
- MAX_CONCURRENT_TASKS=50 # 最大併發任務數
- MEMORY_LIMIT=4096M # 內存限制
- CPU_LIMIT=3.5 # CPU 限制(核數)
- WORKER_THREADS=8 # 工作線程數
- QUEUE_SIZE=1000 # 任務隊列大小
- TASK_TIMEOUT=300 # 任務超時時間(秒)
deploy:
resources:
limits:
cpus: '4.0'
memory: 4G
reservations:
cpus: '1.0'
memory: 1G參數說明:
| 參數 | 說明 | 推薦值 |
|---|---|---|
MAX_CONCURRENT_TASKS | 最大併發任務數 | 1核: 5, 2核: 10, 4核: 50 |
MEMORY_LIMIT | 內存限制 | 根據可用內存的 50-70% |
CPU_LIMIT | CPU 限制 | 總核數的 80% |
WORKER_THREADS | 工作線程數 | CPU 核數的 2 倍 |
QUEUE_SIZE | 任務隊列大小 | 100-1000 |
TASK_TIMEOUT | 單個任務超時 | 60-600 秒 |
更改後,重新應用配置:
cd /opt/openclaw
docker compose up -d4.2 數據庫優化
SQLite 優化(小型部署)
-- 連接到 SQLite 數據庫
docker exec -it openclaw sqlite3 /app/data/database.db
-- 啟用 WAL 模式(提高併發性能)
PRAGMA journal_mode=WAL;
-- 設置同步模式
PRAGMA synchronous=NORMAL;
-- 調整緩存大小(單位:頁,通常 4KB/頁)
PRAGMA cache_size=-64000; -- 64MB
-- 優化查詢
CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(status);
CREATE INDEX IF NOT EXISTS idx_tasks_created ON tasks(created_at);
CREATE INDEX IF NOT EXISTS idx_logs_timestamp ON logs(timestamp);
-- 定期維護
VACUUM;
ANALYZE;PostgreSQL 優化(中大型部署)
# docker-compose.yml 中添加 PostgreSQL 服務
services:
db:
image: postgres:15-alpine
container_name: openclaw-db
restart: unless-stopped
environment:
POSTGRES_DB: openclaw
POSTGRES_USER: openclaw
POSTGRES_PASSWORD: ${DB_PASSWORD}
volumes:
- ./postgres-data:/var/lib/postgresql/data
command:
- postgres
- -c
- max_connections=200
- -c
- shared_buffers=512MB
- -c
- effective_cache_size=1536MB
- -c
- maintenance_work_mem=128MB
- -c
- checkpoint_completion_target=0.9
- -c
- wal_buffers=16MB
- -c
- default_statistics_target=100
- -c
- random_page_cost=1.1
- -c
- effective_io_concurrency=200
- -c
- work_mem=4MB
- -c
- min_wal_size=1GB
- -c
- max_wal_size=4GB
networks:
- openclaw-network4.3 緩存策略
啟用 Redis 緩存
services:
redis:
image: redis:7-alpine
container_name: openclaw-redis
restart: unless-stopped
command: >
redis-server
--maxmemory 512mb
--maxmemory-policy allkeys-lru
--appendonly yes
--save 900 1
--save 300 10
--save 60 10000
volumes:
- ./redis-data:/data
networks:
- openclaw-network
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 3
openclaw:
# ... 其他配置 ...
environment:
- CACHE_BACKEND=redis
- REDIS_URL=redis://redis:6379/0
- CACHE_TTL=3600 # 緩存過期時間(秒)
depends_on:
redis:
condition: service_healthy緩存鍵策略:
# 示例:緩存 API 響應
cache_key = f"api_response:{endpoint}:{hash(params)}"
cached_result = redis.get(cache_key)
if cached_result:
return json.loads(cached_result)
else:
result = fetch_from_api(endpoint, params)
redis.setex(cache_key, 3600, json.dumps(result)) # 緩存 1 小時
return result4.4 負載均衡(多實例部署)
對於高負載場景,可以部署多個 OpenClaw 實例:
services:
openclaw-1:
image: openclaw/core:latest
container_name: openclaw-1
ports:
- "8081:8080"
environment:
- INSTANCE_ID=1
- MAX_CONCURRENT_TASKS=25
volumes:
- ./data-1:/app/data
- ./config:/app/config
networks:
- openclaw-network
openclaw-2:
image: openclaw/core:latest
container_name: openclaw-2
ports:
- "8082:8080"
environment:
- INSTANCE_ID=2
- MAX_CONCURRENT_TASKS=25
volumes:
- ./data-2:/app/data
- ./config:/app/config
networks:
- openclaw-network
nginx:
image: nginx:alpine
container_name: openclaw-lb
ports:
- "8080:80"
volumes:
- ./nginx-lb.conf:/etc/nginx/nginx.conf:ro
depends_on:
- openclaw-1
- openclaw-2
networks:
- openclaw-networkNginx 負載均衡配置:
upstream openclaw_backend {
least_conn; # 最少連接算法
server openclaw-1:8080 weight=1 max_fails=3 fail_timeout=30s;
server openclaw-2:8080 weight=1 max_fails=3 fail_timeout=30s;
}
server {
listen 80;
location / {
proxy_pass http://openclaw_backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}4.5 性能監控
使用 Docker Stats
# 實時監控資源使用
docker stats openclaw
# 輸出示例:
# CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O
# abc123 openclaw 45.23% 1.2GiB / 4GiB 30.00% 1.5GB / 500MB集成 Prometheus + Grafana
services:
prometheus:
image: prom/prometheus:latest
container_name: openclaw-prometheus
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml:ro
- ./prometheus-data:/prometheus
ports:
- "9090:9090"
networks:
- openclaw-network
grafana:
image: grafana/grafana:latest
container_name: openclaw-grafana
environment:
- GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_PASSWORD}
volumes:
- ./grafana-data:/var/lib/grafana
ports:
- "3000:3000"
depends_on:
- prometheus
networks:
- openclaw-networkPrometheus 配置:
# prometheus.yml
global:
scrape_interval: 15s
scrape_configs:
- job_name: 'openclaw'
static_configs:
- targets: ['openclaw:8080']
metrics_path: '/metrics'訪問 http://your-server:3000 查看 Grafana 儀表板。
5. 高級安全配置
5.1 訪問控制
IP 白名單
# Nginx 配置
location / {
allow 192.168.1.0/24; # 允許內網
allow 203.0.113.0/24; # 允許特定公網 IP
deny all; # 拒絕其他所有
proxy_pass http://127.0.0.1:8080;
}HTTP 基本認證
location / {
auth_basic "OpenClaw Admin Area";
auth_basic_user_file /etc/nginx/.htpasswd;
proxy_pass http://127.0.0.1:8080;
}# 創建密碼文件
sudo apt install apache2-utils -y
sudo htpasswd -c /etc/nginx/.htpasswd admin
# 輸入密碼5.2 API 速率限制
# 定義速率限制區域
limit_req_zone $binary_remote_addr zone=openclaw_api:10m rate=10r/s;
server {
location /api/ {
limit_req zone=openclaw_api burst=20 nodelay;
limit_req_status 429;
proxy_pass http://127.0.0.1:8080;
}
}5.3 防止 DDoS 攻擊
# 限制連接數
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
location / {
limit_conn addr 10; # 每個 IP 最多 10 個併發連接
limit_conn_status 429;
proxy_pass http://127.0.0.1:8080;
}
}5.4 Web 應用防火牆(WAF)
使用 ModSecurity 增強安全性:
# 安裝 ModSecurity
sudo apt install libnginx-mod-http-modsecurity -y
# 啟用 OWASP 核心規則集
sudo git clone https://github.com/coreruleset/coreruleset.git /etc/nginx/modsecurity-crsserver {
modsecurity on;
modsecurity_rules_file /etc/nginx/modsecurity.conf;
# ... 其他配置
}5.5 審計日誌
# OpenClaw 配置
logging:
level: info
format: json
outputs:
- type: file
path: /app/logs/audit.log
max_size: 100MB
max_backups: 10
compress: true
- type: syslog
address: udp://localhost:514
facility: local0
audit:
enabled: true
log_authentication: true
log_authorization: true
log_data_access: true
retention_days: 906. 監控與日誌管理
6.1 日誌輪轉
配置 Logrotate 防止日誌文件過大:
sudo nano /etc/logrotate.d/openclaw/opt/openclaw/logs/*.log {
daily
rotate 30
compress
delaycompress
missingok
notifempty
create 0644 root root
postrotate
docker exec openclaw kill -USR1 1
endscript
}6.2 集中式日誌(ELK Stack)
services:
elasticsearch:
image: elasticsearch:8.11.0
environment:
- discovery.type=single-node
- xpack.security.enabled=false
volumes:
- ./es-data:/usr/share/elasticsearch/data
networks:
- openclaw-network
kibana:
image: kibana:8.11.0
ports:
- "5601:5601"
depends_on:
- elasticsearch
networks:
- openclaw-network
logstash:
image: logstash:8.11.0
volumes:
- ./logstash.conf:/usr/share/logstash/pipeline/logstash.conf:ro
depends_on:
- elasticsearch
networks:
- openclaw-network6.3 告警配置
# 告警規則
alerts:
- name: "高 CPU 使用率"
condition: "cpu_usage > 80% for 5m"
severity: warning
notification:
- type: telegram
chat_id: "${ADMIN_CHAT_ID}"
message: "⚠️ CPU 使用率過高:{{ cpu_usage }}%"
- name: "內存不足"
condition: "memory_usage > 90% for 2m"
severity: critical
notification:
- type: telegram
chat_id: "${ADMIN_CHAT_ID}"
message: "🚨 內存嚴重不足:{{ memory_usage }}%"
- type: email
to: "admin@example.com"
- name: "服務宕機"
condition: "service_status == down"
severity: critical
notification:
- type: telegram
chat_id: "${ADMIN_CHAT_ID}"
message: "🚨 OpenClaw 服務已宕機!"
- type: sms
phone: "+86138xxxxxxxx"7. 備份與災難恢復
7.1 自動備份腳本
創建備份腳本:
#!/bin/bash
# /opt/openclaw/scripts/backup.sh
set -e
# 配置
BACKUP_DIR="/opt/backups/openclaw"
RETENTION_DAYS=30
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="openclaw_backup_${DATE}.tar.gz"
# 創建備份目錄
mkdir -p ${BACKUP_DIR}
# 停止服務
echo "Stopping OpenClaw..."
cd /opt/openclaw
docker compose down
# 創建備份
echo "Creating backup..."
tar -czf ${BACKUP_DIR}/${BACKUP_FILE} \
-C /opt/openclaw \
data/ \
config/ \
.env \
docker-compose.yml
# 啟動服務
echo "Starting OpenClaw..."
docker compose up -d
# 清理舊備份
echo "Cleaning old backups..."
find ${BACKUP_DIR} -name "openclaw_backup_*.tar.gz" -mtime +${RETENTION_DAYS} -delete
# 上傳到雲存儲(可選)
# aws s3 cp ${BACKUP_DIR}/${BACKUP_FILE} s3://your-bucket/backups/
echo "Backup completed: ${BACKUP_FILE}"設置定時任務:
# 每天凌晨 2 點執行備份
chmod +x /opt/openclaw/scripts/backup.sh
crontab -e
# 添加:
0 2 * * * /opt/openclaw/scripts/backup.sh >> /var/log/openclaw-backup.log 2>&17.2 異地備份
# 使用 rsync 同步到遠程服務器
rsync -avz --delete /opt/backups/openclaw/ user@backup-server:/backups/openclaw/
# 或使用 rclone 同步到雲存儲
rclone sync /opt/backups/openclaw remote:backups/openclaw7.3 災難恢復流程
# 1. 準備新服務器
ssh root@new-server
# 2. 安裝 Docker
curl -fsSL https://get.docker.com | bash
# 3. 下載備份
scp user@backup-server:/backups/openclaw/latest.tar.gz /opt/
# 4. 解壓備份
cd /opt
mkdir -p openclaw
tar -xzf latest.tar.gz -C openclaw
# 5. 啟動服務
cd /opt/openclaw
docker compose up -d
# 6. 驗證服務
docker ps
curl http://localhost:8080/health8. 插件開發與擴展
8.1 插件結構
my-plugin/
├── plugin.yaml # 插件元數據
├── main.py # 主程序
├── requirements.txt # Python 依賴
├── README.md # 使用說明
└── tests/ # 測試文件8.2 插件元數據
# plugin.yaml
name: my-custom-plugin
version: 1.0.0
description: 我的自定義插件
duthor: Your Name
license: MIT
min_openclaw_version: 2.0.0
entry_point: main:MyPlugin
dependencies:
- requests>=2.28.0
- beautifulsoup4>=4.11.0
config_schema:
api_key:
type: string
required: true
description: API 密鑰
timeout:
type: integer
default: 30
description: 超時時間(秒)8.3 插件代碼示例
# main.py
from openclaw.plugins import PluginBase
import requests
class MyPlugin(PluginBase):
def __init__(self, config):
super().__init__(config)
self.api_key = config.get('api_key')
self.timeout = config.get('timeout', 30)
def fetch_data(self, url):
"""從指定 URL 獲取數據"""
response = requests.get(
url,
headers={'Authorization': f'Bearer {self.api_key}'},
timeout=self.timeout
)
response.raise_for_status()
return response.json()
def process(self, task):
"""處理任務"""
url = task.get('url')
if not url:
raise ValueError("URL is required")
data = self.fetch_data(url)
# 處理數據
result = {
'status': 'success',
'data': data,
'timestamp': self.now()
}
return result
def now(self):
from datetime import datetime
return datetime.now().isoformat()8.4 安裝和使用插件
# 安裝插件
docker exec -it openclaw openclaw plugin install /path/to/my-plugin
# 列出已安裝插件
docker exec -it openclaw openclaw plugin list
# 啟用插件
docker exec -it openclaw openclaw plugin enable my-custom-plugin
# 配置插件
docker exec -it openclaw openclaw plugin config my-custom-plugin api_key=your_key
# 測試插件
docker exec -it openclaw openclaw plugin test my-custom-plugin9. 生產環境部署清單
在將 OpenClaw 部署到生產環境之前,請確保完成以下檢查:
9.1 安全檢查
9.2 性能檢查
9.3 可靠性檢查
9.4 合規檢查
總結與展望
恭喜您完成了 OpenClaw 的高級配置學習!現在您已經掌握了:
✅ 域名和 HTTPS 配置 - 使用 Nginx、1Panel 或 Caddy 綁定域名
✅ 自定義工作流 - 創建複雜的自動化任務
✅ 性能優化 - 調整併發、緩存和數據庫
✅ 安全加固 - 訪問控制、速率限制和 WAF
✅ 監控告警 - 實時監控系統狀態
✅ 備份恢復 - 確保數據安全
✅ 插件開發 - 擴展 OpenClaw 功能
🚀 下一步行動
- 實踐所學 - 立即應用這些高級配置到您的 OpenClaw 實例
- 加入社區 - 分享您的經驗和插件
- 持續關注 - 關注官方更新和新特性
- 貢獻代碼 - 為 OpenClaw 項目做出貢獻
📚 延伸閱讀
💬 獲取支持
- 🐛 報告問題:GitHub Issues
- 💬 討論交流:Discord 社區
- 📧 郵件支持:support@openclaw.dev
- 📖 常見問題:FAQ
🎉 祝賀您! 您現在已經是一位 OpenClaw 高級用戶了。繼續探索和實踐,您將能夠構建出強大的自動化系統,大幅提升工作效率!
💡 提示:收藏本頁面以備將來參考。如果您覺得本教程有幫助,歡迎分享給更多朋友!