我已将 python 和 R 容器化 lambda 转换为多阶段构建,这将 ECR 中容器的大小从 477 MB 减少到 160 MB,但两者的冷启动时间大致相同(事实上,对于更小的封装(从 2.3 -> 2.97s)
鉴于我的 Dockerfile 如下所示:
# Stage 1: Build stage
FROM python:3.10-slim-bullseye as builder
ENV DEBIAN_FRONTEND=noninteractive
# Set up environment variables
ENV LC_ALL=C.UTF-8
ENV LANG=en_US.UTF-8
ENV TZ=:/etc/localtime
ENV PATH=/var/lang/bin:/usr/local/bin:/usr/bin/:/bin:/opt/bin
ENV LD_LIBRARY_PATH=/var/lang/lib:/lib64:/usr/lib64:/var/runtime:/var/runtime/lib:/var/task:/var/task/lib:/opt/lib
# Install build dependencies and R in build stage
RUN apt-get update && \
apt-get install -y \
g++ \
make \
cmake \
unzip \
libcurl4-openssl-dev \
r-base-core \
&& apt-get clean
# Set up working directory
ARG FUNCTION_DIR="/var/task"
WORKDIR ${FUNCTION_DIR}
# Copy requirements for Python and R scripts
COPY requirements.txt .
COPY script_calcproper.R .
COPY main.py .
COPY data/. data/.
# Install Python dependencies
RUN pip install --no-cache-dir -r requirements.txt
# Stage 2: Final stage
FROM python:3.10-slim-bullseye
ENV DEBIAN_FRONTEND=noninteractive
# Set up environment variables
ENV LC_ALL=C.UTF-8
ENV LANG=en_US.UTF-8
ENV TZ=:/etc/localtime
ENV PATH=/var/lang/bin:/usr/local/bin:/usr/bin/:/bin:/opt/bin
ENV LD_LIBRARY_PATH=/var/lang/lib:/lib64:/usr/lib64:/var/runtime:/var/runtime/lib:/var/task:/var/task/lib:/opt/lib
# Install R runtime dependencies in final stage
RUN apt-get update && \
apt-get install -y --no-install-recommends \
r-base-core \
libcurl4-openssl-dev \
&& apt-get clean && rm -rf /var/lib/apt/lists/*
# Define custom function directory
ARG FUNCTION_DIR="/var/task"
WORKDIR ${FUNCTION_DIR}
# Copy only the necessary files from the build stage
COPY --from=builder /usr/local/lib/python3.10/site-packages /usr/local/lib/python3.10/site-packages
COPY --from=builder /usr/local/bin /usr/local/bin
COPY --from=builder ${FUNCTION_DIR} ${FUNCTION_DIR}
# Set the CMD to your handler
ENTRYPOINT [ "/usr/local/bin/python", "-m", "awslambdaric" ]
CMD [ "main.handler"]
关于为什么我的 fcn 冷启动仍然这么慢有什么建议吗? 我的requirements.txt包是pandas、rpy2、boto3和awslambdric。
冷启动时间不仅仅取决于容器尺寸。虽然您缩小了图像尺寸,但还有其他因素在起作用:
改善冷启动时间:
请记住,虽然减小图像大小有利于存储和潜在的下载时间,但运行时和依赖项的初始化通常会主导冷启动性能。
如果您需要进一步优化,请考虑分享有关函数操作的更多详细信息,我们可以研究特定于语言的优化。