02-347-7730  |  Saeree ERP - ระบบ ERP ครบวงจรสำหรับธุรกิจไทย ติดต่อเรา

Deploy OpenClaw สู่ Production

Deploy OpenClaw สู่ Production Security Monitoring Scaling Docker Container
  • 3
  • เมษายน

OpenClaw Deep Dive Series EP.5 — จาก EP.4 ที่เราสร้าง Multi-Agent Workflow ให้ AI หลายตัวทำงานร่วมกันเป็นทีมไปแล้ว ตอนนี้ถึงเวลานำ OpenClaw ขึ้น Production จริง! การรัน Agent บนเครื่อง dev กับการ deploy ให้ user หลายคนใช้งานพร้อมกันนั้นต่างกันมาก — ต้องคิดเรื่อง Security, Monitoring, Scaling ให้รองรับสภาพแวดล้อมจริง เหมือนกับ การ deploy Ollama แบบ Self-host ที่ต้องใส่ใจเรื่อง ความปลอดภัย ตั้งแต่วันแรก

สรุปสั้น — สิ่งที่จะได้เรียนรู้ในบทความนี้:

  • Docker / Container Deployment — Containerize OpenClaw ด้วย Docker + docker-compose
  • Reverse Proxy + TLS — nginx + SSL Certificate ป้องกันการดักฟัง
  • Authentication & Authorization — API Key, JWT, OAuth2/SSO + RBAC
  • Logging & Monitoring — Structured Logging + Prometheus + Grafana
  • Scaling Strategies — Vertical, Horizontal, Queue-based
  • Backup & Recovery — สำรองข้อมูล Agent configs, conversation history

Production vs Development — ต่างกันอย่างไร?

หลายคนรัน OpenClaw บน localhost แล้วคิดว่า "ก็ใช้ได้ดี" แต่พอเปิดให้ user จริงเข้ามาใช้ ปัญหาจะตามมาทันที — ไม่มี authentication ใครก็เข้าได้, ไม่มี monitoring ไม่รู้ว่าระบบล่ม, ไม่มี backup ข้อมูลหาย ก็สูญไปเลย

ด้าน Development Production
Network localhost:3000 ไม่มี TLS Domain + Reverse Proxy + TLS (HTTPS)
Authentication ไม่มี ใครก็เข้าได้ API Key / JWT / OAuth2 + RBAC
Users คนเดียว (developer) หลายคนพร้อมกัน + Load Balancing
Monitoring ดูจาก console.log Prometheus + Grafana + Alerts
Backup ไม่มี Automated Backup + Disaster Recovery Plan
Deployment npm start / node index.js Docker Container + Orchestration

Docker Deployment — Containerize OpenClaw

ขั้นตอนแรกของการ deploy คือ Containerize — ทำให้ OpenClaw รันใน Docker Container เพื่อให้ environment เหมือนกันทุกที่ ไม่ว่าจะเป็น dev, staging, หรือ production

Dockerfile

# Dockerfile สำหรับ OpenClaw Production
FROM node:20-alpine AS builder

WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

COPY . .

# Multi-stage build — ลดขนาด image
FROM node:20-alpine
WORKDIR /app

# Security: ไม่รัน root
RUN addgroup -S openclaw && adduser -S openclaw -G openclaw

COPY --from=builder /app /app
RUN chown -R openclaw:openclaw /app

USER openclaw

EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=10s --retries=3 \
  CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1

CMD ["node", "index.js"]

docker-compose.yml

# docker-compose.yml — OpenClaw + nginx + Redis
version: '3.8'

services:
  openclaw:
    build: .
    restart: unless-stopped
    env_file: .env
    networks:
      - openclaw-net
    depends_on:
      - redis
    healthcheck:
      test: ["CMD", "wget", "--spider", "http://localhost:3000/health"]
      interval: 30s
      timeout: 10s
      retries: 3

  nginx:
    image: nginx:alpine
    restart: unless-stopped
    ports:
      - "443:443"
      - "80:80"
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
      - ./certs:/etc/nginx/certs:ro
    depends_on:
      - openclaw
    networks:
      - openclaw-net

  redis:
    image: redis:7-alpine
    restart: unless-stopped
    command: redis-server --requirepass ${REDIS_PASSWORD}
    volumes:
      - redis-data:/data
    networks:
      - openclaw-net

networks:
  openclaw-net:
    driver: bridge

volumes:
  redis-data:

Environment Variables (.env)

ตัวแปร ตัวอย่างค่า คำอธิบาย
NODE_ENV production โหมด production (ปิด debug, เปิด optimization)
LLM_API_KEY sk-xxxx... API Key สำหรับเชื่อม LLM (OpenAI, Anthropic, etc.)
REDIS_PASSWORD strong-random-password Password สำหรับ Redis (session + queue)
API_SECRET jwt-secret-key Secret สำหรับ sign JWT token
LOG_LEVEL info ระดับ log (debug, info, warn, error)

Reverse Proxy + TLS

ห้ามเปิด OpenClaw ให้เข้าถึงจาก internet โดยตรง — ต้องผ่าน Reverse Proxy เสมอ เพื่อจัดการ TLS, rate limiting, access control เหมือนกับ การตั้งค่า Ollama แบบ self-host ที่ต้องมี nginx คั่นหน้า

# nginx.conf — Reverse Proxy + TLS + WebSocket
server {
    listen 80;
    server_name openclaw.example.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name openclaw.example.com;

    # TLS — Let's Encrypt
    ssl_certificate     /etc/nginx/certs/fullchain.pem;
    ssl_certificate_key /etc/nginx/certs/privkey.pem;
    ssl_protocols       TLSv1.2 TLSv1.3;
    ssl_ciphers         HIGH:!aNULL:!MD5;

    # Security Headers
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header Strict-Transport-Security "max-age=31536000" always;

    # Rate Limiting
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

    location / {
        limit_req zone=api burst=20 nodelay;
        proxy_pass http://openclaw:3000;
        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;
    }

    # WebSocket สำหรับ streaming responses
    location /ws {
        proxy_pass http://openclaw:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_read_timeout 86400;
    }
}

หรือใช้ Caddy ที่จัดการ TLS อัตโนมัติ — แค่ 5 บรรทัด:

# Caddyfile — Auto TLS
openclaw.example.com {
    reverse_proxy openclaw:3000
    encode gzip
}

Authentication & Authorization

OpenClaw ที่เปิดให้ใครก็เข้าได้ = อันตราย! ต้องมีระบบ ยืนยันตัวตน ทุกครั้ง — เลือกระดับความปลอดภัยตามความเหมาะสมขององค์กร:

ระดับ วิธี เหมาะกับ ข้อดี
Basic API Key ใน Header Internal tools, ทีมเล็ก ง่าย ตั้งค่าเร็ว
Standard JWT Token (per-user) ทีมขนาดกลาง ต้องแยก user แยก user ได้ ตรวจสอบ audit log
Enterprise OAuth2 / SSO (AD, LDAP) องค์กรใหญ่ มี Identity Provider จัดการจากส่วนกลาง ปลอดภัยสูงสุด

Middleware: API Key Validation

// middleware/auth.js — API Key Validation

const VALID_API_KEYS = new Set(
  process.env.API_KEYS?.split(',') || []
);

function authenticateApiKey(req, res, next) {
  const apiKey = req.headers['x-api-key'];

  if (!apiKey) {
    return res.status(401).json({
      error: 'Missing API Key',
      message: 'ส่ง API Key ผ่าน header: X-API-Key'
    });
  }

  if (!VALID_API_KEYS.has(apiKey)) {
    console.warn(`[Auth] Invalid API Key attempt from ${req.ip}`);
    return res.status(403).json({
      error: 'Invalid API Key'
    });
  }

  // ระบุ user จาก API Key (สำหรับ audit log)
  req.user = { apiKey: apiKey.substring(0, 8) + '...' };
  next();
}

module.exports = { authenticateApiKey };

RBAC — Role-Based Access Control

Role สิทธิ์ ตัวอย่างผู้ใช้
Admin Full Access — จัดการ Agent, Skill, Module, User ทั้งหมด DevOps, ผู้ดูแลระบบ
User Chat + ใช้ Agent ที่อนุญาต (ไม่สามารถแก้ config) พนักงานทั่วไป
ReadOnly ดู logs + dashboard เท่านั้น (ไม่สามารถ chat) ผู้บริหาร, ผู้ตรวจสอบ

การใช้ Digital Signature ร่วมกับ API Key จะช่วยป้องกันการปลอมแปลง request ได้ดียิ่งขึ้น โดยเฉพาะในองค์กรที่ต้องการความปลอดภัยระดับสูง

Logging & Monitoring

ถ้าไม่ monitor ก็ไม่รู้ว่าระบบมีปัญหา — Production ต้องมี logging ที่ดีตั้งแต่วันแรก เพื่อให้ บริหารความเสี่ยง ได้ทันท่วงที

สิ่งที่ต้อง Log

  • User messages — ใครส่งอะไร เมื่อไหร่ (anonymize ถ้ามี PII)
  • Agent actions — Agent ตัวไหนทำอะไร ใช้เวลาเท่าไหร่
  • Tool calls — เรียก Skill/Module อะไร ผลลัพธ์เป็นอย่างไร
  • Errors — Error ทุกตัว พร้อม stack trace
  • Response times — แต่ละ request ใช้เวลาเท่าไหร่

Structured Logging (JSON)

// logger.js — Structured JSON Logging
const winston = require('winston');

const logger = winston.createLogger({
  level: process.env.LOG_LEVEL || 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.json()
  ),
  defaultMeta: { service: 'openclaw-production' },
  transports: [
    new winston.transports.File({ filename: 'logs/error.log', level: 'error' }),
    new winston.transports.File({ filename: 'logs/combined.log' })
  ]
});

// ตัวอย่าง log entry:
// {
//   "timestamp": "2026-04-03T09:15:30.123Z",
//   "level": "info",
//   "service": "openclaw-production",
//   "message": "Agent completed task",
//   "agent": "research-agent",
//   "userId": "user-abc",
//   "duration_ms": 2340,
//   "tokens_used": 1520,
//   "status": "success"
// }

Key Metrics — ตัวเลขที่ต้องเฝ้าดู

Metric เป้าหมาย แจ้งเตือนเมื่อ
Requests/sec < 100 req/s > 80 req/s (ใกล้ capacity)
Response Time (p95) < 5 วินาที > 10 วินาที (ช้าเกินไป)
Error Rate < 1% > 5% (มีปัญหาร้ายแรง)
Token Usage/day ตาม budget ที่ตั้งไว้ > 80% ของ daily budget
Cost per Request ตาม baseline เพิ่มขึ้น > 50% จาก baseline

แนะนำใช้ Prometheus เก็บ metrics + Grafana แสดง dashboard + ตั้ง alert rules แจ้งเตือนผ่าน Slack/Email เมื่อค่าผิดปกติ

Scaling Strategies — รองรับ User เยอะขึ้น

เมื่อ user เพิ่มขึ้น OpenClaw instance เดียวอาจไม่พอ — มี 3 กลยุทธ์หลักในการ scale:

กลยุทธ์ วิธี เหมาะกับ ข้อจำกัด
Vertical Scaling เพิ่ม CPU / RAM ให้เครื่องเดิม เริ่มต้น ง่ายสุด ไม่ต้องแก้ code มีเพดาน ไม่สามารถเพิ่มได้ไม่จำกัด
Horizontal Scaling เพิ่มจำนวน instance + Load Balancer user เยอะ ต้องการ high availability ต้องจัดการ session sharing (Redis)
Queue-based Redis Queue สำหรับ async processing งาน AI ที่ใช้เวลานาน ไม่ต้องรอ real-time ไม่เหมาะกับ chat แบบ real-time

Architecture: Horizontal Scaling

# Architecture — Horizontal Scaling with Load Balancer

User Request
    |
    v
[nginx Load Balancer] (Round Robin / Least Connections)
    |
    |--> [OpenClaw Instance 1] -->\
    |--> [OpenClaw Instance 2] --> [Shared Redis] --> [LLM API]
    |--> [OpenClaw Instance 3] -->/
    |
    v
[Prometheus + Grafana] (Monitoring)
[Log Aggregator] (ELK / Loki)

ทุก instance แชร์ Redis สำหรับ session, queue, cache — ทำให้ user คุยกับ instance ไหนก็ได้ ข้อมูลไม่หาย

Backup & Recovery

ข้อมูล AI Agent สำคัญกว่าที่คิด — Agent configs, Skill definitions, conversation history หายไปแล้วสร้างใหม่ได้ยาก ต้องมีแผน Disaster Recovery ที่ชัดเจน

สิ่งที่ต้อง Backup

  • Agent configs — YAML/JSON ที่กำหนด agent, prompt, model
  • Skills & Modules — custom code ที่เขียนเอง
  • Conversation history — ประวัติการสนทนา (ถ้าเก็บ)
  • .env file — environment variables (เก็บแยก ห้ามอยู่ใน git)
  • Redis data — session, cache, queue

Backup Script (Cron Job)

#!/bin/bash
# backup-openclaw.sh — รันทุกวัน ตี 2 ผ่าน cron
# crontab: 0 2 * * * /opt/openclaw/backup-openclaw.sh

BACKUP_DIR="/backup/openclaw/$(date +%Y-%m-%d)"
OPENCLAW_DIR="/opt/openclaw"

mkdir -p "$BACKUP_DIR"

# 1. Backup Agent configs + Skills
cp -r "$OPENCLAW_DIR/agents" "$BACKUP_DIR/"
cp -r "$OPENCLAW_DIR/skills" "$BACKUP_DIR/"
cp -r "$OPENCLAW_DIR/modules" "$BACKUP_DIR/"

# 2. Backup conversation history (Redis RDB)
docker exec openclaw-redis redis-cli -a "$REDIS_PASSWORD" BGSAVE
sleep 5
docker cp openclaw-redis:/data/dump.rdb "$BACKUP_DIR/redis-dump.rdb"

# 3. Backup .env (encrypted)
gpg --symmetric --cipher-algo AES256 -o "$BACKUP_DIR/env.gpg" "$OPENCLAW_DIR/.env"

# 4. Compress
tar -czf "$BACKUP_DIR.tar.gz" "$BACKUP_DIR"
rm -rf "$BACKUP_DIR"

# 5. ลบ backup เก่ากว่า 30 วัน
find /backup/openclaw/ -name "*.tar.gz" -mtime +30 -delete

echo "[Backup] Completed: $BACKUP_DIR.tar.gz"

ข้อผิดพลาดที่ห้ามทำใน Production:

  • ห้ามเปิด OpenClaw ให้เข้าถึงจาก internet โดยตรง — ต้องผ่าน Reverse Proxy เสมอ ป้องกัน การโจมตี ได้ดีกว่า
  • ห้ามเก็บ API Key ใน code หรือ commit ลง git — ใช้ .env หรือ Secret Manager (Vault, AWS Secrets)
  • ห้ามข้าม monitoring — ถ้าไม่ monitor ก็ไม่รู้ว่าระบบล่มจนกว่า user จะโทรมาแจ้ง
  • ต้อง rotate credentials สม่ำเสมอ — เปลี่ยน API Key, JWT Secret, Redis Password ทุก 90 วัน
  • ห้ามใช้ SQL query ตรงๆ — ถ้า Agent เชื่อมกับ DB ต้องใช้ parameterized query เท่านั้น

Saeree ERP + Production AI:

Saeree ERP กำลังพัฒนา AI Assistant ที่ออกแบบมาสำหรับ production ตั้งแต่แรก — รองรับ on-premise deployment ด้วย SSL A+ rating, การยืนยันตัวตนแบบ 2FA, backup อัตโนมัติ, monitoring ครบวงจร สนใจระบบ ERP ที่พร้อมรองรับ AI ในอนาคต ปรึกษาทีมงานฟรี ไม่มีค่าใช้จ่าย

OpenClaw Deep Dive Series — อ่านต่อ

"Deploy AI Agent สู่ Production ไม่ใช่แค่รัน npm start — ต้องคิดเรื่อง Security, Monitoring, Scaling เหมือนทุกระบบที่ให้บริการจริง"

- ทีมงาน Saeree ERP

แหล่งอ้างอิง

สนใจระบบ ERP สำหรับองค์กรของคุณ?

ปรึกษาผู้เชี่ยวชาญจาก Grand Linux Solution ฟรี ไม่มีค่าใช้จ่าย

ขอ Demo ฟรี

โทร 02-347-7730 | sale@grandlinux.com

Saeree ERP Author

เกี่ยวกับผู้เขียน

ไพฑูรย์ บุตรี

ผู้เชี่ยวชาญด้านระบบเน็ตเวิร์คและระบบความปลอดภัยเซิร์ฟเวอร์ บริษัท แกรนด์ลีนุกซ์ โซลูชั่น จำกัด