Docker 部署 - Crawl4AI 文档 (v0.5.x)
快速入门 🚀
拉取并运行基础版本:
# 不带安全性的基本运行
docker pull unclecode/crawl4ai:basic
docker run -p 11235:11235 unclecode/crawl4ai:basic
# 带有 API 安全性启用的运行
docker run -p 11235:11235 -e CRAWL4AI_API_TOKEN=your_secret_token unclecode/crawl4ai:basic
使用 Docker Compose 运行 🐳
从本地 Dockerfile 或 Docker Hub 使用 Docker Compose
Crawl4AI 提供灵活的 Docker Compose 选项,用于管理你的容器化服务。你可以使用提供的 Dockerfile
本地构建镜像,也可以使用 Docker Hub 上的预构建镜像。
选项 1:使用 Docker Compose 本地构建
如果你希望本地构建镜像,请使用提供的 docker-compose.local.yml
文件。
docker-compose -f docker-compose.local.yml up -d
这将:
1. 从提供的 Dockerfile
构建 Docker 镜像。
2. 启动容器并将其暴露在 http://localhost:11235
。
选项 2:使用 Docker Compose 从 Hub 获取预构建镜像
如果你更倾向于使用 Docker Hub 上的预构建镜像,请使用 docker-compose.hub.yml
文件。
docker-compose -f docker-compose.hub.yml up -d
这将:
1. 拉取预构建镜像 unclecode/crawl4ai:basic
(或根据你的配置选择 all
)。
2. 启动容器并将其暴露在 http://localhost:11235
。
停止正在运行的服务
要停止通过 Docker Compose 启动的服务,可以使用:
docker-compose -f docker-compose.local.yml down
# 或者
docker-compose -f docker-compose.hub.yml down
如果容器无法停止且应用仍在运行,请检查正在运行的容器:
找到正在运行的服务的 CONTAINER ID
并强制停止它:
docker stop <CONTAINER_ID>
使用 Docker Compose 调试
- 查看日志:要查看容器日志:
docker-compose -f docker-compose.local.yml logs -f
- 移除孤立容器:如果服务仍在意外运行:
docker-compose -f docker-compose.local.yml down --remove-orphans
- 手动移除网络:如果网络仍在使用中:
docker network ls
docker network rm crawl4ai_default
为什么使用 Docker Compose?
Docker Compose 是部署 Crawl4AI 的推荐方式,因为:
1. 它简化了多容器设置。
2. 允许你在单个文件中定义环境变量、资源和端口。
3. 使在本地开发和生产镜像之间切换变得更容易。
例如,你的 docker-compose.yml
可以包含 API 密钥、令牌设置和内存限制,使部署快速且一致。
API 安全性 🔒
了解 CRAWL4AI_API_TOKEN
CRAWL4AI_API_TOKEN
为你的 Crawl4AI 实例提供可选的安全性:
- 如果设置了
CRAWL4AI_API_TOKEN
:所有 API 端点(除了/health
)都需要认证。 - 如果没有设置
CRAWL4AI_API_TOKEN
:API 将公开可用。
# 安全实例
docker run -p 11235:11235 -e CRAWL4AI_API_TOKEN=your_secret_token unclecode/crawl4ai:all
# 未受保护实例
docker run -p 11235:11235 unclecode/crawl4ai:all
进行 API 调用
对于受保护的实例,在所有请求中包含令牌:
import requests
# 设置标头(如果使用了令牌)
api_token = "your_secret_token" # 与 CRAWL4AI_API_TOKEN 中设置的令牌相同
headers = {"Authorization": f"Bearer {api_token}"} if api_token else {}
# 发起认证请求
response = requests.post(
"http://localhost:11235/crawl",
headers=headers,
json={
"urls": "https://example.com",
"priority": 10
}
)
# 检查任务状态
task_id = response.json()["task_id"]
status = requests.get(
f"http://localhost:11235/task/{task_id}",
headers=headers
)
与 Docker Compose 一起使用
在你的 docker-compose.yml
中:
services:
crawl4ai:
image: unclecode/crawl4ai:all
environment:
- CRAWL4AI_API_TOKEN=${CRAWL4AI_API_TOKEN:-} # 可选
# ... 其他配置
然后可以:
1. 在 .env
文件中设置:
CRAWL4AI_API_TOKEN=your_secret_token
或者在命令行中设置:
CRAWL4AI_API_TOKEN=your_secret_token docker-compose up
安全提示:如果你启用了 API 令牌,请确保保持其安全性,不要将其提交到版本控制中。除了健康检查端点(
/health
)外,所有 API 端点都需要该令牌。
配置选项 🔧
环境变量
你可以使用环境变量来配置服务:
# 基本配置
docker run -p 11235:11235 \
-e MAX_CONCURRENT_TASKS=5 \
unclecode/crawl4ai:all
# 启用安全性和 LLM 支持
docker run -p 11235:11235 \
-e CRAWL4AI_API_TOKEN=your_secret_token \
-e OPENAI_API_KEY=sk-... \
-e ANTHROPIC_API_KEY=sk-ant-... \
unclecode/crawl4ai:all
使用 Docker Compose(推荐) 🐳
创建一个 docker-compose.yml
文件:
version: '3.8'
services:
crawl4ai:
image: unclecode/crawl4ai:all
ports:
- "11235:11235"
environment:
- CRAWL4AI_API_TOKEN=${CRAWL4AI_API_TOKEN:-} # 可选 API 安全性
- MAX_CONCURRENT_TASKS=5
# LLM 提供商密钥
- OPENAI_API_KEY=${OPENAI_API_KEY:-}
- ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY:-}
volumes:
- /dev/shm:/dev/shm
deploy:
resources:
limits:
memory: 4G
reservations:
memory: 1G
你可以通过两种方式运行它:
- 直接使用环境变量:
CRAWL4AI_API_TOKEN=secret123 OPENAI_API_KEY=sk-... docker-compose up
- 使用
.env
文件(推荐):
在同一目录下创建一个.env
文件:
# API 安全性(可选)
CRAWL4AI_API_TOKEN=your_secret_token
# LLM 提供商密钥
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
# 其他配置
MAX_CONCURRENT_TASKS=5
然后只需运行:
测试部署 🧪
import requests
# 对于未受保护的实例
def test_unsecured():
# 健康检查
health = requests.get("http://localhost:11235/health")
print("健康检查:", health.json())
# 基本爬取
response = requests.post(
"http://localhost:11235/crawl",
json={
"urls": "https://www.nbcnews.com/business",
"priority": 10
}
)
task_id = response.json()["task_id"]
print("任务 ID:", task_id)
# 对于受保护的实例
def test_secured(api_token):
headers = {"Authorization": f"Bearer {api_token}"}
# 带认证的基本爬取
response = requests.post(
"http://localhost:11235/crawl",
headers=headers,
json={
"urls": "https://www.nbcnews.com/business",
"priority": 10
}
)
task_id = response.json()["task_id"]
print("任务 ID:", task_id)
当你配置了 LLM 提供商密钥(通过环境变量或 .env
文件),你可以使用 LLM 提取:
request = {
"urls": "https://example.com",
"extraction_config": {
"type": "llm",
"params": {
"provider": "openai/gpt-4",
"instruction": "从页面中提取主要主题"
}
}
}
# 发起请求(如果使用 API 安全性,请添加标头)
response = requests.post("http://localhost:11235/crawl", json=request)
提示:记得将
.env
添加到.gitignore
中,以确保你的 API 密钥安全!
使用示例 📝
基本爬取
request = {
"urls": "https://www.nbcnews.com/business",
"priority": 10
}
response = requests.post("http://localhost:11235/crawl", json=request)
task_id = response.json()["task_id"]
# 获取结果
result = requests.get(f"http://localhost:11235/task/{task_id}")
schema = {
"name": "加密货币价格",
"baseSelector": ".cds-tableRow-t45thuk",
"fields": [
{
"name": "加密货币",
"selector": "td:nth-child(1) h2",
"type": "text",
},
{
"name": "价格",
"selector": "td:nth-child(2)",
"type": "text",
}
],
}
request = {
"urls": "https://www.coinbase.com/explore",
"extraction_config": {
"type": "json_css",
"params": {"schema": schema}
}
}
处理动态内容
request = {
"urls": "https://www.nbcnews.com/business",
"js_code": [
"const loadMoreButton = Array.from(document.querySelectorAll('button')).find(button => button.textContent.includes('Load More')); loadMoreButton && loadMoreButton.click();"
],
"wait_for": "article.tease-card:nth-child(10)"
}
request = {
"urls": "https://www.nbcnews.com/business",
"extraction_config": {
"type": "cosine",
"params": {
"semantic_filter": "商业 财务 经济",
"word_count_threshold": 10,
"max_dist": 0.2,
"top_k": 3
}
}
}
平台特定指令 💻
macOS
docker pull unclecode/crawl4ai:basic
docker run -p 11235:11235 unclecode/crawl4ai:basic
Ubuntu
# 基础版本
docker pull unclecode/crawl4ai:basic
docker run -p 11235:11235 unclecode/crawl4ai:basic
# 带 GPU 支持
docker pull unclecode/crawl4ai:gpu
docker run --gpus all -p 11235:11235 unclecode/crawl4ai:gpu
Windows(PowerShell)
docker pull unclecode/crawl4ai:basic
docker run -p 11235:11235 unclecode/crawl4ai:basic
测试 🧪
将以下内容保存为 test_docker.py
:
import requests
import json
import time
import sys
class Crawl4AiTester:
def __init__(self, base_url: str = "http://localhost:11235"):
self.base_url = base_url
def submit_and_wait(self, request_data: dict, timeout: int = 300) -> dict:
# 提交爬取任务
response = requests.post(f"{self.base_url}/crawl", json=request_data)
task_id = response.json()["task_id"]
print(f"任务 ID:{task_id}")
# 轮询结果
start_time = time.time()
while True:
if time.time() - start_time > timeout:
raise TimeoutError(f"任务 {task_id} 超时")
result = requests.get(f"{self.base_url}/task/{task_id}")
status = result.json()
if status["status"] == "completed":
return status
time.sleep(2)
def test_deployment():
tester = Crawl4AiTester()
# 测试基本爬取
request = {
"urls": "https://www.nbcnews.com/business",
"priority": 10
}
result = tester.submit_and_wait(request)
print("基本爬取成功!")
print(f"内容长度:{len(result['result']['markdown'])}")
if __name__ == "__main__":
test_deployment()
高级配置 ⚙️
爬虫参数
crawler_params
字段允许你配置浏览器实例和爬取行为。以下是你可以使用的关键参数:
request = {
"urls": "https://example.com",
"crawler_params": {
# 浏览器配置
"headless": True, # 以无头模式运行
"browser_type": "chromium", # chromium/firefox/webkit
"user_agent": "custom-agent", # 自定义用户代理
"proxy": "http://proxy:8080", # 代理配置
# 性能与行为
"page_timeout": 30000, # 页面加载超时(毫秒)
"verbose": True, # 启用详细日志
"semaphore_count": 5, # 并发请求限制
# 防检测功能
"simulate_user": True, # 模拟人类行为
"magic": True, # 高级防检测
"override_navigator": True, # 覆盖导航器属性
# 会话管理
"user_data_dir": "./browser-data", # 浏览器配置文件位置
"use_managed_browser": True, # 使用持久浏览器
}
}
extra
字段允许直接将额外参数传递给爬虫的 arun
函数:
request = {
"urls": "https://example.com",
"extra": {
"word_count_threshold": 10, # 每个区块的最小字数
"only_text": True, # 仅提取文本
"bypass_cache": True, # 强制刷新爬取
"process_iframes": True, # 包含 iframe 内容
}
}
完整示例
- 高级新闻爬取
request = {
"urls": "https://www.nbcnews.com/business",
"crawler_params": {
"headless": True,
"page_timeout": 30000,
"remove_overlay_elements": True # 移除弹出窗口
},
"extra": {
"word_count_threshold": 50, # 更长的内容区块
"bypass_cache": True # 刷新内容
},
"css_selector": ".article-body"
}
- 防检测配置
request = {
"urls": "https://example.com",
"crawler_params": {
"simulate_user": True,
"magic": True,
"override_navigator": True,
"user_agent": "Mozilla/5.0 ...",
"headers": {
"Accept-Language": "en-US,en;q=0.9"
}
}
}
- 带有自定义参数的 LLM 提取
request = {
"urls": "https://openai.com/pricing",
"extraction_config": {
"type": "llm",
"params": {
"provider": "openai/gpt-4",
"schema": pricing_schema
}
},
"crawler_params": {
"verbose": True,
"page_timeout": 60000
},
"extra": {
"word_count_threshold": 1,
"only_text": True
}
}
- 基于会话的动态内容
request = {
"urls": "https://example.com",
"crawler_params": {
"session_id": "dynamic_session",
"headless": False,
"page_timeout": 60000
},
"js_code": ["window.scrollTo(0, document.body.scrollHeight);"],
"wait_for": "js:() => document.querySelectorAll('.item').length > 10",
"extra": {
"delay_before_return_html": 2.0
}
}
- 带自定义时间的截图
request = {
"urls": "https://example.com",
"screenshot": True,
"crawler_params": {
"headless": True,
"screenshot_wait_for": ".main-content"
},
"extra": {
"delay_before_return_html": 3.0
}
}
参数参考表
分类 | 参数 | 类型 | 描述 |
---|---|---|---|
浏览器 | headless | 布尔值 | 以无头模式运行浏览器 |
浏览器 | browser_type | 字符串 | 浏览器引擎选择 |
浏览器 | user_agent | 字符串 | 自定义用户代理字符串 |
网络 | proxy | 字符串 | 代理服务器 URL |
网络 | headers | 字典 | 自定义 HTTP 标头 |
定时 | page_timeout | 整数 | 页面加载超时(毫秒) |
定时 | delay_before_return_html | 浮点数 | 捕获前等待时间 |
防检测 | simulate_user | 布尔值 | 模拟人类行为 |
防检测 | magic | 布尔值 | 高级保护 |
会话 | session_id | 字符串 | 浏览器会话 ID |
会话 | user_data_dir | 字符串 | 配置文件目录 |
内容 | word_count_threshold | 整数 | 每个区块的最小字数 |
内容 | only_text | 布尔值 | 仅提取文本 |
内容 | process_iframes | 布尔值 | 包含 iframe 内容 |
调试 | verbose | 布尔值 | 详细日志 |
调试 | log_console | 布尔值 | 浏览器控制台日志 |
故障排除 🔍
常见问题
- 连接拒绝
错误:连接被 localhost:11235 拒绝
解决方案:确保容器正在运行且端口映射正确。
- 资源限制
错误:没有可用插槽
解决方案:增加 MAX_CONCURRENT_TASKS 或容器资源。
- GPU 访问
解决方案:确保安装了正确的 NVIDIA 驱动程序并使用 --gpus all
标志。
调试模式
访问容器进行调试:
docker run -it --entrypoint /bin/bash unclecode/crawl4ai:all
查看容器日志:
docker logs [container_id]
最佳实践 🌟
-
资源管理
- 设置适当的内存和 CPU 限制
- 通过健康端点监控资源使用情况
- 对于简单爬取任务使用基础版本 -
扩展
- 对于高负载使用多个容器
- 实施适当的负载均衡
- 监控性能指标 -
安全性
- 使用环境变量存储敏感数据
- 实施适当的网络隔离
- 定期进行安全更新
API 参考 📚
健康检查
提交爬取任务
POST /crawl
Content-Type: application/json
{
"urls": "字符串或数组",
"extraction_config": {
"type": "basic|llm|cosine|json_css",
"params": {}
},
"priority": 1-10,
"ttl": 3600
}