为 AWS ECR 和 Lambda 构建 Docker 映像的依赖性问题

问题描述 投票:0回答:1

我正在尝试在 AWS Lambda 上运行 Python 函数。它需要 ECPy 和 safe-pysha3 作为依赖项。当直接上传到 Lambda 时,无论我如何尝试和构建它,我都无法让 Lambda 找到 pysha3 模块。这是因为 pysha3 使用 gcc 来运行。我也尝试过上传层内的依赖项,但没有成功。

我的方法已更改为构建该函数的 Docker 映像。当 Docker 文件使用 Python 基础镜像时,这有点有效。然后我就可以完全无错误地构建 Docker 映像。唯一的问题是,如果您不使用 AWS 基础映像,Lambda 找不到该函数的事件处理程序。当我删除事件处理程序时,代码在 Lambda 上完美执行,但函数在完成代码时失败,因为它期望从不存在的事件处理程序返回。

为了干净地运行 Lambda 函数,而不会在代码完成时失败。我需要使用 AWS 基础映像构建 Docker 映像,以便事件处理程序可以执行代码并给出返回。不幸的是,由于 safe-pysha3 依赖性及其 gcc 要求,使用 AWS 基础映像制作的 Docker 映像将无法构建。我在构建过程中尝试了多种方法首先从 Dockerfile 安装 gcc,但没有成功。

Dockerfile 变体...

首选的完整 Dockerfile,可在 AWS Lambda 上按要求工作,但不会构建。

构建首选 Dockerfile 时出错。

如有任何其他想法,我们将不胜感激。

python aws-lambda dockerfile dependencies
1个回答
0
投票

解决方案是在 Dockerfile 中使用以下代码...

# syntax=docker/dockerfile:1

# Define custom function directory
ARG FUNCTION_DIR="/function"

FROM python:3.12 as build-image

# Include global arg in this stage of the build
ARG FUNCTION_DIR

# Copy function code
RUN mkdir -p ${FUNCTION_DIR}
COPY . ${FUNCTION_DIR}

# Install the function's dependencies
RUN pip install \
--target ${FUNCTION_DIR} \
    awslambdaric \
    safe-pysha3 \
    ecpy

# Use a slim version of the base Python image to reduce the final image size
FROM python:3.12-slim

# Include global arg in this stage of the build
ARG FUNCTION_DIR
# Set working directory to function root directory
WORKDIR ${FUNCTION_DIR}

# Copy in the built dependencies
COPY --from=build-image ${FUNCTION_DIR} ${FUNCTION_DIR}

# Set runtime interface client as default command for the container runtime
ENTRYPOINT [ "/usr/local/bin/python", "-m", "awslambdaric" ]
# Pass the name of the function handler as an argument to the runtime
CMD [ "lambda_function.lambda_handler" ]
© www.soinside.com 2019 - 2024. All rights reserved.