Local Prerequisites

Docker python 3.6+ (3.8 will be used in this setup)

AWS Prerequisites

AWS Access/Secret keys or AWS SSO AWS ECR AWS Lambda

Setup

Make a local directory and set up local files

mkdir test-python-lambda && cd test-python-lambda
touch Dockerfile build.sh requirements.txt app.py
python -m venv venv
source venv/bin/activate

requirements

Edit your requirements.txt with your dependencies. In my case, I’m including the lambda runtime / xray sdk, as well as boto3/botocore.

# requirements.txt
awslambdaric
aws_xray_sdk
boto3
botocore

docker

Be sure docker is started, configure your Dockerfile

# Dockerfile
FROM public.ecr.aws/lambda/python:3.8

ENV PYTHONDONTWRITEBYTECODE 1

RUN pip install --upgrade pip
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt

COPY app.py ./
CMD ["app.handler"]

python app

Configure your python app, using handler(...) as the entrypoint.

# app.py

import json

def some_function_that_does_something():
    return True

def handler(event, context):
   response = some_function_that_does_something()
    return {
        'statusCode': 200,
        'body': json.dumps('Hello World!')
    }

Set up ECR and a local build script

See AWS guide to configure ECR - name it test-python-lambda.

After setup, copy out the docker push commands and configure a local build script you can call.

# build.sh
#!/bin/bash

aws ecr get-login-password --region us-east-1  | docker login --username AWS --password-stdin <your account id>.dkr.ecr.<your region>.amazonaws.com
docker build -t test-python-lambda .
docker tag test-python-lambda:latest <your account id>.dkr.ecr.<your region>.amazonaws.com/test-python-lambda:latest
docker push <your account id>.dkr.ecr.<your region>.amazonaws.com/test-python-lambda:latest

Note: If you’re using AWS SSO or a separate aws profile in ~/.aws/config, you can add --profile <your profile> if you want the aws ecr get-login-password command to utilize that profile.

Run the build, and configure Lambda to use this image

chmod +x build.sh
./build.sh

If there weren’t any errors, you should be able to configure a new lambda with the container you deployed to ECR.