Creating the Dockerfile#

To set up a Dockerfile for a Lambda function that relies on non-AWS base images, you have to include the Python package awslambdaric in your requirements and install it. Then, do the following in the Dockerfile:

ENTRYPOINT [ "/usr/local/bin/python", "-m", "awslambdaric" ]  
CMD ["lambda_code.function_name"]

Example#

ARG FUNCTION_DIR="/function"
  
FROM tensorflow/tensorflow:2.4.3 as DEV  
ARG FUNCTION_DIR  
RUN mkdir -p ${FUNCTION_DIR}
## copies python code into container's FUNCTION_DIR
COPY lambda_code.py ${FUNCTION_DIR} 
## copies lambda_requirements.txt into container's requirements.txt
COPY lambda_requirements.txt ./requirements.txt  
## copies dataset into container's FUNCTION_DIR/dataset/
COPY dataset ${FUNCTION_DIR}/dataset/  
RUN pip install --no-cache-dir --upgrade pip && \  
    pip install -r requirements.txt --target ${FUNCTION_DIR}  
WORKDIR ${FUNCTION_DIR}  
ENTRYPOINT [ "python", "-m", "awslambdaric" ]  
CMD ["lambda_code.function_name"]

Setting Up the Lambda in CDK#

To create a Lambda from a Dockerfile in CDK, use cdk.aws-lambda.DockerImageFunction when defining your Lambda:

dockerized_lambda = _lambda.DockerImageFunction(  
    self,  
    f"dockerized-lambda-{stage}",  
    code=_lambda.DockerImageCode.from_image_asset(  
        "./dockerfile_directory", target="DEV"  
    ),  
)

Sources#