Crawl4AI Docker 指南🐳
目录
- 先决条件
- 安装
- 选项 1:使用预构建的 Docker Hub 镜像(推荐)
- 选项 2:使用 Docker Compose
- 选项 3:手动本地构建并运行
- Dockerfile 参数
- 使用 API
- 游乐场界面
- Python SDK
- 理解请求模式
- REST API 示例
- 附加 API 端点
- HTML提取端点
- 屏幕截图端点
- PDF 导出端点
- JavaScript 执行端点
- 库上下文端点
- MCP(模型上下文协议)支持
- 什么是 MCP?
- 通过 MCP 连接
- 与 Claude 代码一起使用
- 可用的 MCP 工具
- 测试 MCP 连接
- MCP 模式
- 指标与监控
- 部署场景
- 完整示例
- 服务器配置
- 理解 config.yml
- JWT 身份验证
- 配置技巧和最佳实践
- 自定义配置
- 配置建议
- 获取帮助
- 概括
先决条件
在深入研究之前,请确保您已安装并运行 Docker(版本 20.10.0 或更高版本),包括docker compose
(通常与 Docker Desktop 捆绑在一起)。 -git
用于克隆存储库。 - 容器至少有 4GB 的可用 RAM(建议在大量使用时使用更多)。 - Python 3.10+(如果使用 Python SDK)。 - Node.js 16+(如果使用 Node.js 示例)。
💡 专业提示:跑步docker info
检查您的 Docker 安装和可用资源。
安装
我们提供多种方式来运行 Crawl4AI 服务器。最快捷的方法是使用我们预先构建的 Docker Hub 镜像。
选项 1:使用预构建的 Docker Hub 镜像(推荐)
直接从 Docker Hub 拉取并运行镜像,无需在本地构建。
1. 拉取镜像
我们最新的候选版本是0.7.0-r1
。图像是使用多架构清单构建的,因此 Docker 会自动为您的系统提取正确的版本。
⚠️ 重要提示:latest
标签目前指向稳定0.6.0
版本。经过测试和验证,0.7.0
(不带 -r1)将被释放,并且latest
将会更新。目前,请使用0.7.0-r1
测试新功能。
# Pull the release candidate (for testing new features)
docker pull unclecode/crawl4ai:0.7.0-r1
# Or pull the current stable version (0.6.0)
docker pull unclecode/crawl4ai:latest
2. 设置环境(API 密钥)
如果你打算使用 LLM,请创建一个.llm.env
工作目录中的文件:
# Create a .llm.env file with your API keys
cat > .llm.env << EOL
# OpenAI
OPENAI_API_KEY=sk-your-key
# Anthropic
ANTHROPIC_API_KEY=your-anthropic-key
# Other providers as needed
# DEEPSEEK_API_KEY=your-deepseek-key
# GROQ_API_KEY=your-groq-key
# TOGETHER_API_KEY=your-together-key
# MISTRAL_API_KEY=your-mistral-key
# GEMINI_API_TOKEN=your-gemini-token
EOL
🔑 注意:请妥善保管您的 API 密钥!切勿提交.llm.env
进行版本控制。
3. 运行容器
- 基本运行:
docker run -d \ -p 11235:11235 \ --name crawl4ai \ --shm-size=1g \ unclecode/crawl4ai:latest
- 在法学硕士 (LLM) 的支持下:
# Make sure .llm.env is in the current directory docker run -d \ -p 11235:11235 \ --name crawl4ai \ --env-file .llm.env \ --shm-size=1g \ unclecode/crawl4ai:latest
服务器将在http://localhost:11235
。 访问/playground
进入交互式测试界面。
4.停止容器
Docker Hub 版本控制说明
- 图片名称:
unclecode/crawl4ai
- 标签格式:
LIBRARY_VERSION[-SUFFIX]
(例如,0.7.0-r1
)LIBRARY_VERSION
:核心的语义版本crawl4ai
Python 库SUFFIX
: 候选发布版本的可选标签 (`) and revisions (
r1`) - 标签:指向最新的稳定版本
- 多架构支持:所有图像均支持
linux/amd64
和linux/arm64
通过单个标签的架构
选项 2:使用 Docker Compose
Docker Compose 简化了服务的构建和运行,特别是对于本地开发和测试。
1. 克隆存储库
2. 环境设置(API 密钥)
如果您计划使用 LLM,请复制示例环境文件并添加您的 API 密钥。此文件应位于项目根目录中。
# Make sure you are in the 'crawl4ai' root directory
cp deploy/docker/.llm.env.example .llm.env
# Now edit .llm.env and add your API keys
3. 使用 Compose 构建并运行
这docker-compose.yml
项目根目录中的文件提供了一种简化的方法,可以使用 buildx 自动处理架构检测。
- 从 Docker Hub 运行预构建的映像:
# Pulls and runs the release candidate from Docker Hub # Automatically selects the correct architecture IMAGE=unclecode/crawl4ai:latest docker compose up -d
- 本地构建并运行:
# Builds the image locally using Dockerfile and runs it # Automatically uses the correct architecture for your machine docker compose up --build -d
- 自定义构建:
# Build with all features (includes torch and transformers) INSTALL_TYPE=all docker compose up --build -d # Build with GPU support (for AMD64 platforms) ENABLE_GPU=true docker compose up --build -d
服务器将在http://localhost:11235
。
4.停止服务
选项 3:手动本地构建并运行
如果您不想使用 Docker Compose 直接控制构建和运行过程。
1. 克隆存储库并设置环境
按照上面 Docker Compose 部分的步骤 1 和 2 进行操作(克隆 repo,cd crawl4ai
, 创造.llm.env
在根目录下)。
2. 构建镜像(多架构)
使用docker buildx
构建镜像。Crawl4AI 现在使用 buildx 自动处理多架构构建。
# Make sure you are in the 'crawl4ai' root directory
# Build for the current architecture and load it into Docker
docker buildx build -t crawl4ai-local:latest --load .
# Or build for multiple architectures (useful for publishing)
docker buildx build --platform linux/amd64,linux/arm64 -t crawl4ai-local:latest --load .
# Build with additional options
docker buildx build \
--build-arg INSTALL_TYPE=all \
--build-arg ENABLE_GPU=false \
-t crawl4ai-local:latest --load .
3. 运行容器
- 基本运行(无 LLM 支持):
docker run -d \ -p 11235:11235 \ --name crawl4ai-standalone \ --shm-size=1g \ crawl4ai-local:latest
- 在法学硕士 (LLM) 的支持下:
# Make sure .llm.env is in the current directory (project root) docker run -d \ -p 11235:11235 \ --name crawl4ai-standalone \ --env-file .llm.env \ --shm-size=1g \ crawl4ai-local:latest
服务器将在http://localhost:11235
。
4.停止手动容器
MCP(模型上下文协议)支持
Crawl4AI 服务器包括对模型上下文协议 (MCP) 的支持,允许您将服务器的功能直接连接到与 MCP 兼容的客户端,如 Claude Code。
什么是 MCP?
MCP 是一个开放协议,它标准化了应用程序向 LLM 提供上下文的方式。它允许 AI 模型通过标准化接口访问外部工具、数据源和服务。
通过 MCP 连接
Crawl4AI 服务器公开两个 MCP 端点:
- 服务器发送事件 (SSE):
http://localhost:11235/mcp/sse
- WebSocket:
ws://localhost:11235/mcp/ws
与 Claude 代码一起使用
您可以使用一个简单的命令在 Claude Code 中添加 Crawl4AI 作为 MCP 工具提供程序:
# Add the Crawl4AI server as an MCP provider
claude mcp add --transport sse c4ai-sse http://localhost:11235/mcp/sse
# List all MCP providers to verify it was added
claude mcp list
一旦连接,Claude Code 可以直接使用 Crawl4AI 的功能,如屏幕截图、PDF 生成和 HTML 处理,而无需进行单独的 API 调用。
可用的 MCP 工具
通过 MCP 连接时,可以使用以下工具:
- - 从网页内容生成 markdown
- - 提取预处理的 HTML
- - 捕获网页截图
- - 生成PDF文档
- - 在网页上运行 JavaScript
- - 执行多 URL 抓取
- - 查询 Crawl4AI 库上下文
测试 MCP 连接
您可以使用存储库中包含的测试文件测试 MCP WebSocket 连接:
MCP 模式
访问 MCP 工具架构http://localhost:11235/mcp/schema
有关每个工具的参数和功能的详细信息。
附加 API 端点
除了核心/crawl
和/crawl/stream
端点,服务器提供了几个专门的端点:
HTML提取端点
抓取 URL 并返回针对模式提取优化的预处理 HTML。
屏幕截图端点
捕获指定 URL 的整页 PNG 屏幕截图。
{
"url": "https://example.com",
"screenshot_wait_for": 2,
"output_path": "/path/to/save/screenshot.png"
}
- :捕获前的可选延迟秒数(默认值:2)
- :可选保存截图的路径(推荐)
PDF 导出端点
生成指定 URL 的 PDF 文档。
- :保存 PDF 的可选路径(推荐)
JavaScript 执行端点
在指定的 URL 上执行 JavaScript 片段并返回完整的爬取结果。
{
"url": "https://example.com",
"scripts": [
"return document.title",
"return Array.from(document.querySelectorAll('a')).map(a => a.href)"
]
}
- :按顺序执行的 JavaScript 代码片段列表
Dockerfile 参数
您可以使用构建参数自定义图像构建过程(--build-arg
)通常通过docker buildx build
或在docker-compose.yml
文件。
# Example: Build with 'all' features using buildx
docker buildx build \
--platform linux/amd64,linux/arm64 \
--build-arg INSTALL_TYPE=all \
-t yourname/crawl4ai-all:latest \
--load \
. # Build from root context
构建参数解释
争论 | 描述 | 默认 | 选项 |
---|---|---|---|
安装类型 | 功能集 | default |
,all ,torch ,transformer |
启用 GPU | GPU 支持(适用于 AMD64 的 CUDA) | false |
,false |
应用程序主页 | 容器内的安装路径(高级) | /app |
任何有效路径 |
使用本地 | 从本地源安装库 | true |
,false |
GITHUB_REPO | 如果 USE_LOCAL=false,则克隆 Git 仓库 | (参见 Dockerfile) | 任何 git URL |
GITHUB_BRANCH | 如果 USE_LOCAL=false,则克隆 Git 分支 | main |
任何分支名称 |
(注意:PYTHON_VERSION 由FROM
Dockerfile 中的指令)
建立最佳实践
- 选择正确的安装类型
default
:基本安装,最小图像尺寸。适用于大多数标准网页抓取和 Markdown 生成。all
:全部功能包括torch
和transformers
用于高级提取策略(例如,余弦策略、某些 LLM 滤波器)。图像明显更大。请确保您需要这些额外功能。 - 平台考虑使用
buildx
用于构建多架构镜像,特别是推送到镜像仓库。使用docker compose
配置文件(local-amd64
,local-arm64
) 以便轻松进行特定于平台的本地构建。 - 性能优化图像自动包含特定于平台的优化(用于 AMD64 的 OpenMP、用于 ARM64 的 OpenBLAS)。
使用 API
通过 REST API 与正在运行的 Docker 服务器进行通信(默认为http://localhost:11235
)。您可以使用 Python SDK 或直接发出 HTTP 请求。
游乐场界面
内置的 Web 游乐场位于http://localhost:11235/playground
用于测试和生成 API 请求。该 Playground 允许您:
- 配置
CrawlerRunConfig
和BrowserConfig
使用主库的 Python 语法 - 直接从界面测试爬取操作
- 根据您的配置为 REST API 请求生成相应的 JSON
这是构建集成时将 Python 配置转换为 JSON 请求的最简单方法。
Python SDK
安装 SDK:pip install crawl4ai
import asyncio
from crawl4ai.docker_client import Crawl4aiDockerClient
from crawl4ai import BrowserConfig, CrawlerRunConfig, CacheMode # Assuming you have crawl4ai installed
async def main():
# Point to the correct server port
async with Crawl4aiDockerClient(base_url="http://localhost:11235", verbose=True) as client:
# If JWT is enabled on the server, authenticate first:
# await client.authenticate("user@example.com") # See Server Configuration section
# Example Non-streaming crawl
print("--- Running Non-Streaming Crawl ---")
results = await client.crawl(
["https://httpbin.org/html"],
browser_config=BrowserConfig(headless=True), # Use library classes for config aid
crawler_config=CrawlerRunConfig(cache_mode=CacheMode.BYPASS)
)
if results: # client.crawl returns None on failure
print(f"Non-streaming results success: {results.success}")
if results.success:
for result in results: # Iterate through the CrawlResultContainer
print(f"URL: {result.url}, Success: {result.success}")
else:
print("Non-streaming crawl failed.")
# Example Streaming crawl
print("\n--- Running Streaming Crawl ---")
stream_config = CrawlerRunConfig(stream=True, cache_mode=CacheMode.BYPASS)
try:
async for result in await client.crawl( # client.crawl returns an async generator for streaming
["https://httpbin.org/html", "https://httpbin.org/links/5/0"],
browser_config=BrowserConfig(headless=True),
crawler_config=stream_config
):
print(f"Streamed result: URL: {result.url}, Success: {result.success}")
except Exception as e:
print(f"Streaming crawl failed: {e}")
# Example Get schema
print("\n--- Getting Schema ---")
schema = await client.get_schema()
print(f"Schema received: {bool(schema)}") # Print whether schema was received
if __name__ == "__main__":
asyncio.run(main())
(SDK 参数如超时、verify_ssl 等保持不变)
第二种方法:直接 API 调用
至关重要的是,当通过 JSON 直接发送配置时,它们必须遵循{"type": "ClassName", "params": {...}}
任何非原始值(例如配置对象或策略)的结构。字典必须包装为{"type": "dict", "value": {...}}
。
(保留配置结构、基本模式、简单与复杂、策略模式、复杂嵌套示例、快速语法概述、重要规则、专业提示的详细解释)
更多示例(确保 Schema 示例使用类型/值包装器)
高级爬虫配置(保留示例,确保 cache_mode 使用有效的枚举值,如“bypass”)
提取策略
{
"crawler_config": {
"type": "CrawlerRunConfig",
"params": {
"extraction_strategy": {
"type": "JsonCssExtractionStrategy",
"params": {
"schema": {
"type": "dict",
"value": {
"baseSelector": "article.post",
"fields": [
{"name": "title", "selector": "h1", "type": "text"},
{"name": "content", "selector": ".content", "type": "html"}
]
}
}
}
}
}
}
}
LLM 提取策略(保留示例,确保模式使用类型/值包装器)(保留深度爬虫示例)
REST API 示例
更新 URL 以使用端口11235
。
简单爬取
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}")
流媒体结果
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())
指标与监控
使用以下端点密切关注您的爬虫:
- - 快速健康检查
- - 详细的 Prometheus 指标
- - 完整的 API 模式
健康检查示例:
(部署场景和完整示例部分保持不变,如果示例移动,可能会更新链接)
服务器配置
服务器的行为可以通过config.yml
文件。
理解 config.yml
配置文件从/app/config.yml
在容器内。默认情况下,deploy/docker/config.yml
在构建过程中,存储库中的内容会被复制到那里。
以下是配置选项的详细分类(使用来自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"
api_key_env: "OPENAI_API_KEY"
# api_key: sk-... # If you pass the API key directly then api_key_env will be ignored
# 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
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 身份验证部分保持不变,只需注意请求的默认端口现在是 11235)
(配置技巧和最佳实践保持不变)
自定义配置
您可以覆盖默认config.yml
。
方法一:构建前修改
- 编辑
deploy/docker/config.yml
本地存储库中的文件克隆。 - 使用以下方式构建图像
docker buildx
或者docker compose --profile local-... up --build
. 修改后的文件将被复制到图像中。
方法 2:运行时挂载(推荐用于自定义部署)
- 创建自定义配置文件,例如,
my-custom-config.yml
本地。确保它包含所有必要的部分。 - 在运行容器时挂载它:使用
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
docker-compose.yml
:添加volumes
服务定义的部分:
(注意:确保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
my-custom-config.yml
与以下目录相同docker-compose.yml
)
💡 挂载时,您的自定义文件将完全替换默认文件。请确保其配置有效且完整。
配置建议
- 安全第一
- 始终在生产中启用安全性
- 使用特定的 trusted_hosts 而不是通配符
- 设置适当的速率限制来保护您的服务器
- 启用 HTTPS 重定向之前请考虑您的环境
- 资源管理💻
- 根据可用 RAM 调整 memory_threshold_percent
- 根据内容大小和网络条件设置超时
- 在多容器设置中使用 Redis 进行速率限制
- 监控📊
- 如果需要指标,请启用 Prometheus
- 在开发中设置 DEBUG 日志,在生产中设置 INFO
- 定期健康检查监测至关重要
- 性能调优⚡
- 从保守的速率限制器延迟开始
- 增加大内容的batch_process超时
- 根据初始响应时间调整 stream_init 超时
获取帮助
我们随时准备帮助您通过 Crawl4AI 取得成功!获取支持的方法如下:
- 📖 查看我们的完整文档
- 🐛 发现 bug?提交问题
- 💬 加入我们的Discord 社区
- ⭐ 在 GitHub 上为我们加星标以表示支持!
概括
在本指南中,我们介绍了开始使用 Crawl4AI 的 Docker 部署所需的一切:- 构建和运行 Docker 容器 - 配置环境 - 使用交互式游乐场进行测试 - 使用正确的类型发出 API 请求 - 使用 Python SDK - 利用专用端点进行屏幕截图、PDF 和 JavaScript 执行 - 通过模型上下文协议 (MCP) 连接 - 监控您的部署
新的游乐场界面位于http://localhost:11235/playground
使得测试配置和为 API 请求生成相应的 JSON 变得更加容易。
对于 AI 应用程序开发人员来说,MCP 集成允许 Claude Code 等工具直接访问 Crawl4AI 的功能,而无需复杂的 API 处理。
请记住,examples
文件夹是你的朋友——它们展示了你可以根据自己的需要进行调整的真实世界的使用模式。
继续探索,如需帮助,请随时联系我们!我们正在携手创造非凡。🚀
爬行快乐!🕷️