You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Puppeteer与Sparticuz/Chromium在AWS Lambda中创建浏览器超时

问题:AWS Lambda运行Chromium超时(256MB内存配置)

在AWS Lambda中使用Puppeteer和@sparticuz/chromium启动Chromium实例,配置256MB内存时,Lambda在17秒左右触发任务超时。依赖项已通过Cloud9创建为Layer并添加至Lambda,相关代码、响应及日志如下:

运行代码

import chromium from '@sparticuz/chromium';
import puppeteer from 'puppeteer-core';

export const handler = async (event,context) => {

  var exPath=await chromium.executablePath();
  console.log('exPath'+exPath);

    const browser = await puppeteer.launch({
    args: chromium.args,
    defaultViewport: chromium.defaultViewport,
    executablePath: exPath,
    headless: false,
   });
  console.log("----browser created");
};

响应信息

{
"errorMessage": "2024-03-02T22:21:20.929Z c4ffd913-d40b-4029-b1f2-91971bbe177d Task timed out after 17.11 seconds"
}

函数日志

START RequestId: c4ffd913-d40b-4029-b1f2-91971bbe177d Version: $LATEST
2024-03-02T22:21:20.389Z    c4ffd913-d40b-4029-b1f2-91971bbe177d
INFO    exPath/tmp/chromium
2024-03-02T22:21:20.929Z c4ffd913-d40b-4029-b1f2-91971bbe177d Task timed out after 17.11 seconds

END RequestId: c4ffd913-d40b-4029-b1f2-91971bbe177d
REPORT RequestId: c4ffd913-d40b-4029-b1f2-91971bbe177d  Duration: 17110.91 ms   Billed Duration: 17000 ms   Memory Size: 256 MB Max Memory Used: 256 MB Init Duration: 816.57 ms

解决方案

  • 提升内存配置:日志显示Max Memory Used已达256MB,内存完全耗尽。Chromium启动需要较多资源,建议至少配置1GB内存,Lambda的CPU和网络带宽会随内存提升而增加,大幅缩短启动时间。
  • 启用无头模式:代码中headless: false会消耗更多资源,改为headless: 'new'(@sparticuz/chromium推荐的无头模式),减少资源占用。
  • 优化启动参数:在chromium.args基础上添加资源优化参数:
    args: [
      ...chromium.args,
      '--disable-gpu',
      '--disable-dev-shm-usage',
      '--disable-setuid-sandbox',
      '--no-sandbox',
      '--single-process'
    ]
    
  • 延长超时时间:暂时将Lambda超时时间调整到30秒以上,确保有足够时间完成启动,后续优化后再按需调整。
  • 检查Layer完整性:确认Cloud9创建的Layer包含与Lambda运行时(如Node.js 18.x)匹配的依赖版本,避免因依赖不兼容导致启动缓慢。

内容的提问来源于stack exchange,提问作者vishnumanohar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 14:23:14