> ## Documentation Index
> Fetch the complete documentation index at: https://docs.orcbot.buzzchat.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Deployment

> Production deployment options for OrcBot including Docker, daemon mode, and monitoring

## Overview

OrcBot is designed to run as a long-running service that listens for events from Telegram, WhatsApp, Discord, or other channels. This guide covers deployment strategies for production environments.

<Note>
  OrcBot needs to stay active to:

  * Listen for incoming messages on communication channels
  * Run scheduled tasks and heartbeats
  * Process background actions from the queue
  * Maintain active connections to channel APIs
</Note>

## Deployment Options

### 1. Daemon Mode (Recommended for VPS)

**Best for:** Single-server deployments, personal use, development.

```bash theme={null}
# Start as background daemon
orcbot run --daemon

# Check status
orcbot daemon status

# View logs
tail -f ~/.orcbot/daemon.log

# Stop daemon
orcbot daemon stop
```

**Features:**

* Built-in process management
* PID file tracking (`~/.orcbot/orcbot.pid`)
* Log rotation
* Graceful shutdown
* Conflict detection (prevents multiple instances)

### 2. Docker (Recommended for Production)

**Best for:** Cloud deployments, scalability, isolation.

#### Using Docker Compose (Minimal)

```yaml theme={null}
# docker-compose.minimal.yml
version: '3.8'

services:
  orcbot:
    build: .
    image: orcbot:latest
    container_name: orcbot
    restart: unless-stopped
    environment:
      - OPENAI_API_KEY=${OPENAI_API_KEY}
      - TELEGRAM_TOKEN=${TELEGRAM_TOKEN}
    volumes:
      - ./data:/root/.orcbot
    ports:
      - "3100:3100"  # Web gateway (optional)
```

**Setup:**

<Steps>
  <Step title="Create .env file">
    ```bash theme={null}
    cp .env.example .env
    # Edit .env with your API keys
    ```
  </Step>

  <Step title="Build and start">
    ```bash theme={null}
    docker compose -f docker-compose.minimal.yml up -d
    ```
  </Step>

  <Step title="View logs">
    ```bash theme={null}
    docker logs -f orcbot
    ```
  </Step>

  <Step title="Access shell">
    ```bash theme={null}
    docker exec -it orcbot /bin/sh
    ```
  </Step>
</Steps>

#### Using Docker Compose (Full Stack)

```yaml theme={null}
# docker-compose.yml
version: '3.8'

services:
  orcbot:
    build:
      context: .
      dockerfile: Dockerfile
    image: orcbot:latest
    container_name: orcbot
    restart: unless-stopped
    environment:
      - OPENAI_API_KEY=${OPENAI_API_KEY}
      - GOOGLE_API_KEY=${GOOGLE_API_KEY}
      - TELEGRAM_TOKEN=${TELEGRAM_TOKEN}
      - WHATSAPP_ENABLED=${WHATSAPP_ENABLED}
      - DISCORD_TOKEN=${DISCORD_TOKEN}
    volumes:
      - ./data:/root/.orcbot
      - ./config:/app/config
    ports:
      - "3100:3100"
    networks:
      - orcbot-network
    healthcheck:
      test: ["CMD", "node", "-e", "require('http').get('http://localhost:3100/api/status', (res) => process.exit(res.statusCode === 200 ? 0 : 1))"]
      interval: 30s
      timeout: 10s
      retries: 3

networks:
  orcbot-network:
    driver: bridge
```

**Start:**

```bash theme={null}
docker compose up -d
```

### 3. PM2 Process Manager

**Best for:** Node.js-optimized deployments, shared hosting.

```bash theme={null}
# Install PM2 globally
npm install -g pm2

# Start OrcBot
pm2 start dist/cli/index.js --name orcbot -- run

# View logs
pm2 logs orcbot

# Restart
pm2 restart orcbot

# Stop
pm2 stop orcbot

# Auto-start on system reboot
pm2 startup
pm2 save
```

**PM2 Ecosystem File:**

```javascript theme={null}
// ecosystem.config.js
module.exports = {
  apps: [{
    name: 'orcbot',
    script: './dist/cli/index.js',
    args: 'run',
    instances: 1,
    autorestart: true,
    watch: false,
    max_memory_restart: '1G',
    env: {
      NODE_ENV: 'production',
      ORCBOT_DATA_DIR: '/var/orcbot'
    },
    error_file: './logs/err.log',
    out_file: './logs/out.log',
    log_date_format: 'YYYY-MM-DD HH:mm:ss Z'
  }]
};
```

**Start with ecosystem:**

```bash theme={null}
pm2 start ecosystem.config.js
```

### 4. Systemd Service (Linux)

**Best for:** Native Linux integration, system-level management.

```ini theme={null}
# /etc/systemd/system/orcbot.service
[Unit]
Description=OrcBot AI Agent
After=network.target

[Service]
Type=simple
User=orcbot
WorkingDirectory=/home/orcbot/orcbot
ExecStart=/usr/bin/node /home/orcbot/orcbot/dist/cli/index.js run
Restart=always
RestartSec=10
StandardOutput=append:/var/log/orcbot/orcbot.log
StandardError=append:/var/log/orcbot/error.log
Environment="NODE_ENV=production"
Environment="ORCBOT_DATA_DIR=/var/lib/orcbot"

[Install]
WantedBy=multi-user.target
```

**Setup:**

<Steps>
  <Step title="Create service user">
    ```bash theme={null}
    sudo useradd -r -s /bin/false orcbot
    sudo mkdir -p /var/lib/orcbot /var/log/orcbot
    sudo chown orcbot:orcbot /var/lib/orcbot /var/log/orcbot
    ```
  </Step>

  <Step title="Install service file">
    ```bash theme={null}
    sudo cp orcbot.service /etc/systemd/system/
    sudo systemctl daemon-reload
    ```
  </Step>

  <Step title="Enable and start">
    ```bash theme={null}
    sudo systemctl enable orcbot
    sudo systemctl start orcbot
    ```
  </Step>

  <Step title="Check status">
    ```bash theme={null}
    sudo systemctl status orcbot
    sudo journalctl -u orcbot -f
    ```
  </Step>
</Steps>

## Cloud Platforms

### Railway

<Steps>
  <Step title="Connect repository">
    Link your GitHub repository to Railway.
  </Step>

  <Step title="Set environment variables">
    Add `OPENAI_API_KEY`, `TELEGRAM_TOKEN`, etc. in the Railway dashboard.
  </Step>

  <Step title="Deploy">
    Railway auto-detects Node.js and runs `npm start`.
  </Step>
</Steps>

**Procfile:**

```
web: node dist/cli/index.js run
```

### Heroku

```bash theme={null}
# Install Heroku CLI
curl https://cli-assets.heroku.com/install.sh | sh

# Login
heroku login

# Create app
heroku create orcbot-prod

# Set environment variables
heroku config:set OPENAI_API_KEY=sk-...
heroku config:set TELEGRAM_TOKEN=123...

# Deploy
git push heroku main

# View logs
heroku logs --tail
```

### AWS EC2

<Steps>
  <Step title="Launch EC2 instance">
    * AMI: Ubuntu Server 22.04 LTS
    * Instance type: t3.small (2 vCPU, 2 GB RAM)
    * Storage: 20 GB SSD
  </Step>

  <Step title="Install dependencies">
    ```bash theme={null}
    sudo apt update
    sudo apt install -y nodejs npm
    ```
  </Step>

  <Step title="Clone and build">
    ```bash theme={null}
    git clone https://github.com/fredabila/orcbot.git
    cd orcbot
    npm install
    npm run build
    ```
  </Step>

  <Step title="Configure environment">
    ```bash theme={null}
    cp .env.example .env
    nano .env  # Add your API keys
    ```
  </Step>

  <Step title="Start with PM2">
    ```bash theme={null}
    npm install -g pm2
    pm2 start dist/cli/index.js --name orcbot -- run
    pm2 startup
    pm2 save
    ```
  </Step>
</Steps>

### DigitalOcean Droplet

Similar to AWS EC2 - follow the same steps.

**Recommended:** Use Docker for easier deployment.

## Configuration for Production

### Environment Variables

```bash theme={null}
# .env
NODE_ENV=production
ORCBOT_DATA_DIR=/var/lib/orcbot

# LLM API Keys
OPENAI_API_KEY=sk-...
GOOGLE_API_KEY=...

# Channels
TELEGRAM_TOKEN=123...
DISCORD_TOKEN=...
WHATSAPP_ENABLED=true

# Web Gateway
GATEWAY_PORT=3100
GATEWAY_API_KEY=strong-random-key

# Security
SAFE_MODE=false
ADMIN_USER_TELEGRAM=123456789
```

### Production Config

```yaml theme={null}
# orcbot.config.yaml
modelName: gpt-4o
llmProvider: openai

# Performance
maxStepsPerAction: 15
maxMessagesPerAction: 25
messageDedupWindow: 5

# Autonomy
autonomyEnabled: true
autonomyInterval: 600000  # 10 minutes
autonomyAllowedChannels:
  - telegram

# Memory
memoryContextLimit: 15000
consolidateThreshold: 100

# Logging
logLevel: info  # info, warn, error (not debug in prod)

# Gateway
gatewayPort: 3100
gatewayHost: 0.0.0.0
gatewayApiKey: ${GATEWAY_API_KEY}

# Security
safeMode: false
adminUsers:
  telegram: ["${ADMIN_USER_TELEGRAM}"]
```

## Monitoring

### Health Checks

**HTTP Endpoint:**

```bash theme={null}
curl http://localhost:3100/api/status
```

**Response:**

```json theme={null}
{
  "status": "running",
  "uptime": 3600,
  "memory": {
    "used": 250,
    "total": 512
  },
  "queueDepth": 0,
  "activeWorkers": 2
}
```

**Docker Healthcheck:**

```dockerfile theme={null}
HEALTHCHECK --interval=30s --timeout=10s --retries=3 \
  CMD node -e "require('http').get('http://localhost:3100/api/status', (res) => process.exit(res.statusCode === 200 ? 0 : 1))"
```

### Logging

**View Logs:**

```bash theme={null}
# Daemon mode
tail -f ~/.orcbot/daemon.log

# Docker
docker logs -f orcbot

# PM2
pm2 logs orcbot

# Systemd
sudo journalctl -u orcbot -f
```

**Log Rotation:**

```bash theme={null}
# /etc/logrotate.d/orcbot
/var/log/orcbot/*.log {
    daily
    rotate 14
    compress
    delaycompress
    notifempty
    missingok
    create 0640 orcbot orcbot
}
```

### Metrics

**Custom Prometheus Exporter:**

```typescript theme={null}
// src/utils/metrics.ts
import { Registry, Counter, Gauge } from 'prom-client';

const register = new Registry();

export const tasksProcessed = new Counter({
  name: 'orcbot_tasks_processed_total',
  help: 'Total tasks processed',
  registers: [register]
});

export const queueDepth = new Gauge({
  name: 'orcbot_queue_depth',
  help: 'Current action queue depth',
  registers: [register]
});

export { register };
```

**Expose Metrics:**

```typescript theme={null}
// In gateway/index.ts
app.get('/metrics', (req, res) => {
  res.set('Content-Type', register.contentType);
  res.end(register.metrics());
});
```

## Updates and Maintenance

### Updating OrcBot

<Steps>
  <Step title="Backup data">
    ```bash theme={null}
    tar -czf orcbot-backup-$(date +%Y%m%d).tar.gz ~/.orcbot/
    ```
  </Step>

  <Step title="Pull updates">
    ```bash theme={null}
    cd ~/orcbot
    git pull origin main
    ```
  </Step>

  <Step title="Install dependencies">
    ```bash theme={null}
    npm install
    ```
  </Step>

  <Step title="Rebuild">
    ```bash theme={null}
    npm run build
    ```
  </Step>

  <Step title="Restart">
    ```bash theme={null}
    # Daemon
    orcbot daemon restart

    # Docker
    docker compose restart

    # PM2
    pm2 restart orcbot

    # Systemd
    sudo systemctl restart orcbot
    ```
  </Step>
</Steps>

### Database Migrations

OrcBot uses file-based storage by default (no migrations needed).

**If using SQLite:**

```bash theme={null}
# Backup database
cp ~/.orcbot/orcbot.db ~/.orcbot/orcbot.db.backup

# Run migrations (if added in future versions)
node dist/migrations/migrate.js
```

## Troubleshooting

### Agent Not Starting

**Check logs:**

```bash theme={null}
# Daemon
cat ~/.orcbot/daemon.log

# Docker
docker logs orcbot

# Systemd
sudo journalctl -u orcbot -n 50
```

**Common issues:**

* Missing API keys
* Port already in use (3100)
* Invalid configuration syntax
* Insufficient permissions

### High Memory Usage

**Symptoms:** Agent uses over 1GB RAM.

**Solutions:**

```yaml theme={null}
# Reduce memory limits
memoryContextLimit: 10000  # Down from 15000
consolidateThreshold: 50   # More frequent consolidation

# Disable vector memory if not needed
vectorMemoryEnabled: false
```

**Restart periodically:**

```bash theme={null}
# With PM2
pm2 start dist/cli/index.js --name orcbot --max-memory-restart 1G -- run
```

### Channel Disconnections

**Telegram:** Token revoked or bot blocked.

```bash theme={null}
# Test token
curl "https://api.telegram.org/bot<TOKEN>/getMe"
```

**WhatsApp:** Session expired.

```bash theme={null}
# Re-pair device
orcbot ui
# Navigate to Connections → WhatsApp → Reconnect
```

**Discord:** Invalid token or missing permissions.

```bash theme={null}
# Regenerate token in Discord Developer Portal
# Update config and restart
```

## Best Practices

<CardGroup cols={2}>
  <Card title="Use Docker" icon="docker">
    Containerize for portability and isolation.
  </Card>

  <Card title="Enable Health Checks" icon="heart-pulse">
    Monitor agent status and restart on failure.
  </Card>

  <Card title="Rotate Logs" icon="rotate">
    Prevent disk space issues with log rotation.
  </Card>

  <Card title="Backup Regularly" icon="floppy-disk">
    Backup config and memory daily.
  </Card>

  <Card title="Monitor Resources" icon="chart-line">
    Track CPU, memory, and disk usage.
  </Card>

  <Card title="Update Dependencies" icon="arrows-rotate">
    Keep Node.js and npm packages up to date.
  </Card>
</CardGroup>

## Related Guides

<CardGroup cols={2}>
  <Card title="Configuration" href="/guides/configuration">
    Configure OrcBot for production
  </Card>

  <Card title="Security" href="/advanced/security">
    Production security best practices
  </Card>

  <Card title="Web Gateway" href="/guides/web-gateway">
    Expose OrcBot via REST API
  </Card>

  <Card title="Multi-Agent" href="/advanced/multi-agent">
    Scale with worker processes
  </Card>
</CardGroup>
