> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch42-hands-on-project/42.5-deployment-and-launch.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 42.5 Deployment and Launch

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~370k tokens, Output \~5k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

After completing MiniClaw's feature development, this section guides readers through deploying it to a production environment. We will cover three aspects: Docker containerization, daemon process configuration, and security hardening.

## 42.5.1 Docker Containerization

### Dockerfile

Referencing OpenClaw's multi-stage build (Chapter 37), write a Dockerfile for MiniClaw:

```dockerfile
# Dockerfile

# Stage 1: Build
FROM node:22-slim AS builder
WORKDIR /app
COPY package.json pnpm-lock.yaml ./
RUN corepack enable && pnpm install --frozen-lockfile
COPY . .
RUN pnpm build

# Stage 2: Runtime
FROM node:22-slim AS runtime
RUN groupadd -r miniclaw && useradd -r -g miniclaw -m miniclaw
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json .
COPY --from=builder /app/ui ./ui

# Run as non-root user
USER miniclaw

# Data directory
VOLUME /home/miniclaw/.miniclaw
ENV NODE_ENV=production

EXPOSE 3000 8080
CMD ["node", "dist/index.js"]
```

Key security measures:

| Measure             | Description                                                 |
| ------------------- | ----------------------------------------------------------- |
| Multi-stage build   | Production image doesn't include build tools or source code |
| Non-root user       | Run with `miniclaw` user, reducing privileges               |
| `--frozen-lockfile` | Ensures dependency versions match development environment   |
| VOLUME mount        | Data persistence on host machine                            |

### docker-compose.yml

```yaml
# docker-compose.yml

version: "3.8"

services:
  miniclaw:
    build: .
    ports:
      - "3000:3000"
      - "8080:8080"
    volumes:
      - miniclaw-data:/home/miniclaw/.miniclaw
    environment:
      - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
      - TELEGRAM_BOT_TOKEN=${TELEGRAM_BOT_TOKEN}
    restart: unless-stopped
    # Resource limits
    deploy:
      resources:
        limits:
          memory: 512M
          cpus: "1.0"

volumes:
  miniclaw-data:
```

### Startup Commands

```bash
# Build image
docker compose build

# Create .env file
echo "ANTHROPIC_API_KEY=sk-ant-..." > .env
echo "TELEGRAM_BOT_TOKEN=123456:ABC..." >> .env

# Start
docker compose up -d

# View logs
docker compose logs -f
```

## 42.5.2 Daemon Process Configuration

For deployments not using Docker, MiniClaw needs to be configured as a system daemon.

### systemd (Linux)

```ini
# /etc/systemd/system/miniclaw.service

[Unit]
Description=MiniClaw AI Assistant
After=network.target

[Service]
Type=simple
User=miniclaw
WorkingDirectory=/opt/miniclaw
ExecStart=/usr/bin/node dist/index.js
Restart=on-failure
RestartSec=5s

# Environment variables
EnvironmentFile=/opt/miniclaw/.env

# Security hardening
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/opt/miniclaw/.miniclaw

# Resource limits
MemoryMax=512M
CPUQuota=100%

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

```bash
# Install service
sudo systemctl daemon-reload
sudo systemctl enable miniclaw
sudo systemctl start miniclaw

# Check status
sudo systemctl status miniclaw
sudo journalctl -u miniclaw -f
```

### launchd (macOS)

```xml
<!-- ~/Library/LaunchAgents/com.miniclaw.gateway.plist -->

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>com.miniclaw.gateway</string>
  <key>ProgramArguments</key>
  <array>
    <string>/usr/local/bin/node</string>
    <string>/opt/miniclaw/dist/index.js</string>
  </array>
  <key>WorkingDirectory</key>
  <string>/opt/miniclaw</string>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>StandardOutPath</key>
  <string>/tmp/miniclaw-stdout.log</string>
  <key>StandardErrorPath</key>
  <string>/tmp/miniclaw-stderr.log</string>
  <key>EnvironmentVariables</key>
  <dict>
    <key>NODE_ENV</key>
    <string>production</string>
  </dict>
</dict>
</plist>
```

```bash
# Load service
launchctl load ~/Library/LaunchAgents/com.miniclaw.gateway.plist

# Stop service
launchctl unload ~/Library/LaunchAgents/com.miniclaw.gateway.plist
```

## 42.5.3 Security Hardening

Referencing OpenClaw's security model (Chapter 32), MiniClaw's minimum security checklist:

### 1. Authentication Protection

```typescript
// Add simple token authentication to Gateway

const GATEWAY_TOKEN = process.env.MINICLAW_TOKEN;

gateway.addMiddleware((client, frame) => {
  if (!GATEWAY_TOKEN) return true;  // Skip if not configured
  if (client.authenticated) return true;

  if (frame.type === "req" && frame.method === "auth") {
    const token = (frame.params as { token: string })?.token;
    if (token === GATEWAY_TOKEN) {
      client.authenticated = true;
      return true;
    }
    return false;  // Authentication failed
  }
  return false;  // Unauthenticated requests rejected
});
```

### 2. Tool Safety

```typescript
// Enhanced Bash tool security

const BLOCKED_COMMANDS = [
  /rm\s+-rf\s+\//,
  /mkfs/,
  /dd\s+if=\/dev/,
  />(\/etc|\/var|\/usr)/,
  /curl.*\|\s*(bash|sh)/,
  /wget.*\|\s*(bash|sh)/,
];

const ALLOWED_PATHS = [
  process.cwd(),
  path.join(os.homedir(), ".miniclaw"),
];

function isSafeCommand(command: string): boolean {
  for (const pattern of BLOCKED_COMMANDS) {
    if (pattern.test(command)) return false;
  }
  return true;
}

function isSafePath(filePath: string): boolean {
  const resolved = path.resolve(filePath);
  return ALLOWED_PATHS.some(allowed => resolved.startsWith(allowed));
}
```

### 3. Input Sanitization

```typescript
// Prevent prompt injection

function sanitizeInput(message: string): string {
  // Remove potential system prompt injection attempts
  const dangerous = [
    /ignore (previous|above|all) instructions/i,
    /you are now/i,
    /system:\s/i,
    /\[SYSTEM\]/i,
  ];

  let sanitized = message;
  for (const pattern of dangerous) {
    if (pattern.test(sanitized)) {
      sanitized = `[User message - potentially contains instruction override attempt]\n\n${sanitized}`;
      break;
    }
  }
  return sanitized;
}
```

### 4. Reverse Proxy

In production, it's recommended to use Caddy or Nginx as a reverse proxy:

```
# Caddyfile

miniclaw.example.com {
    # WebSocket proxy
    @ws {
        header Connection *Upgrade*
        header Upgrade websocket
    }
    reverse_proxy @ws localhost:3000

    # WebChat UI
    reverse_proxy /chat/* localhost:8080

    # Automatic HTTPS
    tls {
        protocols tls1.3
    }

    # Rate limiting
    rate_limit {
        zone dynamic {
            key {remote_host}
            events 60
            window 1m
        }
    }
}
```

### Security Checklist

| Item                         | Status      | Description                              |
| ---------------------------- | ----------- | ---------------------------------------- |
| Gateway Token Authentication | Required    | Prevent unauthorized access              |
| HTTPS / WSS                  | Required    | Encrypt transmission                     |
| Non-root Execution           | Required    | Least privilege                          |
| Tool Command Whitelist       | Recommended | Restrict dangerous operations            |
| File Path Restriction        | Recommended | Limit to working directory               |
| Input Sanitization           | Recommended | Prevent prompt injection                 |
| Rate Limiting                | Recommended | Prevent abuse                            |
| Audit Logging                | Optional    | Log all tool invocations                 |
| Automatic Backup             | Optional    | Regularly backup session and memory data |

***

## Summary of This Section

1. **Docker containerization** uses multi-stage builds, runs as non-root user, and persists data via volumes.
2. **Daemon processes** support systemd (Linux) and launchd (macOS), with auto-restart and resource limit configuration.
3. **Security hardening** covers four layers: Gateway authentication, tool safety, input sanitization, and reverse proxy.
4. **Reverse proxy** recommends Caddy (automatic HTTPS) with WebSocket proxy and rate limiting configuration.
5. After deployment, check the security checklist item by item to ensure production environment security.

***

> ### 📐 Next: Part XI, "Source Reading and Design Insight"
>
> That completes the book's **implementation layer** (Ch. 11–42): you've taken OpenClaw apart once, and built a small one yourself.
>
> The last three chapters change the lens — put the magnifying glass down and step back:
>
> * [**Chapter 43: Engineering Panorama**](https://www.openclawbook.xyz/en/ch43-engineering-panorama/43.1-positioning-and-evolution.md) How half a million lines avoid falling apart; how much of 18,000 commits involved AI; four recommended source-reading paths.
> * [**Chapter 44: Seven Design Themes Running Through the Codebase**](https://www.openclawbook.xyz/en/ch44-design-themes/44.1-converged-surface-and-embed-not-fork.md) A design grammar extracted from the shapes that keep recurring — degradation chains, files as the source of truth, a trust model written as case law.
> * [**Chapter 45: Risks and Transferable Lessons**](https://www.openclawbook.xyz/en/ch45-risks-and-lessons/45.1-ten-patterns-worth-stealing.md) Ten patterns you can lift directly, an honest risk list (**every risk is the invoice for some advantage**), and a contrast with a different technical route.
>
> **Specific line numbers expire. Shapes don't.** If the first forty-two chapters taught you to read this one project, the last three aim to give you **something you can use the next time you design a system of your own.**
