Docker 部署 - Crawl4AI 文档 (v0.5.x)

[复制链接]
发表于 2025-9-8 16:20:55 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
Docker 部署 - Crawl4AI 文档 (v0.5.x)

快速入门 🚀

拉取并运行基础版本
  1. # 不带安全性的基本运行
  2. docker pull unclecode/crawl4ai:basic
  3. docker run -p 11235:11235 unclecode/crawl4ai:basic
  4. # 带有 API 安全性启用的运行
  5. docker run -p 11235:11235 -e CRAWL4AI_API_TOKEN=your_secret_token
  6. unclecode/crawl4ai:basic
复制代码
使用 Docker Compose 运行 🐳

从本地 Dockerfile 或 Docker Hub 使用 Docker Compose

Crawl4AI 提供灵活的 Docker Compose 选项,用于管理你的容器化服务。你可以使用提供的 Dockerfile 本地构建镜像,也可以使用 Docker Hub 上的预构建镜像。
选项 1:使用 Docker Compose 本地构建

如果你盼望本地构建镜像,请使用提供的 docker-compose.local.yml 文件。
  1. 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 文件。
  1. docker-compose -f docker-compose.hub.yml up -d
复制代码
这将:
1. 拉取预构建镜像 unclecode/crawl4ai:basic(或根据你的配置选择 all)。
2. 启动容器并将其袒露在 http://localhost:11235。

制止正在运行的服务

要制止通过 Docker Compose 启动的服务,可以使用:
  1. docker-compose -f docker-compose.local.yml down
  2. # 或者
  3. docker-compose -f docker-compose.hub.yml down
复制代码
如果容器无法制止且应用仍在运行,请检查正在运行的容器:
找到正在运行的服务的 CONTAINER ID 并强制制止它:
  1. docker stop <CONTAINER_ID>
复制代码

使用 Docker Compose 调试

  1. docker-compose -f docker-compose.local.yml logs -f
复制代码

  • 移除孤立容器:如果服务仍在意外运行:
  1. docker-compose -f docker-compose.local.yml down --remove-orphans
复制代码

  • 手动移除网络:如果网络仍在使用中:
  1. docker network ls
  2. 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 将公开可用。
  1. # 安全实例
  2. docker run -p 11235:11235 -e CRAWL4AI_API_TOKEN=your_secret_token
  3. unclecode/crawl4ai:all
  4. # 未受保护实例
  5. docker run -p 11235:11235 unclecode/crawl4ai:all
复制代码
进行 API 调用

对于受保护的实例,在所有请求中包含令牌:
  1. import requests
  2. # 设置标头(如果使用了令牌)
  3. api_token = "your_secret_token"  # 与 CRAWL4AI_API_TOKEN 中设置的令牌相同
  4. headers = {"Authorization": f"Bearer {api_token}"} if api_token else {}
  5. # 发起认证请求
  6. response = requests.post(
  7.     "http://localhost:11235/crawl",
  8.     headers=headers,
  9.     json={
  10.         "urls": "https://example.com",
  11.         "priority": 10
  12.     }
  13. )
  14. # 检查任务状态
  15. task_id = response.json()["task_id"]
  16. status = requests.get(
  17.     f"http://localhost:11235/task/{task_id}",
  18.     headers=headers
  19. )
复制代码
与 Docker Compose 一起使用

在你的 docker-compose.yml 中:
  1. services:
  2.   crawl4ai:
  3.     image: unclecode/crawl4ai:all
  4.     environment:
  5.       - CRAWL4AI_API_TOKEN=${CRAWL4AI_API_TOKEN:-}  # 可选
  6.     # ... 其他配置
复制代码
然后可以:
1. 在 .env 文件中设置:
  1. CRAWL4AI_API_TOKEN=your_secret_token
复制代码
大概在命令行中设置:
  1. CRAWL4AI_API_TOKEN=your_secret_token
  2. docker-compose up
复制代码
安全提示:如果你启用了 API 令牌,请确保保持其安全性,不要将其提交到版本控制中。除了康健检查端点(/health)外,所有 API 端点都必要该令牌。
配置选项 🔧

情况变量

你可以使用情况变量来配置服务:
  1. # 基本配置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
  2. \    -e OPENAI_API_KEY=sk-... \    -e ANTHROPIC_API_KEY=sk-ant-... \    unclecode/crawl4ai:all
复制代码
使用 Docker Compose(推荐) 🐳

创建一个 docker-compose.yml 文件:
  1. version: '3.8'
  2. services:
  3.   crawl4ai:
  4.     image: unclecode/crawl4ai:all
  5.     ports:
  6.       - "11235:11235"
  7.     environment:
  8.       - CRAWL4AI_API_TOKEN=${CRAWL4AI_API_TOKEN:-}  # 可选 API 安全性
  9.       - MAX_CONCURRENT_TASKS=5
  10.       # LLM 提供商密钥
  11.       - OPENAI_API_KEY=${OPENAI_API_KEY:-}
  12.       - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY:-}
  13.     volumes:
  14.       - /dev/shm:/dev/shm
  15.     deploy:
  16.       resources:
  17.         limits:
  18.           memory: 4G
  19.         reservations:
  20.           memory: 1G
复制代码
你可以通过两种方式运行它:

  • 直接使用情况变量:
  1. CRAWL4AI_API_TOKEN=secret123 OPENAI_API_KEY=sk-... docker-compose up
复制代码

  • 使用 .env 文件(推荐):
    在同一目次下创建一个 .env 文件:
  1. # API 安全性(可选)CRAWL4AI_API_TOKEN=your_secret_token
  2. # LLM 提供商密钥OPENAI_API_KEY=sk-...ANTHROPIC_API_KEY=sk-ant-...# 其他配置MAX_CONCURRENT_TASKS=5
复制代码
然后只需运行:
测试部署 🧪
  1. import requests
  2. # 对于未受保护的实例
  3. def test_unsecured():
  4.     # 健康检查
  5.     health = requests.get("http://localhost:11235/health")
  6.     print("健康检查:", health.json())
  7.     # 基本爬取
  8.     response = requests.post(
  9.         "http://localhost:11235/crawl",
  10.         json={
  11.             "urls": "https://www.nbcnews.com/business",
  12.             "priority": 10
  13.         }
  14.     )
  15.     task_id = response.json()["task_id"]
  16.     print("任务 ID:", task_id)
  17. # 对于受保护的实例
  18. def test_secured(api_token):
  19.     headers = {"Authorization": f"Bearer {api_token}"}
  20.     # 带认证的基本爬取
  21.     response = requests.post(
  22.         "http://localhost:11235/crawl",
  23.         headers=headers,
  24.         json={
  25.             "urls": "https://www.nbcnews.com/business",
  26.             "priority": 10
  27.         }
  28.     )
  29.     task_id = response.json()["task_id"]
  30.     print("任务 ID:", task_id)
复制代码
当你配置了 LLM 提供商密钥(通过情况变量或 .env 文件),你可以使用 LLM 提取:
  1. request = {
  2.     "urls": "https://example.com",
  3.     "extraction_config": {
  4.         "type": "llm",
  5.         "params": {
  6.             "provider": "openai/gpt-4",
  7.             "instruction": "从页面中提取主要主题"
  8.         }
  9.     }
  10. }
  11. # 发起请求(如果使用 API 安全性,请添加标头)
  12. response = requests.post("http://localhost:11235/crawl", json=request)
复制代码
提示:记得将 .env 添加到 .gitignore 中,以确保你的 API 密钥安全!
使用示例 📝

基本爬取
  1. request = {
  2.     "urls": "https://www.nbcnews.com/business",
  3.     "priority": 10
  4. }
  5. response = requests.post("http://localhost:11235/crawl", json=request)
  6. task_id = response.json()["task_id"]
  7. # 获取结果
  8. result = requests.get(f"http://localhost:11235/task/{task_id}")
复制代码
  1. schema = {
  2.     "name": "加密货币价格",
  3.     "baseSelector": ".cds-tableRow-t45thuk",
  4.     "fields": [
  5.         {
  6.             "name": "加密货币",
  7.             "selector": "td:nth-child(1) h2",
  8.             "type": "text",
  9.         },
  10.         {
  11.             "name": "价格",
  12.             "selector": "td:nth-child(2)",
  13.             "type": "text",
  14.         }
  15.     ],
  16. }
  17. request = {
  18.     "urls": "https://www.coinbase.com/explore",
  19.     "extraction_config": {
  20.         "type": "json_css",
  21.         "params": {"schema": schema}
  22.     }
  23. }
复制代码
处置惩罚动态内容
  1. request = {
  2.     "urls": "https://www.nbcnews.com/business",
  3.     "js_code": [
  4.         "const loadMoreButton = Array.from(document.querySelectorAll('button')).find(button => button.textContent.includes('Load More')); loadMoreButton && loadMoreButton.click();"
  5.     ],
  6.     "wait_for": "article.tease-card:nth-child(10)"
  7. }
复制代码
  1. request = {
  2.     "urls": "https://www.nbcnews.com/business",
  3.     "extraction_config": {
  4.         "type": "cosine",
  5.         "params": {
  6.             "semantic_filter": "商业 财务 经济",
  7.             "word_count_threshold": 10,
  8.             "max_dist": 0.2,
  9.             "top_k": 3
  10.         }
  11.     }
  12. }
复制代码
平台特定指令 💻

macOS
  1. docker pull unclecode/crawl4ai:basic
  2. docker run -p 11235:11235 unclecode/crawl4ai:basic
复制代码
Ubuntu
  1. # 基础版本docker pull unclecode/crawl4ai:basic
  2. docker run -p 11235:11235 unclecode/crawl4ai:basic
  3. # 带 GPU 支持docker pull unclecode/crawl4ai:gpudocker run --gpus all -p 11235:11235 unclecode/crawl4ai:gpu
复制代码
Windows(PowerShell)
  1. docker pull unclecode/crawl4ai:basic
  2. docker run -p 11235:11235 unclecode/crawl4ai:basic
复制代码
测试 🧪

将以下内容保存为 test_docker.py:
  1. import requests
  2. import json
  3. import time
  4. import sys
  5. class Crawl4AiTester:
  6.     def __init__(self, base_url: str = "http://localhost:11235"):
  7.         self.base_url = base_url
  8.     def submit_and_wait(self, request_data: dict, timeout: int = 300) -> dict:
  9.         # 提交爬取任务
  10.         response = requests.post(f"{self.base_url}/crawl", json=request_data)
  11.         task_id = response.json()["task_id"]
  12.         print(f"任务 ID:{task_id}")
  13.         # 轮询结果
  14.         start_time = time.time()
  15.         while True:
  16.             if time.time() - start_time > timeout:
  17.                 raise TimeoutError(f"任务 {task_id} 超时")
  18.             result = requests.get(f"{self.base_url}/task/{task_id}")
  19.             status = result.json()
  20.             if status["status"] == "completed":
  21.                 return status
  22.             time.sleep(2)
  23. def test_deployment():
  24.     tester = Crawl4AiTester()
  25.     # 测试基本爬取
  26.     request = {
  27.         "urls": "https://www.nbcnews.com/business",
  28.         "priority": 10
  29.     }
  30.     result = tester.submit_and_wait(request)
  31.     print("基本爬取成功!")
  32.     print(f"内容长度:{len(result['result']['markdown'])}")
  33. if __name__ == "__main__":
  34.     test_deployment()
复制代码
高级配置 ⚙️

爬虫参数

crawler_params 字段允许你配置浏览器实例和爬取举动。以下是你可以使用的关键参数:
  1. request = {
  2.     "urls": "https://example.com",
  3.     "crawler_params": {
  4.         # 浏览器配置
  5.         "headless": True,                    # 以无头模式运行
  6.         "browser_type": "chromium",          # chromium/firefox/webkit
  7.         "user_agent": "custom-agent",        # 自定义用户代理
  8.         "proxy": "http://proxy:8080",        # 代理配置
  9.         # 性能与行为
  10.         "page_timeout": 30000,               # 页面加载超时(毫秒)
  11.         "verbose": True,                     # 启用详细日志日志
  12.         "semaphore_count": 5,               # 并发请求限制
  13.         # 防检测功能
  14.         "simulate_user": True,               # 模拟人类行为
  15.         "magic": True,                       # 高级防检测
  16.         "override_navigator": True,          # 覆盖导航器属性
  17.         # 会话管理
  18.         "user_data_dir": "./browser-data",   # 浏览器配置文件位置
  19.         "use_managed_browser": True,         # 使用持久浏览器
  20.     }
  21. }
复制代码
extra 字段允许直接将额外参数传递给爬虫的 arun 函数:
  1. request = {
  2.     "urls": "https://example.com",
  3.     "extra": {
  4.         "word_count_threshold": 10,          # 每个区块的最小字数
  5.         "only_text": True,                   # 仅提取文本
  6.         "bypass_cache": True,                # 强制刷新爬取
  7.         "process_iframes": True,             # 包含 iframe 内容
  8.     }
  9. }
复制代码
完整示例


  • 高级新闻爬取
  1. request = {
  2.     "urls": "https://www.nbcnews.com/business",
  3.     "crawler_params": {
  4.         "headless": True,
  5.         "page_timeout": 30000,
  6.         "remove_overlay_elements": True      # 移除弹出窗口
  7.     },
  8.     "extra": {
  9.         "word_count_threshold": 50,          # 更长的内容区块
  10.         "bypass_cache": True                 # 刷新内容
  11.     },
  12.     "css_selector": ".article-body"
  13. }
复制代码

  • 防检测配置
  1. request = {
  2.     "urls": "https://example.com",
  3.     "crawler_params": {
  4.         "simulate_user": True,
  5.         "magic": True,
  6.         "override_navigator": True,
  7.         "user_agent": "Mozilla/5.0 ...",
  8.         "headers": {
  9.             "Accept-Language": "en-US,en;q=0.9"
  10.         }
  11.     }
  12. }
复制代码

  • 带有自界说参数的 LLM 提取
  1. request = {
  2.     "urls": "https://openai.com/pricing",
  3.     "extraction_config": {
  4.         "type": "llm",
  5.         "params": {
  6.             "provider": "openai/gpt-4",
  7.             "schema": pricing_schema
  8.         }
  9.     },
  10.     "crawler_params": {
  11.         "verbose": True,
  12.         "page_timeout": 60000
  13.     },
  14.     "extra": {
  15.         "word_count_threshold": 1,
  16.         "only_text": True
  17.     }
  18. }
复制代码

  • 基于会话的动态内容
  1. request = {
  2.     "urls": "https://example.com",
  3.     "crawler_params": {
  4.         "session_id": "dynamic_session",
  5.         "headless": False,
  6.         "page_timeout": 60000
  7.     },
  8.     "js_code": ["window.scrollTo(0, document.body.scrollHeight);"],
  9.     "wait_for": "js:() => document.querySelectorAll('.item').length > 10",
  10.     "extra": {
  11.         "delay_before_return_html": 2.0
  12.     }
  13. }
复制代码

  • 带自界说时间的截图
  1. request = {
  2.     "urls": "https://example.com",
  3.     "screenshot": True,
  4.     "crawler_params": {
  5.         "headless": True,
  6.         "screenshot_wait_for": ".main-content"
  7.     },
  8.     "extra": {
  9.         "delay_before_return_html": 3.0
  10.     }
  11. }
复制代码
参数参考表

分类参数范例描述浏览器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布尔值浏览器控制台日志故障排除 🔍

常见问题


  • 连接拒绝
  1. 错误:连接被 localhost:11235 拒绝
复制代码
办理方案:确保容器正在运行且端口映射精确。

  • 资源限定
  1. 错误:没有可用插槽
复制代码
办理方案:增加 MAX_CONCURRENT_TASKS 或容器资源。

  • GPU 访问
办理方案:确保安装了精确的 NVIDIA 驱动步伐并使用 --gpus all 标志。
调试模式

访问容器进行调试:
  1. docker run -it --entrypoint /bin/bash unclecode/crawl4ai:all
复制代码
查察容器日志:
  1. docker logs [container_id]
复制代码
最佳实践 🌟


  • 资源管理
    - 设置适当的内存和 CPU 限定
    - 通过康健端点监控监控资源使用情况
    - 对于简单爬取任务使用基础版本
  • 扩展
    - 对于高负载使用多个容器
    - 实施适当的负载均衡
    - 监控监控性能指标
  • 安全性
    - 使用情况变量存储敏感数据
    - 实施适当的网络隔离
    - 定期进行安全更新
API 参考 📚

康健检查

提交爬取任务
  1. POST /crawl
  2. Content-Type: application/json
  3. {
  4.     "urls": "字符串或数组",
  5.     "extraction_config": {
  6.         "type": "basic|llm|cosine|json_css",
  7.         "params": {}
  8.     },
  9.     "priority": 1-10,
  10.     "ttl": 3600
  11. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
继续阅读请点击广告
回复

使用道具 举报

×
登录参与点评抽奖,加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表