Home Tutorials Categories Skills About
ZH EN JA KO
Security-Ops

Managing OpenClaw Processes with PM2 and Systemd

· 20 min read

Introduction

Running openclaw up directly in a terminal has a critical flaw: once the terminal is closed or the SSH session disconnects, the service stops. This article introduces two production-grade process management solutions -- PM2 and Systemd -- to help you keep OpenClaw running reliably on your server.

1. PM2 Approach (Recommended)

PM2 is the most popular process manager in the Node.js ecosystem and is naturally compatible with OpenClaw.

1.1 Installing PM2

# Install PM2 globally
npm install -g pm2

# Verify installation
pm2 --version

1.2 Quick Start with OpenClaw

# Start OpenClaw with PM2
pm2 start openclaw -- up

# Check running status
pm2 status

Output example:

┌─────┬──────────┬─────────────┬─────────┬─────────┬──────────┐
│ id  │ name     │ namespace   │ mode    │ status  │ cpu      │
├─────┼──────────┼─────────────┼─────────┼─────────┼──────────┤
│ 0   │ openclaw │ default     │ fork    │ online  │ 0.3%     │
└─────┴──────────┴─────────────┴─────────┴─────────┴──────────┘

1.3 Using an Ecosystem Configuration File

For production environments, it is recommended to use a PM2 ecosystem configuration file for fine-grained control:

# Create configuration file
nano ~/openclaw-ecosystem.config.js
// ~/openclaw-ecosystem.config.js
module.exports = {
  apps: [
    {
      name: "openclaw",
      script: "openclaw",
      args: "up",
      cwd: process.env.HOME,

      // Restart policy
      autorestart: true,
      max_restarts: 10,
      min_uptime: "30s",
      restart_delay: 5000,

      // Resource limits
      max_memory_restart: "512M",

      // Environment variables
      env: {
        NODE_ENV: "production",
        NODE_OPTIONS: "--max-old-space-size=512"
      },

      // Log configuration
      log_file: "/var/log/openclaw/combined.log",
      out_file: "/var/log/openclaw/out.log",
      error_file: "/var/log/openclaw/error.log",
      log_date_format: "YYYY-MM-DD HH:mm:ss Z",
      merge_logs: true,

      // Watch for file changes and auto-restart (for development use)
      watch: false,

      // Graceful shutdown
      kill_timeout: 10000,
      listen_timeout: 15000
    }
  ]
};
# Create log directory
sudo mkdir -p /var/log/openclaw
sudo chown $USER:$USER /var/log/openclaw

# Start using the ecosystem file
pm2 start ~/openclaw-ecosystem.config.js

# Check status
pm2 status

1.4 Auto-Start on Boot

This is one of PM2's most powerful features -- auto-start on boot with a single command:

# Generate startup script (automatically selects systemd/upstart/launchd based on your system)
pm2 startup

# The system will output a command that needs to be run with sudo -- copy and execute it
# For example:
# sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u your_user --hp /home/your_user

# Save the current process list
pm2 save

Important: After any changes to PM2-managed processes (adding, removing, or restarting), you must run pm2 save to update the saved process list.

1.5 Common PM2 Management Commands

Command Function
pm2 status View all process statuses
pm2 logs openclaw View real-time logs
pm2 logs openclaw --lines 100 View the last 100 log lines
pm2 restart openclaw Restart the service
pm2 stop openclaw Stop the service
pm2 delete openclaw Delete the process
pm2 reload openclaw Zero-downtime reload
pm2 monit Open the real-time monitoring dashboard
pm2 describe openclaw View detailed process information
pm2 env 0 View process environment variables

1.6 PM2 Real-Time Monitoring Dashboard

# Launch the interactive monitoring dashboard
pm2 monit

This dashboard displays the following information in real time:

  • CPU and memory usage
  • Real-time log scrolling
  • Process metadata (PID, uptime, restart count)
  • Custom metrics

1.7 PM2 Log Management

After prolonged operation, log files can grow very large. Use the pm2-logrotate module for automatic rotation:

# Install log rotation module
pm2 install pm2-logrotate

# Configure rotation parameters
pm2 set pm2-logrotate:max_size 50M       # Max 50MB per file
pm2 set pm2-logrotate:retain 7           # Retain the last 7 files
pm2 set pm2-logrotate:compress true      # Compress old logs
pm2 set pm2-logrotate:dateFormat YYYY-MM-DD_HH-mm-ss
pm2 set pm2-logrotate:rotateInterval '0 0 * * *'  # Rotate daily

# Manually flush current logs
pm2 flush openclaw

1.8 Upgrading OpenClaw with PM2

When you need to upgrade OpenClaw:

# 1. Upgrade OpenClaw
npm install -g openclaw@latest

# 2. Restart the process in PM2
pm2 restart openclaw

# 3. Verify version and status
pm2 describe openclaw
curl -s http://localhost:18789/health | jq .version

2. Systemd Approach

If you prefer the native Linux process management method, Systemd is the best choice.

2.1 Creating a Systemd Service File

# Find the openclaw installation path
which openclaw
# Usually /usr/bin/openclaw or /usr/local/bin/openclaw

# Create the service file
sudo nano /etc/systemd/system/openclaw.service
[Unit]
Description=OpenClaw AI Assistant Platform
Documentation=https://openclaw.com
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=openclaw
Group=openclaw
WorkingDirectory=/home/openclaw

# Start command
ExecStart=/usr/local/bin/openclaw up
ExecStop=/bin/kill -SIGTERM $MAINPID
ExecReload=/bin/kill -SIGUSR2 $MAINPID

# Environment variables
Environment=NODE_ENV=production
Environment=NODE_OPTIONS=--max-old-space-size=512

# Restart policy
Restart=always
RestartSec=10
StartLimitBurst=5
StartLimitIntervalSec=60

# Resource limits
MemoryMax=1G
CPUQuota=80%

# Security hardening
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=read-only
ReadWritePaths=/home/openclaw/.config/openclaw
ReadWritePaths=/home/openclaw/.openclaw
PrivateTmp=true

# Logging
StandardOutput=journal
StandardError=journal
SyslogIdentifier=openclaw

[Install]
WantedBy=multi-user.target

2.2 Creating a Dedicated User (Recommended)

# Create a system user
sudo useradd -r -m -s /bin/bash openclaw

# Switch to that user to complete initial configuration
sudo -u openclaw bash -c "openclaw onboard"

2.3 Enabling and Managing the Service

# Reload systemd configuration
sudo systemctl daemon-reload

# Enable auto-start on boot
sudo systemctl enable openclaw

# Start the service
sudo systemctl start openclaw

# Check status
sudo systemctl status openclaw

2.4 Common Systemd Management Commands

Command Function
systemctl start openclaw Start the service
systemctl stop openclaw Stop the service
systemctl restart openclaw Restart the service
systemctl status openclaw Check status
systemctl enable openclaw Enable auto-start on boot
systemctl disable openclaw Disable auto-start on boot
journalctl -u openclaw -f View logs in real time
journalctl -u openclaw --since "1 hour ago" View logs from the last hour
journalctl -u openclaw -p err View error logs only

2.5 Systemd Log Management

Systemd uses journald for log management. You can control log size as follows:

# Edit journald configuration
sudo nano /etc/systemd/journald.conf

# Set maximum log disk usage
# SystemMaxUse=500M
# SystemMaxFileSize=50M

# Restart journald
sudo systemctl restart systemd-journald

# Manually clean old logs (keep last 3 days)
sudo journalctl --vacuum-time=3d

# Manually clean old logs (limit total size to 200MB)
sudo journalctl --vacuum-size=200M

3. PM2 vs Systemd Comparison

Feature PM2 Systemd
Installation Difficulty Easy (npm install) No installation needed (built-in)
Configuration Difficulty Moderate Moderate
Node.js Integration Native support Requires manual configuration
Monitoring Dashboard Built-in (pm2 monit) Requires third-party tools
Log Management Requires plugin Native journald support
Security Hardening Limited Rich sandboxing options
Resource Limits Memory limits Comprehensive CPU/memory/IO limits
Cluster Mode Supported Not directly supported
Cross-Platform Windows/Mac/Linux Linux only
Best For Development / small production Production environments

4. Crash Recovery Testing

Regardless of which approach you use, it is recommended to test crash recovery:

# Get OpenClaw's PID
pgrep -f "openclaw up"

# Simulate a process crash
kill -9 $(pgrep -f "openclaw up")

# Wait a few seconds and check if it auto-restarted
sleep 15

# PM2 approach
pm2 status

# Systemd approach
systemctl status openclaw

5. Best Practice Recommendations

  1. Personal projects or development environments: Use PM2 -- simple setup, feature-rich
  2. Production servers: Use Systemd -- more security hardening options
  3. Combine both: Use Systemd to manage PM2 itself, getting the best of both worlds
  4. Always configure log rotation: Prevent disk from filling up with log files
  5. Set reasonable restart limits: Avoid infinite restart loops consuming resources
  6. Use alongside monitoring: Refer to the "OpenClaw Service Monitoring and Alerting Configuration Guide" on this site to set up monitoring

Once you have process management configured, your OpenClaw service will have enterprise-grade operational stability, and you will never have to worry about unexpected interruptions again.

OpenClaw is a free, open-source personal AI assistant that supports WhatsApp, Telegram, Discord, and many more platforms