# OpenClaw Guide Ch.2: Environment Setup and Installation

# Chapter 2: Environment Setup and Installation

> 🎯 Learning Objective: Complete the installation and configuration of OpenClaw, and successfully start your first Agent

## 🔍 **Pre-Installation Checklist**

Before you begin, ensure your environment meets the following requirements:

### **📋 Hardware Requirements**

| Deployment Mode | CPU | Memory | Disk | Network |
|-----------------|-----|--------|------|---------|
| Development/Learning | 2 cores | 4 GB | 20 GB | Stable internet |
| Small-Scale Production | 4 cores | 8 GB | 50 GB | 10 Mbps+ |
| Enterprise | 8+ cores | 16+ GB | 100+ GB | 100 Mbps+ |

### **💻 Supported Operating Systems**

✅ **Ubuntu 22.04 LTS** (Recommended)
✅ **Debian 11+**
✅ **CentOS 8+**
✅ **macOS 12+**
✅ **Windows 11** (WSL2)

### **🛠️ Required Software**

- **Node.js 18+** (Required)
- **npm 8+** (Required)
- **Git 2.0+** (Required)
- **Docker 20+** (Optional, for containerized deployment)
- **SSL Certificate** (Optional, for HTTPS)

---

## 🚀 **Installation Methods Compared**

| Method | Use Case | Pros | Cons | Time |
|--------|----------|------|------|------|
| **One-Click Script** | Beginners | Fully automated | Less customizable | 5–10 min |
| **Manual Install** | Production | Full control | More steps | 20–30 min |
| **Docker** | Containerized environments | Isolated environments | Requires Docker knowledge | 10–15 min |
| **Cluster** | Enterprise | High availability | High complexity | 1–2 hours |

---

## 🎯 **Method 1: One-Click Install Script** ⭐ Recommended for Beginners

### **Download and Run the Script**
```bash
# Download the install script
curl -sSL https://raw.githubusercontent.com/openclaw/openclaw/main/scripts/install.sh -o install-openclaw.sh

# Review the script contents (recommended)
cat install-openclaw.sh

# Run the install script
chmod +x install-openclaw.sh
./install-openclaw.sh
```

### **Script Features**
✅ Auto-detects operating system
✅ Installs Node.js and dependencies
✅ Downloads OpenClaw CLI
✅ Creates workspace directory structure
✅ Generates initial configuration files
✅ Sets up environment variables

### **Installation Preview**
```
🔍 Detecting OS: ubuntu
✅ Node.js version meets requirements: v20.10.0
📦 Installing OpenClaw CLI...
📁 Creating workspace: ~/.openclaw/workspace-main
⚙️  Generating config file: openclaw.json
🎉 Installation complete!
```

---

## 🛠️ **Method 2: Manual Step-by-Step Installation**

### **Step 1: Install Node.js**

#### **Ubuntu/Debian**
```bash
# Add the NodeSource repository
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -

# Install Node.js
sudo apt-get install -y nodejs

# Verify installation
node --version  # Should show v20.x.x
npm --version   # Should show 9.x.x
```

#### **CentOS/RHEL**
```bash
# Add the NodeSource repository
curl -fsSL https://rpm.nodesource.com/setup_20.x | sudo bash -

# Install Node.js
sudo yum install -y nodejs

# Verify installation
node --version
npm --version
```

#### **macOS**
```bash
# Using Homebrew
brew install node

# Or download the official installer
# https://nodejs.org/en/download/
```

### **Step 2: Install OpenClaw CLI**
```bash
# Install OpenClaw globally
sudo npm install -g openclaw

# Verify installation
openclaw --version
openclaw help
```

### **Step 3: Create the Workspace**
```bash
# Create the OpenClaw home directory
mkdir -p ~/.openclaw/workspace-main
cd ~/.openclaw/workspace-main

# Initialize a git repository
git init
git config --local user.name "Your Name"
git config --local user.email "your.email@example.com"

# Create the directory structure
mkdir -p {memory,skills,projects,logs}
```

### **Step 4: Initialize Configuration**
```bash
# Interactive configuration wizard
openclaw onboard

# Or manual setup
openclaw setup

# Or manually create openclaw.json
cat > openclaw.json << 'EOF'
{
  "gateway": {
    "port": 18789,
    "bind": "loopback"
  },
  "agents": [
    {
      "id": "main",
      "name": "Main Assistant",
      "model": "anthropic/claude-sonnet-4-20250514",
      "workspace": {
        "root": "."
      }
    }
  ],
  "auth": {
    "profiles": [
      {
        "id": "anthropic",
        "provider": "anthropic"
      }
    ]
  }
}
EOF
```

---

## 🐳 **Method 3: Docker Deployment**

### **Create a Dockerfile**
```dockerfile
# Based on the official Node.js image
FROM node:20-slim

# Set working directory
WORKDIR /app

# Install system dependencies
RUN apt-get update && apt-get install -y \
    git \
    curl \
    && rm -rf /var/lib/apt/lists/*

# Install OpenClaw
RUN npm install -g openclaw

# Create workspace
RUN mkdir -p /app/workspace
WORKDIR /app/workspace

# Copy configuration files
COPY openclaw.json .
COPY auth-profiles.json .

# Expose port
EXPOSE 18789

# Startup command
CMD ["openclaw", "gateway", "start", "--port", "18789"]
```

### **Docker Compose Deployment**
```yaml
version: '3.8'

services:
  openclaw-gateway:
    build: .
    ports:
      - "18789:18789"
    volumes:
      - ./workspace:/app/workspace
      - ./logs:/app/logs
    environment:
      - NODE_ENV=production
    restart: unless-stopped

  openclaw-agent-1:
    build: .
    ports:
      - "18790:18789"
    volumes:
      - ./agents/agent-1:/app/workspace
    environment:
      - AGENT_ID=agent-1
      - NODE_ENV=production
    restart: unless-stopped
```

---

## 🔧 **API Key Configuration**

After installation, configure the API keys for your AI models:

### **Configure Anthropic Claude**
```bash
# Interactive configuration
openclaw auth add anthropic

# Or set environment variables directly
export ANTHROPIC_API_KEY="sk-ant-api03-..."

# Verify configuration
openclaw auth list
```

### **Configure OpenAI GPT**
```bash
# Add OpenAI authentication
openclaw auth add openai

# Set the API key
export OPENAI_API_KEY="sk-..."

# Test the connection
openclaw test openai
```

### **Other Model Configurations**
```bash
# Google Gemini
export GOOGLE_API_KEY="..."
openclaw auth add google

# Azure OpenAI
export AZURE_OPENAI_API_KEY="..."
export AZURE_OPENAI_ENDPOINT="https://..."
openclaw auth add azure-openai
```

---

## 🎮 **First Launch and Testing**

### **Start the Gateway**
```bash
# Navigate to the workspace
cd ~/.openclaw/workspace-main

# Start the Gateway (foreground)
openclaw gateway start

# Or run in the background
openclaw gateway start --daemon

# Check status
openclaw status
```

### **Test Basic Functionality**
```bash
# In another terminal, test the API
curl -X POST http://localhost:18789/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "main",
    "messages": [
      {"role": "user", "content": "Hello, OpenClaw!"}
    ]
  }'
```

### **Expected Response**
```json
{
  "id": "chatcmpl-...",
  "object": "chat.completion",
  "model": "main",
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "Hello! I'm the OpenClaw AI assistant. Happy to help!"
      }
    }
  ]
}
```

---

## ❗ **Common Issues and Solutions**

### **Issue 1: Node.js Version Too Old**
```bash
# Error message
Error: OpenClaw requires Node.js 18 or higher

# Solution
# Remove the old version
sudo apt remove nodejs npm

# Reinstall the latest version
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs
```

### **Issue 2: Permission Error**
```bash
# Error message
EACCES: permission denied, mkdir '/usr/local/lib/node_modules/@openclaw'

# Solution: Configure npm global directory
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
npm install -g @openclaw/openclaw
```

### **Issue 3: Port Already in Use**
```bash
# Error message
Error: listen EADDRINUSE :::18789

# Solution: Find the process using the port
sudo netstat -tlnp | grep 18789
sudo kill -9 <PID>

# Or use a different port
openclaw gateway start --port 18790
```

### **Issue 4: Invalid API Key**
```bash
# Error message
AuthenticationError: Invalid API key

# Solution: Reconfigure the key
openclaw auth remove anthropic
openclaw auth add anthropic
# Enter the correct API key

# Verify configuration
openclaw auth test anthropic
```

### **Issue 5: Network Connectivity Issues**
```bash
# Error message
fetch failed

# Solution: Check network and firewall
# Test connectivity
curl -I https://api.anthropic.com
curl -I https://api.openai.com

# Configure proxy (if needed)
export HTTPS_PROXY=http://proxy.company.com:8080
export HTTP_PROXY=http://proxy.company.com:8080
```

---

## ✅ **Post-Installation Verification Checklist**

After installation, verify each item:

- [ ] **Node.js version**: `node --version` >= v18.0.0
- [ ] **OpenClaw CLI**: `openclaw --version` shows version info
- [ ] **Workspace**: `~/.openclaw/workspace-main` exists
- [ ] **Configuration**: `openclaw.json` is valid
- [ ] **API keys**: `openclaw auth list` shows configured providers
- [ ] **Gateway starts**: `openclaw gateway start` runs without errors
- [ ] **API test**: HTTP request returns a normal response
- [ ] **Logging**: `logs/gateway.log` contains normal log entries

---

## 📊 **Performance Optimization Tips**

### **System-Level Optimization**
```bash
# Increase file descriptor limits
echo "* soft nofile 65536" | sudo tee -a /etc/security/limits.conf
echo "* hard nofile 65536" | sudo tee -a /etc/security/limits.conf

# Optimize Node.js memory
export NODE_OPTIONS="--max-old-space-size=4096"

# Enable high-performance mode
echo performance | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
```

### **OpenClaw Configuration Optimization**
```json
{
  "gateway": {
    "maxConcurrency": 10,
    "timeout": 30000,
    "keepAlive": true
  },
  "agents": [
    {
      "id": "main",
      "maxConcurrency": 3,
      "contextPruning": {
        "enabled": true,
        "maxTokens": 100000
      }
    }
  ]
}
```

---

## 🚀 **Next Steps**

Congratulations! OpenClaw has been successfully installed. Now you can:

**[Next Chapter: Your First Agent →](../chapter3/README.md)**

---

## 📝 **Chapter Summary**

After this chapter, you should have:

- [x] Completed OpenClaw installation and basic configuration
- [x] Mastered both one-click and manual installation methods
- [x] Configured AI model API keys
- [x] Successfully started the OpenClaw Gateway
- [x] Learned solutions for common issues
- [x] Understood performance optimization techniques

**Ready to create your first Agent?** 🎯

---

📌 **This article is written by the AI team at [TechsFree](https://techsfree.com)**

🔗 Read more → Check out [TechsFree Tech Blog](https://techsfree.com/blog) for more articles on AI, multi-agent systems, and automation!

🌐 [Website](https://techsfree.com) | 📖 [Tech Blog](https://techsfree.com/blog) | 💼 [Our Services](https://techsfree.com/services)

