欢迎光临
我们一直在努力

OpenClaw 多网关管理方案

OpenClaw 多网关管理方案

整理自实际部署调试过程,涵盖两种方案的原理、对比与完整实现代码。 适用版本:OpenClaw 2026.3.x +


一、背景与核心概念

为什么需要多网关

每个租户(用户)需要独立的 agent 运行环境,包括独立的 sessions、凭据、workspace 和端口,互不干扰。

隔离的四个要素

每个 Gateway 实例必须保持以下四项唯一:

隔离项说明
OPENCLAW_CONFIG_PATH 独立配置文件路径
OPENCLAW_STATE_DIR 独立状态目录(sessions、凭据、缓存)
agents.defaults.workspace 独立 workspace 根目录
gateway.port 独立端口号

端口规划

每个 Gateway 的 base port 会自动派生额外端口:

  • Browser control service port = base + 2(仅 loopback)
  • Browser CDP 范围:controlPort + 9 到 + 108

两实例之间至少留 20 端口间距。

setup 与 onboard 的区别

  • openclaw setup:轻量初始化,只创建目录和配置骨架,不写 gateway.mode,直接启动会报错 Gateway start blocked: set gateway.mode=local
  • openclaw onboard:完整引导流程,写入 gateway.mode 等完整配置
  • 本文方案:跳过两者,直接手动写 openclaw.json,最可靠,也与主 gateway 配置维护方式一致

二、方案对比

方案一:–profile方案二:环境变量 + 注册表
路径管理 OpenClaw 自动,散落在 ~/.openclaw-<name>/ 统一在自定义目录,结构清晰
重启命令 openclaw –profile <name> gateway restart 只能走 Python 脚本
批量重启 需要自己扫描目录 读注册表,更可靠
删除清理 需手动找目录 rm remove_gateway() 一步完成
与主 gateway 隔离 目录散落 ~/,容易混淆 物理隔离,不影响主 gateway
适合场景 少量实例、手动运维 服务端程序化批量管理

结论:服务端程序化管理推荐方案二(环境变量 + 注册表)。


三、方案一:–profile 方式

原理

–profile <name> 是 OpenClaw 内置的隔离机制,自动将路径映射到:

~/.openclaw-<name>/openclaw.json ← 配置文件
~/.openclaw-<name>/ ← state 目录
~/.openclaw/workspace-<name>/ ← workspace

手动操作命令

# 初始化(注意:setup 不会写 gateway.mode,需要补写)
openclaw –profile zhangsan setup

# 补写 gateway.mode(或直接编辑 ~/.openclaw-zhangsan/openclaw.json)
openclaw –profile zhangsan configure gateway –mode local

# 启动
openclaw –profile zhangsan gateway –port 29001

# 注册为系统服务(开机自启)
openclaw –profile zhangsan gateway install –port 29001

# 停止 / 重启 / 卸载
openclaw –profile zhangsan gateway stop
openclaw –profile zhangsan gateway restart
openclaw –profile zhangsan gateway uninstall

Python 实现

import subprocess
import os
import json
import shutil
from pathlib import Path

BASE_PORT = 29001
PORT_STEP = 20
LLM_BASE_URL = "https://coding.dashscope.aliyuncs.com/apps/anthropic"
LLM_API_KEY = "sk-sp-xxx"
LLM_MODEL_ID = "qwen3-coder"
GATEWAY_TOKEN = "your-token"

def get_port(index: int) –> int:
return BASE_PORT + index * PORT_STEP

def get_profile_config_path(user_id: str) –> Path:
return Path.home() / f".openclaw-{user_id}" / "openclaw.json"

def get_profile_workspace(user_id: str) –> Path:
return Path.home() / ".openclaw" / f"workspace-{user_id}"

def build_config(user_id: str, port: int) –> dict:
return {
"models": {
"mode": "merge",
"providers": {
"qwen-coder-plan": {
"baseUrl": LLM_BASE_URL,
"apiKey": LLM_API_KEY,
"api": "anthropic-messages",
"models": [{
"id": LLM_MODEL_ID,
"name": "qwen3 coder next",
"reasoning": False,
"input": ["text"],
"cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0},
"contextWindow": 128000,
"maxTokens": 8192
}]
}
}
},
"agents": {
"defaults": {
"workspace": str(get_profile_workspace(user_id)),
"model": f"qwen-coder-plan/{LLM_MODEL_ID}"
}
},
"gateway": {
"mode": "local",
"port": port,
"bind": "lan",
"auth": {"mode": "token", "token": GATEWAY_TOKEN},
"http": {"endpoints": {"chatCompletions": {"enabled": True}}},
"controlUi": {"allowInsecureAuth": True, "dangerouslyDisableDeviceAuth": True}
},
"session": {"dmScope": "per-channel-peer"}
}

def setup_gateway(user_id: str, index: int) –> int:
port = get_port(index)
config_path = get_profile_config_path(user_id)
config_path.parent.mkdir(parents=True, exist_ok=True)
get_profile_workspace(user_id).mkdir(parents=True, exist_ok=True)

config_path.write_text(json.dumps(build_config(user_id, port), indent=2, ensure_ascii=False))

subprocess.Popen(
["openclaw", "–profile", user_id, "gateway", "–port", str(port)],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
print(f"[{user_id}] Gateway 已启动 port={port}")
return port

def stop_gateway(user_id: str):
subprocess.run(["openclaw", "–profile", user_id, "gateway", "stop"])

def restart_gateway(user_id: str):
config_path = get_profile_config_path(user_id)
config = json.loads(config_path.read_text())
port = config["gateway"]["port"]
subprocess.run(["openclaw", "–profile", user_id, "gateway", "stop"])
subprocess.Popen(
["openclaw", "–profile", user_id, "gateway", "–port", str(port)],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
print(f"[{user_id}] Gateway 已重启 port={port}")

def restart_all_gateways():
home = Path.home()
profiles = [
d.name.replace(".openclaw-", "")
for d in home.iterdir()
if d.is_dir() and d.name.startswith(".openclaw-")
]
for user_id in profiles:
try:
restart_gateway(user_id)
except Exception as e:
print(f"[{user_id}] 重启失败: {e}")

def remove_gateway(user_id: str):
stop_gateway(user_id)
shutil.rmtree(Path.home() / f".openclaw-{user_id}", ignore_errors=True)
shutil.rmtree(get_profile_workspace(user_id), ignore_errors=True)
print(f"[{user_id}] Gateway 已删除")


四、方案二:环境变量 + 注册表(推荐)

原理

完全绕过 OpenClaw 的 profile 机制,通过两个环境变量手动指定路径:

OPENCLAW_CONFIG_PATH=/path/to/openclaw.json
OPENCLAW_STATE_DIR=/path/to/state/

每个 openclaw 命令都必须携带这两个环境变量,否则会回落到默认路径。

用一个 registry.json 文件记录所有租户的路径和端口,实现重启、批量操作等管理功能。

目录结构

~/.openclaw-tenants/
├── registry.json ← 注册表,记录所有租户信息
├── zhangsan/
│ ├── openclaw.json ← 租户配置文件
│ ├── state/ ← sessions、凭据、缓存
│ └── workspace/ ← agent workspace
├── lisi/
│ ├── openclaw.json
│ ├── state/
│ └── workspace/
└── …

registry.json 结构

{
"zhangsan": {
"port": 29001,
"config_path": "/root/.openclaw-tenants/zhangsan/openclaw.json",
"state_dir": "/root/.openclaw-tenants/zhangsan/state"
},
"lisi": {
"port": 29021,
"config_path": "/root/.openclaw-tenants/lisi/openclaw.json",
"state_dir": "/root/.openclaw-tenants/lisi/state"
}
}

完整 Python 实现

import subprocess
import os
import json
import shutil
from pathlib import Path

# ── 基础配置 ──────────────────────────────────────────
BASE_PORT = 29001
PORT_STEP = 20
BASE_DIR = Path.home() / ".openclaw-tenants"
REGISTRY_PATH = BASE_DIR / "registry.json"

LLM_BASE_URL = "https://coding.dashscope.aliyuncs.com/apps/anthropic"
LLM_API_KEY = "sk-sp-xxx"
LLM_MODEL_ID = "qwen3-coder"
GATEWAY_TOKEN = "your-token"

# ── 注册表操作 ────────────────────────────────────────

def _load_registry() –> dict:
if REGISTRY_PATH.exists():
return json.loads(REGISTRY_PATH.read_text())
return {}

def _save_registry(registry: dict):
REGISTRY_PATH.parent.mkdir(parents=True, exist_ok=True)
REGISTRY_PATH.write_text(json.dumps(registry, indent=2, ensure_ascii=False))

def _get_env(info: dict) –> dict:
"""注入环境变量,让 openclaw 命令使用租户隔离路径"""
return {
**os.environ,
"OPENCLAW_CONFIG_PATH": info["config_path"],
"OPENCLAW_STATE_DIR": info["state_dir"],
}

# ── 端口 & 配置生成 ───────────────────────────────────

def _next_port() –> int:
registry = _load_registry()
if not registry:
return BASE_PORT
return max(v["port"] for v in registry.values()) + PORT_STEP

def _build_config(user_id: str, port: int, gateway_token: str) –> dict:
workspace = str(BASE_DIR / user_id / "workspace")
return {
"models": {
"mode": "merge",
"providers": {
"qwen-coder-plan": {
"baseUrl": LLM_BASE_URL,
"apiKey": LLM_API_KEY,
"api": "anthropic-messages",
"models": [{
"id": LLM_MODEL_ID,
"name": "qwen3 coder next",
"reasoning": False,
"input": ["text"],
"cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0},
"contextWindow": 128000,
"maxTokens": 8192
}]
}
}
},
"agents": {
"defaults": {
"workspace": workspace,
"model": f"qwen-coder-plan/{LLM_MODEL_ID}"
}
},
"gateway": {
"mode": "local",
"port": port,
"bind": "lan",
"auth": {"mode": "token", "token": gateway_token},
"http": {"endpoints": {"chatCompletions": {"enabled": True}}},
"controlUi": {
"allowInsecureAuth": True,
"dangerouslyDisableDeviceAuth": True
}
},
"session": {"dmScope": "per-channel-peer"}
}

# ── 核心操作 ──────────────────────────────────────────

def setup_gateway(user_id: str) –> int:
registry = _load_registry()
if user_id in registry:
raise ValueError(f"{user_id} 已存在")

port = _next_port()
gateway_token = generate_gateway_token() # ← 在这里调用
tenant_dir = BASE_DIR / user_id
config_path = tenant_dir / "openclaw.json"
state_dir = tenant_dir / "state"

for d in [config_path.parent, state_dir, tenant_dir / "workspace"]:
d.mkdir(parents=True, exist_ok=True)

config_path.write_text(
json.dumps(_build_config(user_id, port, gateway_token), indent=2, ensure_ascii=False)
)

registry[user_id] = {
"port": port,
"config_path": str(config_path),
"state_dir": str(state_dir),
"gateway_token": gateway_token,
}
_save_registry(registry)

_start_process(user_id, registry[user_id])
print(f"[{user_id}] Gateway 已启动 port={port}")
return port

def _start_process(user_id: str, info: dict):
"""启动 gateway 进程(内部复用)"""
subprocess.Popen(
["openclaw", "gateway", "–port", str(info["port"])],
env=_get_env(info),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)

def stop_gateway(user_id: str):
"""停止租户 Gateway"""
registry = _load_registry()
if user_id not in registry:
raise ValueError(f"未找到租户: {user_id}")
subprocess.run(["openclaw", "gateway", "stop"], env=_get_env(registry[user_id]))
print(f"[{user_id}] Gateway 已停止")

def restart_gateway(user_id: str):
"""重启单个租户 Gateway"""
registry = _load_registry()
if user_id not in registry:
raise ValueError(f"未找到租户: {user_id}")
info = registry[user_id]
subprocess.run(["openclaw", "gateway", "stop"], env=_get_env(info))
_start_process(user_id, info)
print(f"[{user_id}] Gateway 已重启 port={info['port']}")

def restart_all_gateways():
"""重启所有租户 Gateway"""
registry = _load_registry()
if not registry:
print("注册表为空,没有租户 Gateway")
return
print(f"共 {len(registry)} 个租户,开始重启…")
for user_id, info in registry.items():
try:
subprocess.run(["openclaw", "gateway", "stop"], env=_get_env(info))
_start_process(user_id, info)
print(f" [{user_id}] ✓ port={info['port']}")
except Exception as e:
print(f" [{user_id}] ✗ 失败: {e}")

def remove_gateway(user_id: str):
"""停止并删除租户所有数据"""
registry = _load_registry()
if user_id not in registry:
raise ValueError(f"未找到租户: {user_id}")
subprocess.run(["openclaw", "gateway", "stop"], env=_get_env(registry[user_id]))
shutil.rmtree(BASE_DIR / user_id, ignore_errors=True)
del registry[user_id]
_save_registry(registry)
print(f"[{user_id}] Gateway 已删除")

def list_gateways():
"""列出所有租户 Gateway"""
registry = _load_registry()
if not registry:
print("暂无租户 Gateway")
return
print(f"{'用户ID':<20} {'端口':<8} 配置路径")
print("-" * 60)
for user_id, info in registry.items():
print(f"{user_id:<20} {info['port']:<8} {info['config_path']}")

# ── 使用示例 ──────────────────────────────────────────
if __name__ == "__main__":
# 创建
setup_gateway("zhangsan")
setup_gateway("lisi")

# 列出
list_gateways()

# 重启单个
restart_gateway("zhangsan")

# 重启全部
restart_all_gateways()

# 删除
remove_gateway("lisi")

注意事项

环境变量必须每次传递:每个 openclaw 命令都要携带 OPENCLAW_CONFIG_PATH 和 OPENCLAW_STATE_DIR,漏传会导致操作作用到默认 profile 上。

不要把租户目录放在 ~/.openclaw/ 内部:~/.openclaw/ 是主 gateway 的根目录,嵌套进去有被 doctor –fix 或清理命令误删的风险。统一放在 ~/.openclaw-tenants/ 下物理隔离。

API key 安全:生产环境不要把 LLM_API_KEY 和 GATEWAY_TOKEN 硬编码在脚本里,改用环境变量或 secrets 管理工具注入。


五、常见报错速查

报错信息原因解决方法
Gateway start blocked: set gateway.mode=local 用了 setup 而非 onboard,gateway.mode 未写入 直接手动写 openclaw.json 并包含 gateway.mode: local
Non-interactive onboarding requires explicit risk acknowledgement onboard –non-interactive 缺少参数 补充 –accept-risk(仅部分 auth-choice 需要)或改为直接写配置文件
error: unknown option '–accept-risk' 当前 auth-choice 不需要该参数 去掉 –accept-risk,或改为直接写配置文件
EADDRINUSE 端口冲突 确保两实例间隔 ≥ 20 端口
multiple reachable gateways detected probe 警告,多实例下正常 确认各实例路径和端口已隔离即可忽略

六、参考链接

  • Gateway Runbook
  • Multiple Gateways
  • CLI Automation
  • CLI Reference
  • Gateway Troubleshooting
赞(0)
未经允许不得转载:171主机测评 » OpenClaw 多网关管理方案
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址