> 记录时间: 2026-02-25
> 系统环境: Linux (Amazon Linux 2023), systemd
---
## 1. 创建 systemd 用户服务
创建服务文件 `~/.config/systemd/user/openclaw.service`:
```
mkdir -p ~/.config/systemd/user
```
文件内容:
```ini
[Unit]
Description=OpenClaw Gateway
After=network.target
[Service]
Type=simple
Environment=PATH=/home/ec2-user/.npm-global/bin:/usr/local/nodejs/bin:/usr/bin:/bin
Environment=AWS_REGION=us-east-1
ExecStart=/home/ec2-user/.npm-global/bin/openclaw gateway --port 18789
Restart=always
RestartSec=5
[Install]
WantedBy=default.target
```
关键配置说明:
| 配置项 | 说明 |
|--------|------|
| `Environment=PATH=...` | 确保 node 和 openclaw 命令可被找到 |
| `Environment=AWS_REGION=us-east-1` | Bedrock 所在区域 |
| `Restart=always` | 进程崩溃后自动重启 |
| `RestartSec=5` | 重启间隔 5 秒 |
---
## 2. 启用并启动服务
```bash
# 重新加载 systemd 配置
systemctl --user daemon-reload
# 设置开机自启
systemctl --user enable openclaw
# 启动服务
systemctl --user start openclaw
```
---
## 3. 开启 linger(关键!)
默认情况下,用户退出 SSH 后 systemd 用户服务会被停止。开启 linger 后服务会持续运行:
```bash
sudo loginctl enable-linger ec2-user
```
---
## 4. 常用管理命令
```bash
# 查看服务状态
systemctl --user status openclaw
# 实时查看日志
journalctl --user -u openclaw -f
# 查看最近 100 行日志
journalctl --user -u openclaw -n 100
# 重启服务(修改配置后需要执行)
systemctl --user restart openclaw
# 停止服务
systemctl --user stop openclaw
# 禁用开机自启
systemctl --user disable openclaw
```
---
## 5. 修改配置后的操作流程
编辑 `~/.openclaw/openclaw.json` 后,需要重启服务使配置生效:
```bash
systemctl --user restart openclaw
```
如果修改了服务文件本身(`~/.config/systemd/user/openclaw.service`),需要先重新加载:
```bash
systemctl --user daemon-reload
systemctl --user restart openclaw
```
---
## 6. 故障排查
```bash
# 服务启动失败时查看详细日志
journalctl --user -u openclaw --no-pager -n 50
# 确认进程是否在运行
systemctl --user is-active openclaw
# 确认 linger 是否开启
loginctl show-user ec2-user | grep Linger
# 应输出: Linger=yes
```