如何安装(2/2)

Low temperature for factual extraction response = requests.post( "http://localhost:11235/md", json={ "url": "https://example.com", "f": "llm", "q": "Extract all dates and numbers from this page", "temperature": 0.2 # Very focused, deterministic } )

High temperature for creative tasks response = requests.post( "http://localhost:11235/md", json={ "url": "https://example.com", "f": "llm", "q": "Write a creative summary of this content", "temperature": 1.2 # More creative, varied responses } )


###### Custom API Endpoints

Use custom base URLs for proxy servers or alternative API endpoints:

```python

#
Using a local LLM server
response = requests.post(
    "http://localhost:11235/md",
    json={
        "url": "https://example.com",
        "f": "llm",
        "q": "Extract key information",
        "provider": "ollama/llama2",
        "base_url": "http://localhost:11434/v1"
    }
)
Dynamic Provider Selection

Switch between providers based on task requirements:

async def smart_extraction(url: str, content_type: str):
    """Select provider and temperature based on content type"""

    configs = {
        "technical": {
            "provider": "openai/gpt-4",
            "temperature": 0.3,
            "query": "Extract technical specifications and code examples"
        },
        "creative": {
            "provider": "anthropic/claude-3-opus",
            "temperature": 0.9,
            "query": "Create an engaging narrative summary"
        },
        "quick": {
            "provider": "groq/mixtral-8x7b",
            "temperature": 0.5,
            "query": "Quick summary in bullet points"
        }
    }

    config = configs.get(content_type, configs["quick"])

    response = await httpx.post(
        "http://localhost:11235/md",
        json={
            "url": url,
            "f": "llm",
            "q": config["query"],
            "provider": config["provider"],
            "temperature": config["temperature"]
        }
    )

    return response.json()
REST API Examples

Update URLs to use port 11235.

Simple Crawl
import requests

#
Configuration objects converted to the required JSON structure
browser_config_payload = {
    "type": "BrowserConfig",
    "params": {"headless": True}
}
crawler_config_payload = {
    "type": "CrawlerRunConfig",
    "params": {"stream": False, "cache_mode": "bypass"} # Use string value of enum
}

crawl_payload = {
    "urls": ["https://httpbin.org/html"],
    "browser_config": browser_config_payload,
    "crawler_config": crawler_config_payload
}
response = requests.post(
    "http://localhost:11235/crawl", # Updated port
    # headers={"Authorization": f"Bearer {token}"},  # If JWT is enabled
    json=crawl_payload
)
print(f"Status Code: {response.status_code}")
if response.ok:
    print(response.json())
else:
    print(f"Error: {response.text}")

Streaming Results
import json
import httpx # Use httpx for async streaming example

async def test_stream_crawl(token: str = None): # Made token optional
    """Test the /crawl/stream endpoint with multiple URLs."""
    url = "http://localhost:11235/crawl/stream" # Updated port
    payload = {
        "urls": [
            "https://httpbin.org/html",
            "https://httpbin.org/links/5/0",
        ],
        "browser_config": {
            "type": "BrowserConfig",
            "params": {"headless": True, "viewport": {"type": "dict", "value": {"width": 1200, "height": 800}}} # Viewport needs type:dict
        },
        "crawler_config": {
            "type": "CrawlerRunConfig",
            "params": {"stream": True, "cache_mode": "bypass"}
        }
    }

    headers = {}
    # if token:
    #    headers = {"Authorization": f"Bearer {token}"} # If JWT is enabled

    try:
        async with httpx.AsyncClient() as client:
            async with client.stream("POST", url, json=payload, headers=headers, timeout=120.0) as response:
                print(f"Status: {response.status_code} (Expected: 200)")
                response.raise_for_status() # Raise exception for bad status codes

                # Read streaming response line-by-line (NDJSON)
                async for line in response.aiter_lines():
                    if line:
                        try:
                            data = json.loads(line)
                            # Check for completion marker
                            if data.get("status") == "completed":
                                print("Stream completed.")
                                break
                            print(f"Streamed Result: {json.dumps(data, indent=2)}")
                        except json.JSONDecodeError:
                            print(f"Warning: Could not decode JSON line: {line}")

    except httpx.HTTPStatusError as e:
         print(f"HTTP error occurred: {e.response.status_code} - {e.response.text}")
    except Exception as e:
        print(f"Error in streaming crawl test: {str(e)}")

#
To run this example:
#
import asyncio
#
asyncio.run(test_stream_crawl())

Real-time Monitoring & Operations

One of the key advantages of self-hosting is complete visibility into your infrastructure. Crawl4AI includes a comprehensive real-time monitoring system that gives you full transparency and control.

Monitoring Dashboard

Access the built-in real-time monitoring dashboard for complete operational visibility:

http://localhost:11235/dashboard

⚠️ The dashboard UI lives at /dashboard. /monitor is the API namespace (/monitor/health, /monitor/ws, …); older docs pointed there, so that exact URL now redirects to /dashboard for convenience — the /monitor/* routes themselves still require a token. On the dashboard, paste your API token into the API token bar (top right) and click Set; the WebSocket then connects and live stats appear.

Monitoring Dashboard

Dashboard Features:

1. System Health Overview
  • CPU & Memory: Live usage with progress bars and percentage indicators
  • Network I/O: Total bytes sent/received since startup
  • Server Uptime: How long your server has been running
  • Browser Pool Status:
  • 🔥 Permanent browser (always-on default config, ~270MB)
  • ♨️ Hot pool (frequently used configs, ~180MB each)
  • ❄️ Cold pool (idle browsers awaiting cleanup, ~180MB each)
  • Memory Pressure: LOW/MEDIUM/HIGH indicator for janitor behavior
2. Live Request Tracking
  • Active Requests: Currently running crawls with:
  • Request ID for tracking
  • Target URL (truncated for display)
  • Endpoint being used
  • Elapsed time (updates in real-time)
  • Memory usage from start
  • Completed Requests: Last 10 finished requests showing:
  • Success/failure status (color-coded)
  • Total execution time
  • Memory delta (how much memory changed)
  • Pool hit (was browser reused?)
  • HTTP status code
  • Filtering: View all, success only, or errors only
3. Browser Pool Management

Interactive table showing all active browsers:

Type Signature Age Last Used Hits Actions
permanent abc12345 2h 5s ago 1,247 Restart
hot def67890 45m 2m ago 89 Kill / Restart
cold ghi11213 30m 15m ago 3 Kill / Restart
  • Reuse Rate: Percentage of requests that reused existing browsers
  • Memory Estimates: Total memory used by browser pool
  • Manual Control: Kill or restart individual browsers
4. Janitor Events Log

Real-time log of browser pool cleanup events: - When cold browsers are closed due to memory pressure - When browsers are promoted from cold to hot pool - Forced cleanups triggered manually - Detailed cleanup reasons and browser signatures

5. Error Monitoring

Recent errors with full context: - Timestamp - Endpoint where error occurred - Target URL - Error message - Request ID for correlation

Live Updates: The dashboard connects via WebSocket and refreshes every 2 seconds with the latest data. Connection status indicator shows when you're connected/disconnected.


Monitor API Endpoints

For programmatic monitoring, automation, and integration with your existing infrastructure:

Health & Statistics

Get System Health

GET /monitor/health

Returns current system snapshot:

{
  "container": {
    "memory_percent": 45.2,
    "cpu_percent": 23.1,
    "network_sent_mb": 1250.45,
    "network_recv_mb": 3421.12,
    "uptime_seconds": 7234
  },
  "pool": {
    "permanent": {"active": true, "memory_mb": 270},
    "hot": {"count": 3, "memory_mb": 540},
    "cold": {"count": 1, "memory_mb": 180},
    "total_memory_mb": 990
  },
  "janitor": {
    "next_cleanup_estimate": "adaptive",
    "memory_pressure": "MEDIUM"
  }
}

Get Request Statistics

GET /monitor/requests?status=all&limit=50

Query parameters: - status: Filter by all, active, completed, success, or error - limit: Number of completed requests to return (1-1000)

Get Browser Pool Details

GET /monitor/browsers

Returns detailed information about all active browsers:

{
  "browsers": [
    {
      "type": "permanent",
      "sig": "abc12345",
      "age_seconds": 7234,
      "last_used_seconds": 5,
      "memory_mb": 270,
      "hits": 1247,
      "killable": false
    },
    {
      "type": "hot",
      "sig": "def67890",
      "age_seconds": 2701,
      "last_used_seconds": 120,
      "memory_mb": 180,
      "hits": 89,
      "killable": true
    }
  ],
  "summary": {
    "total_count": 5,
    "total_memory_mb": 990,
    "reuse_rate_percent": 87.3
  }
}

Get Endpoint Performance Statistics

GET /monitor/endpoints/stats

Returns aggregated metrics per endpoint:

{
  "/crawl": {
    "count": 1523,
    "avg_latency_ms": 2341.5,
    "success_rate_percent": 98.2,
    "pool_hit_rate_percent": 89.1,
    "errors": 27
  },
  "/md": {
    "count": 891,
    "avg_latency_ms": 1823.7,
    "success_rate_percent": 99.4,
    "pool_hit_rate_percent": 92.3,
    "errors": 5
  }
}

Get Timeline Data

GET /monitor/timeline?metric=memory&window=5m

Parameters: - metric: memory, requests, or browsers - window: Currently only 5m (5-minute window, 5-second resolution)

Returns time-series data for charts:

{
  "timestamps": [1699564800, 1699564805, 1699564810, ...],
  "values": [42.1, 43.5, 41.8, ...]
}
Logs

Get Janitor Events

GET /monitor/logs/janitor?limit=100

Get Error Log

GET /monitor/logs/errors?limit=100

WebSocket Streaming

For real-time monitoring in your own dashboards or applications:

WS /monitor/ws

Connection Example (Python):

import asyncio
import websockets
import json

async def monitor_server():
    uri = "ws://localhost:11235/monitor/ws"

    async with websockets.connect(uri) as websocket:
        print("Connected to Crawl4AI monitor")

        while True:
            # Receive update every 2 seconds
            data = await websocket.recv()
            update = json.loads(data)

            # Extract key metrics
            health = update['health']
            active_requests = len(update['requests']['active'])
            browsers = len(update['browsers'])

            print(f"Memory: {health['container']['memory_percent']:.1f}% | "
                  f"Active: {active_requests} | "
                  f"Browsers: {browsers}")

            # Check for high memory pressure
            if health['janitor']['memory_pressure'] == 'HIGH':
                print("⚠️  HIGH MEMORY PRESSURE - Consider cleanup")

asyncio.run(monitor_server())

Update Payload Structure:

{
  "timestamp": 1699564823.456,
  "health": { /* System health snapshot */ },
  "requests": {
    "active": [ /* Currently running */ ],
    "completed": [ /* Last 10 completed */ ]
  },
  "browsers": [ /* All active browsers */ ],
  "timeline": {
    "memory": { /* Last 5 minutes */ },
    "requests": { /* Request rate */ },
    "browsers": { /* Pool composition */ }
  },
  "janitor": [ /* Last 10 cleanup events */ ],
  "errors": [ /* Last 10 errors */ ]
}

Control Actions

Take manual control when needed:

Force Immediate Cleanup

POST /monitor/actions/cleanup

Kills all cold pool browsers immediately (useful when memory is tight):

{
  "success": true,
  "killed_browsers": 3
}

Kill Specific Browser

POST /monitor/actions/kill_browser
Content-Type: application/json

{
  "sig": "abc12345"  // First 8 chars of browser signature
}

Response:

{
  "success": true,
  "killed_sig": "abc12345",
  "pool_type": "hot"
}

Restart Browser

POST /monitor/actions/restart_browser
Content-Type: application/json

{
  "sig": "permanent"  // Or first 8 chars of signature
}

For permanent browser, this will close and reinitialize it. For hot/cold browsers, it kills them and lets new requests create fresh ones.

Reset Statistics

POST /monitor/stats/reset

Clears endpoint counters (useful for starting fresh after testing).


Production Integration
Integration with Existing Monitoring Systems

Prometheus Integration:

#
Scrape metrics endpoint
curl http://localhost:11235/metrics

Custom Dashboard Integration:

#
Example: Push metrics to your monitoring system
import asyncio
import websockets
import json
from your_monitoring import push_metric

async def integrate_monitoring():
    async with websockets.connect("ws://localhost:11235/monitor/ws") as ws:
        while True:
            data = json.loads(await ws.recv())

            # Push to your monitoring system
            push_metric("crawl4ai.memory.percent",
                       data['health']['container']['memory_percent'])
            push_metric("crawl4ai.active_requests",
                       len(data['requests']['active']))
            push_metric("crawl4ai.browser_count",
                       len(data['browsers']))

Alerting Example:

import requests
import time

def check_health():
    """Poll health endpoint and alert on issues"""
    response = requests.get("http://localhost:11235/monitor/health")
    health = response.json()

    # Alert on high memory
    if health['container']['memory_percent'] > 85:
        send_alert(f"High memory: {health['container']['memory_percent']}%")

    # Alert on high error rate
    stats = requests.get("http://localhost:11235/monitor/endpoints/stats").json()
    for endpoint, metrics in stats.items():
        if metrics['success_rate_percent'] < 95:
            send_alert(f"{endpoint} success rate: {metrics['success_rate_percent']}%")

#
Run every minute
while True:
    check_health()
    time.sleep(60)

Log Aggregation:

import requests
from datetime import datetime

def aggregate_errors():
    """Fetch and aggregate errors for logging system"""
    response = requests.get("http://localhost:11235/monitor/logs/errors?limit=100")
    errors = response.json()['errors']

    for error in errors:
        log_to_system({
            'timestamp': datetime.fromtimestamp(error['timestamp']),
            'service': 'crawl4ai',
            'endpoint': error['endpoint'],
            'url': error['url'],
            'message': error['error'],
            'request_id': error['request_id']
        })
Key Metrics to Track

For production self-hosted deployments, monitor these metrics:

  1. Memory Usage Trends
  2. Track container.memory_percent over time
  3. Alert when consistently above 80%
  4. Prevents OOM kills

  5. Request Success Rates

  6. Monitor per-endpoint success rates
  7. Alert when below 95%
  8. Indicates crawling issues

  9. Average Latency

  10. Track avg_latency_ms per endpoint
  11. Detect performance degradation
  12. Optimize slow endpoints

  13. Browser Pool Efficiency

  14. Monitor reuse_rate_percent
  15. Should be >80% for good efficiency
  16. Low rates indicate pool churn

  17. Error Frequency

  18. Count errors per time window
  19. Alert on sudden spikes
  20. Track error patterns

  21. Janitor Activity

  22. Monitor cleanup frequency
  23. Excessive cleanup indicates memory pressure
  24. Adjust pool settings if needed

Quick Health Check

For simple uptime monitoring:

curl http://localhost:11235/health

Returns:

{
  "status": "healthy",
  "version": "0.9.2"
}

Other useful endpoints: - /metrics - Prometheus metrics - /schema - Full API schema


Server Configuration

The server's behavior can be customized through the config.yml file.

Understanding config.yml

The configuration file is loaded from /app/config.yml inside the container. By default, the file from deploy/docker/config.yml in the repository is copied there during the build.

Here's a detailed breakdown of the configuration options (using defaults from deploy/docker/config.yml):

#
Application Configuration
app:
  title: "Crawl4AI API"
  version: "1.0.0" # Consider setting this to match library version, e.g., "0.5.1"
  host: "0.0.0.0"
  port: 8020 # NOTE: This port is used ONLY when running server.py directly. Gunicorn overrides this (see supervisord.conf).
  reload: False # Default set to False - suitable for production
  timeout_keep_alive: 300

#
Default LLM Configuration
llm:
  provider: "openai/gpt-4o-mini"  # Can be overridden by LLM_PROVIDER env var
  # api_key: sk-...  # If you pass the API key directly (not recommended)
  # temperature and base_url are controlled via environment variables or request parameters

#
Redis Configuration (Used by internal Redis server managed by supervisord)
redis:
  host: "localhost"
  port: 6379
  db: 0
  password: ""
  # ... other redis options ...

#
Rate Limiting Configuration
rate_limiting:
  enabled: True
  default_limit: "1000/minute"
  trusted_proxies: []
  storage_uri: "memory://"  # Use "redis://localhost:6379" if you need persistent/shared limits

#
Security Configuration
#
NOTE (0.9.0): the defaults below reflect 0.8.x. In 0.9.0 the Docker server is
#
secure-by-default - authentication is required, the server binds loopback
#
unless a token is set, and request bodies are validated against a trust
#
boundary. See the migration guide for the 0.9.0 defaults and config keys:
#
https://github.com/unclecode/crawl4ai/blob/main/deploy/docker/MIGRATION.md
security:
  enabled: false # Master toggle for security features
  jwt_enabled: false # Enable JWT authentication (requires security.enabled=true)
  https_redirect: false # Force HTTPS (requires security.enabled=true)
  trusted_hosts: ["*"] # Allowed hosts (use specific domains in production)
  headers: # Security headers (applied if security.enabled=true)
    x_content_type_options: "nosniff"
    x_frame_options: "DENY"
    content_security_policy: "default-src 'self'"
    strict_transport_security: "max-age=63072000; includeSubDomains"

#
Crawler Configuration
crawler:
  memory_threshold_percent: 95.0
  rate_limiter:
    base_delay: [1.0, 2.0] # Min/max delay between requests in seconds for dispatcher
  timeouts:
    stream_init: 30.0  # Timeout for stream initialization
    batch_process: 300.0 # Timeout for non-streaming /crawl processing

#
Logging Configuration
logging:
  level: "INFO"
  format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"

#
Observability Configuration
observability:
  prometheus:
    enabled: True
    endpoint: "/metrics"
  health_check:
    endpoint: "/health"

(JWT Authentication section remains the same, just note the default port is now 11235 for requests)

(Configuration Tips and Best Practices remain the same)

Customizing Your Configuration

You can override the default config.yml.

Method 1: Modify Before Build
  1. Edit the deploy/docker/config.yml file in your local repository clone.
  2. Build the image using docker buildx or docker compose --profile local-... up --build. The modified file will be copied into the image.
  1. Create your custom configuration file, e.g., my-custom-config.yml locally. Ensure it contains all necessary sections.
  2. Mount it when running the container:

    • Using docker run:
# Assumes my-custom-config.yml is in the current directory
docker run -d -p 11235:11235 \
  --name crawl4ai-custom-config \
  --env-file .llm.env \
  --shm-size=1g \
  -v $(pwd)/my-custom-config.yml:/app/config.yml \
  unclecode/crawl4ai:latest # Or your specific tag
*   **Using `docker-compose.yml`:** Add a `volumes` section to the service definition:
services:
  crawl4ai-hub-amd64: # Or your chosen service
    image: unclecode/crawl4ai:latest
    profiles: ["hub-amd64"]
    <<: *base-config
    volumes:
      # Mount local custom config over the default one in the container
      - ./my-custom-config.yml:/app/config.yml
      # Keep the shared memory volume from base-config
      - /dev/shm:/dev/shm
    *(Note: Ensure `my-custom-config.yml` is in the same directory as `docker-compose.yml`)*

💡 When mounting, your custom file completely replaces the default one. Ensure it's a valid and complete configuration.

Configuration Recommendations
  1. Security First 🔒
  2. Always enable security in production
  3. Use specific trusted_hosts instead of wildcards
  4. Set up proper rate limiting to protect your server
  5. Consider your environment before enabling HTTPS redirect

  6. Resource Management 💻

  7. Adjust memory_threshold_percent based on available RAM
  8. Set timeouts according to your content size and network conditions
  9. Use Redis for rate limiting in multi-container setups

  10. Monitoring 📊

  11. Enable Prometheus if you need metrics
  12. Set DEBUG logging in development, INFO in production
  13. Regular health check monitoring is crucial

  14. Performance Tuning ⚡

  15. Start with conservative rate limiter delays
  16. Increase batch_process timeout for large content
  17. Adjust stream_init timeout based on initial response times

Getting Help

We're here to help you succeed with Crawl4AI! Here's how to get support:

Summary

Congratulations! You now have everything you need to self-host your own Crawl4AI infrastructure with complete control and visibility.

What You've Learned: - ✅ Multiple deployment options (Docker Hub, Docker Compose, manual builds) - ✅ Environment configuration and LLM integration - ✅ Using the interactive playground for testing - ✅ Making API requests with proper typing (SDK and REST) - ✅ Specialized endpoints (screenshots, PDFs, JavaScript execution) - ✅ MCP integration for AI-assisted development - ✅ Real-time monitoring dashboard for operational transparency - ✅ Monitor API for programmatic control and integration - ✅ Production deployment best practices

Why This Matters:

By self-hosting Crawl4AI, you: - 🔒 Own Your Data: Everything stays in your infrastructure - 📊 See Everything: Real-time dashboard shows exactly what's happening - 💰 Control Costs: Scale within your resources, no per-request fees - ⚡ Maximize Performance: Direct access with smart browser pooling (10x memory efficiency) - 🛡️ Stay Secure: Keep sensitive workflows behind your firewall - 🔧 Customize Freely: Full control over configs, strategies, and optimizations

Next Steps:

  1. Start Simple: Deploy with Docker Hub image and test with the playground
  2. Monitor Everything: Open http://localhost:11235/dashboard to watch your server
  3. Integrate: Connect your applications using the Python SDK or REST API
  4. Scale Smart: Use the monitoring data to optimize your deployment
  5. Go Production: Set up alerting, log aggregation, and automated cleanup

Key Resources: - 🎮 Playground: http://localhost:11235/playground - Interactive testing - 📊 Monitor Dashboard: http://localhost:11235/dashboard - Real-time visibility - 📖 Architecture Docs: deploy/docker/ARCHITECTURE.md - Deep technical dive - 💬 Discord Community: Get help and share experiences - ⭐ GitHub: Report issues, contribute, show support

Remember: The monitoring dashboard is your window into your infrastructure. Use it to understand performance, troubleshoot issues, and optimize your deployment. The examples in the examples folder show real-world usage patterns you can adapt.

You're now in control of your web crawling destiny! 🚀

Happy crawling! 🕷️


Crawl4AI is available as Docker images for easy deployment. You can either pull directly from Docker Hub (recommended) or build from the repository.


🐳 Option 1: Docker Hub (Recommended) Choose the appropriate image based on your platform and needs: ##### For AMD64 (Regular Linux/Windows):
# Basic version (recommended)
docker pull unclecode/crawl4ai:basic-amd64
docker run -p 11235:11235 unclecode/crawl4ai:basic-amd64

# Full ML/LLM support
docker pull unclecode/crawl4ai:all-amd64
docker run -p 11235:11235 unclecode/crawl4ai:all-amd64

# With GPU support
docker pull unclecode/crawl4ai:gpu-amd64
docker run -p 11235:11235 unclecode/crawl4ai:gpu-amd64
##### For ARM64 (M1/M2 Macs, ARM servers):
# Basic version (recommended)
docker pull unclecode/crawl4ai:basic-arm64
docker run -p 11235:11235 unclecode/crawl4ai:basic-arm64

# Full ML/LLM support
docker pull unclecode/crawl4ai:all-arm64
docker run -p 11235:11235 unclecode/crawl4ai:all-arm64

# With GPU support
docker pull unclecode/crawl4ai:gpu-arm64
docker run -p 11235:11235 unclecode/crawl4ai:gpu-arm64
Need more memory? Add `--shm-size`:
docker run --shm-size=2gb -p 11235:11235 unclecode/crawl4ai:basic-amd64
Test the installation:
curl http://localhost:11235/health
##### For Raspberry Pi (32-bit) (coming soon):
# Pull and run basic version (recommended for Raspberry Pi)
docker pull unclecode/crawl4ai:basic-armv7
docker run -p 11235:11235 unclecode/crawl4ai:basic-armv7

# With increased shared memory if needed
docker run --shm-size=2gb -p 11235:11235 unclecode/crawl4ai:basic-armv7
Note: Due to hardware constraints, only the basic version is recommended for Raspberry Pi.
🐳 Option 2: Build from Repository Build the image locally based on your platform:
# Clone the repository
git clone https://github.com/unclecode/crawl4ai.git
cd crawl4ai

# For AMD64 (Regular Linux/Windows)
docker build --platform linux/amd64 \
  --tag crawl4ai:local \
  --build-arg INSTALL_TYPE=basic \
  .

# For ARM64 (M1/M2 Macs, ARM servers)
docker build --platform linux/arm64 \
  --tag crawl4ai:local \
  --build-arg INSTALL_TYPE=basic \
  .
Build options: - INSTALL_TYPE=basic (default): Basic crawling features - INSTALL_TYPE=all: Full ML/LLM support - ENABLE_GPU=true: Add GPU support Example with all options:
docker build --platform linux/amd64 \
  --tag crawl4ai:local \
  --build-arg INSTALL_TYPE=all \
  --build-arg ENABLE_GPU=true \
  .
Run your local build:
# Regular run
docker run -p 11235:11235 crawl4ai:local

# With increased shared memory
docker run --shm-size=2gb -p 11235:11235 crawl4ai:local
Test the installation:
curl http://localhost:11235/health
🐳 Option 3: Using Docker Compose Docker Compose provides a more structured way to run Crawl4AI, especially when dealing with environment variables and multiple configurations.
# Clone the repository
git clone https://github.com/unclecode/crawl4ai.git
cd crawl4ai
##### For AMD64 (Regular Linux/Windows):
# Build and run locally
docker-compose --profile local-amd64 up

# Run from Docker Hub
VERSION=basic docker-compose --profile hub-amd64 up   # Basic version
VERSION=all docker-compose --profile hub-amd64 up     # Full ML/LLM support
VERSION=gpu docker-compose --profile hub-amd64 up     # GPU support
##### For ARM64 (M1/M2 Macs, ARM servers):
# Build and run locally
docker-compose --profile local-arm64 up

# Run from Docker Hub
VERSION=basic docker-compose --profile hub-arm64 up   # Basic version
VERSION=all docker-compose --profile hub-arm64 up     # Full ML/LLM support
VERSION=gpu docker-compose --profile hub-arm64 up     # GPU support
Environment variables (optional):
# Create a .env file
CRAWL4AI_API_TOKEN=your_token
OPENAI_API_KEY=your_openai_key
CLAUDE_API_KEY=your_claude_key
The compose file includes: - Memory management (4GB limit, 1GB reserved) - Shared memory volume for browser support - Health checks - Auto-restart policy - All necessary port mappings Test the installation:
curl http://localhost:11235/health
🚀 One-Click Deployment Deploy your own instance of Crawl4AI with one click: [![DigitalOcean Referral Badge](https://web-platforms.sfo2.cdn.digitaloceanspaces.com/WWW/Badge%203.svg)](https://www.digitalocean.com/?repo=https://github.com/unclecode/crawl4ai/tree/0.3.74&refcode=a0780f1bdb3d&utm_campaign=Referral_Invite&utm_medium=Referral_Program&utm_source=badge) > 💡 **Recommended specs**: 4GB RAM minimum. Select "professional-xs" or higher when deploying for stable operation. The deploy will: - Set up a Docker container with Crawl4AI - Configure Playwright and all dependencies - Start the FastAPI server on port `11235` - Set up health checks and auto-deployment

1. Basic Installation

pip install crawl4ai

This installs the core Crawl4AI library along with essential dependencies. No advanced features (like transformers or PyTorch) are included yet.

2. Initial Setup & Diagnostics

2.1 Run the Setup Command

After installing, call:

crawl4ai-setup

What does it do? - Installs or updates required browser dependencies for both regular and undetected modes - Performs OS-level checks (e.g., missing libs on Linux) - Confirms your environment is ready to crawl

2.2 Diagnostics

Optionally, you can run diagnostics to confirm everything is functioning:

crawl4ai-doctor

This command attempts to: - Check Python version compatibility - Verify Playwright installation - Inspect environment variables or library conflicts

If any issues arise, follow its suggestions (e.g., installing additional system packages) and re-run crawl4ai-setup.


3. Verifying Installation: A Simple Crawl (Skip this step if you already run crawl4ai-doctor)

Below is a minimal Python script demonstrating a basic crawl. It uses our new BrowserConfig and CrawlerRunConfig for clarity, though no custom settings are passed in this example:

import asyncio
from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig

async def main():
    async with AsyncWebCrawler() as crawler:
        result = await crawler.arun(
            url="https://www.example.com",
        )
        print(result.markdown[:300])  # Show the first 300 characters of extracted text

if __name__ == "__main__":
    asyncio.run(main())

Expected outcome: - A headless browser session loads example.com - Crawl4AI returns ~300 characters of markdown. If errors occur, rerun crawl4ai-doctor or manually ensure Playwright is installed correctly.


4. Advanced Installation (Optional)

Warning: Only install these if you truly need them. They bring in larger dependencies, including big models, which can increase disk usage and memory load significantly.

4.1 Torch, Transformers, or All
  • Text Clustering (Torch)
pip install crawl4ai[torch]
crawl4ai-setup

Installs PyTorch-based features (e.g., cosine similarity or advanced semantic chunking).

  • Transformers
pip install crawl4ai[transformer]
crawl4ai-setup

Adds Hugging Face-based summarization or generation strategies.

  • All Features
pip install crawl4ai[all]
crawl4ai-setup
(Optional) Pre-Fetching Models
crawl4ai-download-models

This step caches large models locally (if needed). Only do this if your workflow requires them.


5. Docker (Experimental)

We provide a temporary Docker approach for testing. It’s not stable and may break with future releases. We plan a major Docker revamp in a future stable version, 2025 Q1. If you still want to try:

docker pull unclecode/crawl4ai:basic
docker run -p 11235:11235 unclecode/crawl4ai:basic

You can then make POST requests to http://localhost:11235/crawl to perform crawls. Production usage is discouraged until our new Docker approach is ready (planned in Jan or Feb 2025).


6. Local Server Mode (Legacy)

Some older docs mention running Crawl4AI as a local server. This approach has been partially replaced by the new Docker-based prototype and upcoming stable server release. You can experiment, but expect major changes. Official local server instructions will arrive once the new Docker architecture is finalized.


Summary

1. Install with pip install crawl4ai and run crawl4ai-setup. 2. Diagnose with crawl4ai-doctor if you see errors. 3. Verify by crawling example.com with minimal BrowserConfig + CrawlerRunConfig. 4. Advanced features (Torch, Transformers) are optional—avoid them if you don’t need them (they significantly increase resource usage). 5. Docker is experimental—use at your own risk until the stable version is released. 6. Local server references in older docs are largely deprecated; a new solution is in progress.

Got questions? Check GitHub issues for updates or ask the community!

Version numbering

Crawl4AI follows PEP 440: MAJOR.MINOR.PATCH, for example 0.9.4. A pre-release carries a suffix: dev (unstable), a (alpha), b (beta), rc (release candidate).

  • The stable version: pip install -U crawl4ai
  • The latest pre-release: pip install crawl4ai --pre
  • One exact version: pip install crawl4ai==0.9.4

Use the stable version in production. Pre-releases exist to test new features with real users before the final release.