Sub topic 11
Packaging code: zip archives, layers and container images
Lambda needs your code and its dependencies in a form it can unpack into an execution environment. You can supply them as a zip archive, as one or more layers added to a zip function, or as a container image. This chapter covers how each option works, its limits, and how to choose.
This chapter assumes you can write a handler and configure a function (memory, timeout, execution role). It also assumes you have used the AWS CLI and have a basic grasp of Python packaging. The examples use Python 3.12, but the mechanics are the same for other runtimes.
The two package types
Every function has a package type, set when you create it. It cannot be changed afterward.
- Zip (
Zip): you upload an archive. You choose a managed runtime such aspython3.12, and aHandlersuch asapp.handler. - Image (
Image): you point Lambda at a container image in Amazon ECR. The image carries the runtime, soRuntimeandHandlerare not set on the function. The handler comes from the image'sCMD.
| Property | Zip | Layers (zip only) | Container image |
|---|---|---|---|
| Size limit | 50 MB zipped upload, 250 MB unzipped including layers | Counts toward the 250 MB unzipped total | Up to 10 GB uncompressed |
| Runtime | Managed by AWS | Managed by AWS | You choose the base image |
| Dependency sharing | Copied into each function | Shared across functions | Shared through base images |
| Build tool | zip or SAM | zip or SAM | Docker or compatible builder |
| Storage | Lambda, or S3 for large uploads | Lambda | ECR, same Region as the function |
Zip archives
A zip package must have your handler file at the root of the archive, or at the path your Handler setting names. A common mistake is zipping the parent folder, so the file ends up at src/app.py and Lambda reports Unable to import module 'app'.
Building a zip with dependencies
Python dependencies must be inside the archive. The libraries in the managed runtime include boto3, but you should not rely on its version for anything else.
mkdir -p build
pip install \
--requirement requirements.txt \
--target build/ \
--platform manylinux2014_x86_64 \
--implementation cp \
--python-version 3.12 \
--only-binary=:all:
cp src/app.py build/
cd build && zip -r ../function.zip . && cd ..
aws lambda update-function-code \
--function-name orders-function \
--zip-file fileb://function.zipThe --platform and --only-binary flags matter. Packages with compiled code (numpy, cryptography, psycopg2) ship platform-specific wheels. If you build on macOS or Windows without these flags, you package binaries that fail at import time on Lambda's Amazon Linux. Use manylinux2014_aarch64 if the function runs on arm64.
Size limits and S3
The direct upload limit is 50 MB zipped. For larger archives, upload to S3 and pass --s3-bucket and --s3-key instead. The unzipped limit of 250 MB still applies, and it includes every layer. Lambda rejects the deployment if the total exceeds it.
Layers
A layer is a zip archive that Lambda extracts into /opt in the execution environment. Layers hold libraries, a custom runtime, or shared code that several functions use.
Key facts:
- A function can use up to five layers. All layers and the function code together must fit in 250 MB unzipped.
- Each publish creates a new, immutable layer version. A function references a specific version by ARN, such as
arn:aws:lambda:us-east-1:123456789012:layer:deps:3. - Layers merge in the order you list them. If two layers contain the same path, the later layer wins.
- Layers can be shared with other accounts or made public through layer permissions.
- Layers apply only to zip functions. For image functions, put the content in the image.
Directory layout
The runtime only finds layer content if it is in a path it already searches. For Python, that is python/ at the top of the layer archive. For Node.js it is nodejs/node_modules.
mkdir -p layer/python
pip install \
--requirement layer-requirements.txt \
--target layer/python \
--platform manylinux2014_x86_64 \
--implementation cp \
--python-version 3.12 \
--only-binary=:all:
(cd layer && zip -r ../deps-layer.zip python)
aws lambda publish-layer-version \
--layer-name deps \
--zip-file fileb://deps-layer.zip \
--compatible-runtimes python3.12 \
--compatible-architectures x86_64The command prints the new version ARN. Attach it with aws lambda update-function-configuration --function-name orders-function --layers <arn>. Note that --layers replaces the whole list, so include every layer you still want.
What layers do and do not do
Layers help you separate rarely changing dependencies from frequently changing code. Your function zip stays small, so uploads are quick. They also let several functions share one copy of a dependency set.
Layers do not make the function faster or smaller at runtime. Lambda still unpacks the layer contents into every execution environment, and the code is counted in the 250 MB limit. Layers also tie the function to a layer version. Updating a layer means publishing a new version and updating each function that uses it. Existing functions keep using the old version until you do.
Container images
A container image gives you full control over the runtime and system libraries. Choose it when your package exceeds 250 MB (machine learning models, large native libraries), when you need system packages, or when your team already builds and scans containers.
Start from an AWS base image, which includes the Lambda Runtime Interface Client. You can also use another base image and add the client yourself.
FROM public.ecr.aws/lambda/python:3.12
COPY requirements.txt ${LAMBDA_TASK_ROOT}/
RUN pip install --no-cache-dir -r ${LAMBDA_TASK_ROOT}/requirements.txt
COPY src/app.py ${LAMBDA_TASK_ROOT}/
CMD ["app.handler"]LAMBDA_TASK_ROOT is /var/task, where Lambda looks for code. CMD takes the place of the Handler setting. Copy requirements.txt and install before copying your source, so Docker's build cache keeps the dependency layer when only code changes.
Build, push and create the function:
aws ecr create-repository --repository-name orders-function
aws ecr get-login-password | docker login --username AWS \
--password-stdin 123456789012.dkr.ecr.us-east-1.amazonaws.com
docker build -t orders-function .
docker tag orders-function:latest \
123456789012.dkr.ecr.us-east-1.amazonaws.com/orders-function:v1
docker push 123456789012.dkr.ecr.us-east-1.amazonaws.com/orders-function:v1
aws lambda create-function \
--function-name orders-function \
--package-type Image \
--code ImageUri=123456789012.dkr.ecr.us-east-1.amazonaws.com/orders-function:v1 \
--role arn:aws:iam::123456789012:role/orders-function-roleYou can test locally. The base image includes a runtime interface emulator, so docker run -p 9000:8080 orders-function accepts invocations at http://localhost:9000/2015-03-31/functions/function/invocations.
Gotchas with images
- Tags are resolved at deploy time. Lambda converts the tag to an image digest when you create or update the function. Pushing a new image to
v1later does not change the running function. Runupdate-function-code --image-uriagain, and prefer unique tags or digests. - The image must be in ECR in the same Region. The function's creator needs ECR pull permissions.
- Image layers are cached. Lambda optimizes pulls, so a large image does not always mean a proportionally slow cold start. Measure it before assuming.
- You maintain the base. With managed runtimes, AWS patches the runtime. With images, you rebuild and redeploy to get security fixes.
Packaging with SAM
SAM can build and deploy all three styles. It takes over the tricky parts, including dependency installation and layer layout.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
DepsLayer:
Type: AWS::Serverless::LayerVersion
Properties:
LayerName: deps
ContentUri: layer/
CompatibleRuntimes:
- python3.12
Metadata:
BuildMethod: python3.12
OrdersFunction:
Type: AWS::Serverless::Function
Properties:
Handler: app.handler
Runtime: python3.12
CodeUri: src/
Layers:
- !Ref DepsLayer
ImageFunction:
Type: AWS::Serverless::Function
Properties:
PackageType: Image
ImageConfig:
Command: ["app.handler"]
Metadata:
Dockerfile: Dockerfile
DockerContext: ./image
DockerTag: v1Here ContentUri: layer/ holds a requirements.txt, and BuildMethod tells SAM to install it into the correct python/ path. Run sam build --use-container to build inside a Lambda-like container, which avoids platform mismatches for native dependencies. Then sam deploy uploads artifacts to S3 or ECR and publishes a new layer version whenever the content changes.
Choosing a package type
- Start with a zip. It is the simplest and has the fewest moving parts.
- Add a layer when several functions share a heavy dependency set, or when you want fast code-only uploads.
- Switch to an image when you exceed 250 MB, need OS-level packages, or want your container tooling and scanning.
Exercise
A Python function deploys successfully with a layer, but the first invocation fails with "No module named 'requests'". The layer zip contains requests/ and its dependencies at the root. What is wrong, and how do you fix it?
Show answer
Lambda's Python runtime only searches /opt/python (and /opt/python/lib/python3.12/site-packages) for layer content. With the packages at the zip root, they land in /opt/requests, which is not on the path. Rebuild the layer so the packages sit under a top-level python/ directory, publish a new layer version, and update the function to use the new version ARN.
Exercise
You push a fixed image to the tag latest in ECR, but your Lambda function still runs the old code. Why, and what should you do?
Show answer
Lambda resolves the image tag to a digest when the function code is created or updated, so later pushes to the same tag are ignored. Run aws lambda update-function-code --function-name <name> --image-uri <uri> again to pick up the new image. To avoid this, tag releases uniquely (for example with a version or commit hash) and deploy by that tag.