AWS

How to Build and Deploy Python Libraries for AWS Lambda Layers

Lambda Layers let you package Python libraries once and share them across multiple Lambda functions. Instead of bundling dependencies into every deployment package, you…

How to Build and Deploy Python Libraries for AWS Lambda Layers
Share:

How to Build and Deploy Python Libraries for AWS Lambda Layers

6 min read
2.8K views

Lambda Layers let you package Python libraries once and share them across multiple Lambda functions. Instead of bundling dependencies into every deployment package, you build a layer with your libraries and attach it to any function that needs them. This guide shows you how to build Python Lambda Layers using Docker (to match the Lambda runtime) and deploy them with the AWS CLI.

The examples here are run on WSL2 Ubuntu in Windows, but they work the same on any Linux or macOS system.

Advertisement

Prerequisites

  • AWS CLI v2 installed and configured with credentials
  • Docker installed and running. For WSL access problems, see Docker daemon permission troubleshooting
  • ZIP tooling (sudo apt install zip on Ubuntu) and IAM permissions for lambda:PublishLayerVersion. Attaching a layer also needs lambda:GetFunctionConfiguration, lambda:UpdateFunctionConfiguration, and access to the layer version (lambda:GetLayerVersion). The optional S3 path needs bucket write/read access

Why Use Docker to Build Layers?

Some Python packages (like pandas, numpy, or psycopg2) include compiled C extensions. If you pip install them on your Mac or Windows machine, the binaries won’t work inside Lambda’s Amazon Linux environment. Match the container’s Python version, architecture, and native dependencies to the function. The Lambda runtime image does not include every compiler or external library: the binary-only example below fails if a compatible wheel is unavailable. For extra ODBC libraries and registration, see the PyODBC Lambda packaging guide.

Step 1: Set Up the Project

Create a directory for your layer build:

mkdir -p lambda-layer
cd lambda-layer

Create a requirements.txt with the libraries your functions need. This minimal example uses Requests; review and test package updates before changing a deployed layer:

Advertisement
requests==2.34.2

This pins the direct dependency, but its transitive dependencies also need locking for reproducible builds. Resolve and record the complete dependency set for the target Python version and architecture, and reuse the reviewed lock file. AWS includes Boto3 in its Python runtimes, but recommends packaging all dependencies, including Boto3 when used, to avoid version misalignment. Requests brings dependencies such as urllib3 that can overlap the SDK: if your function uses Boto3, include a compatible, pinned Boto3 dependency set rather than mixing an arbitrary layer version with the runtime SDK.

Step 2: Install Dependencies with Docker

Lambda expects layer contents in a python/ directory. Use Docker to install the packages into the correct structure:

mkdir -p python
docker run --rm --platform linux/amd64 \
  --user "$(id -u):$(id -g)" -e HOME=/tmp \
  --entrypoint /var/lang/bin/python \
  -v "$(pwd)":/var/task \
  public.ecr.aws/lambda/python:3.12 \
  -m pip install -r /var/task/requirements.txt \
  -t /var/task/python --only-binary=:all: --no-cache-dir
  • public.ecr.aws/lambda/python:3.12: official Python 3.12 Lambda image. Match the function version and architecture; pin the image digest as well when reproducing a build
  • -v "$(pwd)":/var/task: mounts your current directory into the container
  • -t /var/task/python: installs packages into the python/ directory (required by Lambda)
  • --entrypoint /var/lang/bin/python overrides Lambda’s handler entrypoint. --user keeps host files owned by your Linux/WSL user. --only-binary=:all: requires compatible wheels; --no-cache-dir disables pip caching

Use a fresh build directory for each dependency set, Python version, and architecture; do not mix old package files into a new build. For arm64 functions, run the same command with --platform linux/arm64 and publish with --compatible-architectures arm64. Docker must support that platform natively or through emulation. Labeling an x86_64 build as arm64 does not convert its binaries.

Change the Lambda image tag and publication runtime together to match the target function, for example 3.12, 3.13, or 3.14. Python 3.12 and later use AL2023; rebuilding for a different Python version may require different wheels. Validate against AWS’s Python layer requirements.

Docker-free option: install compatible wheels

On WSL2 Ubuntu, create a virtual environment so the build does not modify the system Python. Install into a separate fresh layer project. Cross-platform wheel selection must specify the target Python implementation, version, ABI, and architecture:

sudo apt install -y python3-venv
python3 -m venv .venv
.venv/bin/python -m pip install -r requirements.txt \
  --platform manylinux2014_x86_64 --implementation cp \
  --python-version 3.12 --abi cp312 --only-binary=:all: \
  --target python --no-cache-dir

For arm64, replace the platform with manylinux2014_aarch64. Match Python/ABI flags to the function. If no compatible wheel exists, this command should fail; do not remove the platform constraints and accidentally package host binaries. Use a suitable Linux build environment with the required compiler and libraries instead.

Before zipping, check imports against the intended runtime image when Docker is available. For the Requests example:

docker run --rm --platform linux/amd64 \
  --entrypoint /var/lang/bin/python \
  -e PYTHONPATH=/opt/python -v "$(pwd)/python":/opt/python:ro \
  public.ecr.aws/lambda/python:3.12 \
  -c "import requests; print(requests.__version__)"

Step 3: Create the ZIP Archive

zip -r layer.zip python/

The ZIP must contain the python/ directory at the root. Lambda extracts the layer and adds python/ to the Python path automatically.

Check the combined size: the function deployment package and all attached layers share the 250 MB unzipped limit. The direct-upload ZIP limit is 50 MB. For larger archives, upload to an S3 bucket in the function’s Region and use --content S3Bucket=...,S3Key=...; an S3 upload does not bypass the unzipped limit.

Step 4: Publish the Layer

aws lambda publish-layer-version \
  --layer-name my-python-libs \
  --zip-file fileb://layer.zip \
  --compatible-runtimes python3.12 \
  --compatible-architectures x86_64 \
  --region ap-southeast-1
  • --layer-name: a descriptive name for the layer
  • --compatible-runtimes: which Python versions this layer works with (you can list multiple)
  • --compatible-architectures: use x86_64 or arm64 depending on your Lambda function’s architecture

The command returns the layer ARN and version number. Save the ARN: you’ll need it to attach the layer to your functions.

For layers larger than 50 MB (zipped)

Upload to S3 first, then reference it:

aws s3 cp layer.zip s3://your-deploy-bucket/layers/layer.zip

aws lambda publish-layer-version \
  --layer-name my-python-libs \
  --content S3Bucket=your-deploy-bucket,S3Key=layers/layer.zip \
  --compatible-runtimes python3.12 \
  --compatible-architectures x86_64 \
  --region ap-southeast-1

Step 5: Attach the Layer to a Lambda Function

# Review the current attachments before changing them.
aws lambda get-function-configuration --function-name your-function \
  --query 'Layers[].Arn' --region your-region --profile dev

# Replace this placeholder with the versioned ARN returned by publish.
LAYER_VERSION_ARN=YOUR_LAYER_VERSION_ARN
aws lambda update-function-configuration \
  --function-name your-function \
  --layers "$LAYER_VERSION_ARN" \
  --region your-region --profile dev

Use the exact versioned ARN returned in Step 4. The --layers list replaces all current layer attachments. If the function already has layers, include every ARN you intend to retain alongside the new one. Review their ordering and dependency overlap before updating. Each publish creates a new version; it does not automatically update functions using an older version.

You can also attach layers in the Lambda console under Function > Layers > Add a layer.

Verify the Layer Works

Create a quick test function that imports one of the layer’s packages:

import requests

def lambda_handler(event, context):
    return {"statusCode": 200, "body": requests.__version__}

A successful import verifies this package, not every native extension or external library in the layer. Test all required imports in the matching runtime and then in a test Lambda. For ModuleNotFoundError or native loader errors, check that:

  • The ZIP contains python/ at the root (not nested inside another directory)
  • The runtime version matches between the layer and the function
  • The architecture matches (x86_64 vs arm64)

For more on writing Lambda functions, see Understanding Lambda’s Event and Context Parameters.

Conclusion

Building Python Lambda Layers with an explicit runtime and architecture reduces compatibility problems; native libraries still need validation. The workflow is: pip install into python/ using the official Lambda image, zip it, and publish with the AWS CLI. Once published, any function in your account can use the layer.

For organizing your Lambda code alongside layers, check out How to Structure Your Python Projects for AWS Lambda, APIs, and CLI Tools.

Recommended for Linux builders

Contabo VPS hosting for Linux projects

Run Linux servers, automation tools, and self-hosted apps on a Contabo VPS with generous resources and predictable pricing.

Our customers sayExcellent4.6 out of 5 based on 11,008 reviews Trustpilot

Some links are affiliate links. This may earn LinuxBeast a commission at no extra cost to you.

Privacy settings

Choose which privacy controls to open.

Opening these controls does not change your saved choices.