Selenium Docker容器在EC2运行正常但AWS Lambda运行失败如何解决
修复步骤
1. 调整Lambda基础配置
- 进入Lambda函数配置页,将内存调整至至少1024MB,Chrome运行最低需要512MB以上内存,默认256MB配置会直接导致tab崩溃。
- 确认Lambda运行架构选择
x86_64,与你构建镜像使用的EC2架构、Chrome安装包架构保持一致,不要选择Graviton2/arm架构。
2. 修复app.py代码问题
import json # 新增缺失的json依赖导入 from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC def handler(event, context): chrome_options = Options() chrome_options.add_argument("--allow-running-insecure-content") chrome_options.add_argument("--ignore-certificate-errors") chrome_options.add_argument("--headless") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-dev-shm-usage") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--no-zygote") chrome_options.add_argument("--v=99") # 移除导致Lambda沙箱崩溃的--single-process、--disable-dev-tools参数 # 新增Lambda环境适配参数 chrome_options.add_argument("--disable-extensions") chrome_options.add_argument("--disable-background-networking") chrome_options.add_argument("--disable-default-apps") chrome_options.add_argument("--disable-sync") chrome_options.add_argument("--disable-translate") chrome_options.add_argument("--hide-scrollbars") chrome_options.add_argument("--metrics-recording-only") chrome_options.add_argument("--mute-audio") chrome_options.add_argument("--no-first-run") chrome_options.add_argument("--safebrowsing-disable-auto-update") chrome_options.binary_location = '/usr/bin/google-chrome-stable' # 直接在options中配置不安全证书配置,移除冲突的DesiredCapabilities配置 chrome_options.accept_insecure_certs = True driver = webdriver.Chrome( executable_path='/usr/local/bin/chromedriver', options=chrome_options) if driver: response = { "statusCode": 200, "body": json.dumps("Selenium Driver Initiated") } # 用完关闭driver避免资源泄漏 driver.quit() return response
3. 优化Dockerfile避免版本不兼容
锁死Chrome和Chromedriver版本,避免自动拉取最新版导致的版本 mismatch 问题:
FROM public.ecr.aws/lambda/python:3.8 # 安装Chrome,和报错中的93.0.4577版本对齐 RUN curl https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm > ./google-chrome-stable_current_x86_64.rpm RUN yum install -y ./google-chrome-stable_current_x86_64.rpm RUN rm ./google-chrome-stable_current_x86_64.rpm # 安装对应版本的Chromedriver,不再拉取最新版 RUN yum install -y unzip RUN curl http://chromedriver.storage.googleapis.com/93.0.4577.63/chromedriver_linux64.zip > /tmp/chromedriver.zip RUN unzip /tmp/chromedriver.zip chromedriver -d /usr/local/bin/ RUN chmod +x /usr/local/bin/chromedriver # 新增执行权限配置 RUN rm /tmp/chromedriver.zip RUN yum remove -y unzip # 安装依赖 RUN pip3 install --upgrade pip RUN pip3 install selenium==3.141.0 --target "${LAMBDA_TASK_ROOT}" # 锁死selenium版本,避免新版本语法兼容问题 # 复制代码 COPY app.py ${LAMBDA_TASK_ROOT} CMD ["app.handler"]
4. 重新部署验证
- 重新构建镜像后推送到ECR,更新Lambda函数的镜像版本
- 触发测试即可正常运行
内容的提问来源于stack exchange,提问作者lbrb
相关产品推荐
相关产品推荐

