当我们需要在 AWS 中为 lambda 函数创建一个层,并且该层对其操作有一些 SO 依赖项时,所以我们遇到了问题,AWS 文档对此进行了说明,可能还不够。
因此,在这种情况下,我们可以在所需的层中构建缺少的二进制文件。
好吧,对于这个例子,我们将使用 Python 3.x 和 Pdf2Image 库来制作演示
mkdir lambda-layer cd lambda-layer mkdir python cd python
pip3 install [your_dependencies] \ --platform manylinux2014_x86_64 \ --target . \ --only-binary=:all: \ --implementation cp \ --python-version [TU_VERSION_PYTHON] \ --no-deps
pdf2image 示例:
pip3 install pdf2image Pillow \ --platform manylinux2014_x86_64 \ --target . \ --only-binary=:all: \ --implementation cp \ --python-version 3.10 \ --no-deps
FROM ubuntu:22.04 as builder ENV DEBIAN_FRONTEND=noninteractive RUN apt-get update && apt-get install -y \ python3.10 \ python3-pip \ binutils \ zip \ [TUS_PAQUETES_ADICIONALES] \ --no-install-recommends \ && rm -rf /var/lib/apt/lists/* WORKDIR /lambda RUN mkdir -p /opt/python/lib/python3.10/site-packages/bin COPY python/ /opt/python/lib/python3.10/site-packages/ RUN cp [TUS_BINARIOS] /opt/python/lib/python3.10/site-packages/bin/ && \ chmod 755 /opt/python/lib/python3.10/site-packages/bin/* RUN cd /opt && zip -r9 /lambda/layer.zip python/ FROM alpine:3.18 COPY --from=builder /lambda/layer.zip / CMD ["/bin/sh"]
# image build docker build -t lambda-layer . # extract layer.zip docker run --rm -v "$(pwd)":/out lambda-layer cp /layer.zip /out/
完成前面的步骤后,我们可以像往常一样上传图层并将其导入到我们的项目中
import os import sys #Configuring paths SITE_PACKAGES = '/opt/python/lib/python3.10/site-packages' BIN_DIR = os.path.join(SITE_PACKAGES, 'bin') os.environ['PATH'] = f"{BIN_DIR}:{os.environ['PATH']}" sys.path.append(SITE_PACKAGES) #importing dependencies from pdf2image import [your_import] def lambda_handler(event, context): try: # your code here return { 'statusCode': 200, 'body': 'Success' } except Exception as e: return { 'statusCode': 500, 'body': f'Error: {str(e)}' }
以上是使用 Docker 创建 AWS 层。的详细内容。更多信息请关注PHP中文网其他相关文章!