TL;DR
Learn how to leverage container images with AWS Lambda, including best practices, optimization techniques, and real-world examples
AWS Lambda Container Support: A Comprehensive Guide
AWS Lambda's container image support allows you to package and deploy Lambda functions as container images up to 10GB in size. This guide explores how to effectively use containers with Lambda.
$1
Lambda container support enables you to:
`` graph TB
subgraph Container["Container Image"]
direction TB
Base["Base Image"]
Runtime["Lambda Runtime"]
Code["Function Code"]
Deps["Dependencies"]
end
subgraph Lambda["Lambda Service"]
direction TB
API["Lambda API"]
Exec["Execution Environment"]
end
Container --> Lambda
classDef aws fill:#FF9900,stroke:#232F3E,color:#232F3E
classDef container fill:#0DB7ED,stroke:#384d54,color:#384d54
class Lambda aws
class Container container
mermaid
`
$1
$1
AWS provides optimized base images for Lambda:
` FROM public.ecr.aws/lambda/python:3.9 COPY app.py ${LAMBDA_TASK_ROOT} COPY requirements.txt .
RUN pip install -r requirements.txt CMD [ "app.handler" ]
dockerfile
`Python example
Copy function code
Install dependencies
Set the handler
$1
Creating a custom runtime:
` FROM public.ecr.aws/amazonlinux/amazonlinux:2 RUN yum install -y python39 pip RUN curl -Lo /usr/local/bin/aws-lambda-rie https://github.com/aws/aws-lambda-runtime-interface-emulator/releases/latest/download/aws-lambda-rie
RUN chmod +x /usr/local/bin/aws-lambda-rie COPY app.py ${LAMBDA_TASK_ROOT}
COPY requirements.txt .
RUN pip install -r requirements.txt ENTRYPOINT [ "/usr/local/bin/aws-lambda-rie" ]
CMD [ "python3", "app.py" ]
dockerfile
`Custom runtime example
Install required dependencies
Set up Lambda Runtime Interface Emulator
Copy function code
$1
$1
` docker build -t my-lambda-function . docker tag my-lambda-function:latest ${AWS_ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com/my-lambda-function:latest docker push ${AWS_ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com/my-lambda-function:latest
bash
`Build the image
Tag the image
Push to ECR
$1
Using AWS CLI:
` aws lambda create-function \
--function-name my-container-function \
--package-type Image \
--code ImageUri=${AWS_ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com/my-lambda-function:latest \
--role arn:aws:iam::${AWS_ACCOUNT_ID}:role/lambda-role
bash
`
Using AWS CDK:
` import * as lambda from 'aws-cdk-lib/aws-lambda'; const containerFunction = new lambda.DockerImageFunction(this, 'ContainerFunction', {
code: lambda.DockerImageCode.fromEcr(repository, {
tag: 'latest',
}),
memorySize: 1024,
timeout: Duration.seconds(30),
});
typescript
`
$1
$1
` FROM public.ecr.aws/lambda/python:3.9 AS builder COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt -t /asset FROM public.ecr.aws/lambda/python:3.9
COPY --from=builder /asset ${LAMBDA_TASK_ROOT}
COPY app.py ${LAMBDA_TASK_ROOT} CMD [ "app.handler" ]
dockerfile
`Multi-stage build example
$1
Using layers with container images:
` Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
PackageType: Image
ImageUri: my-function.ecr.repo
ImageConfig:
Command: ["app.handler"]
Layers:
- !Ref MyLayer
yaml
`SAM template example
$1
$1
` import os
import json heavy_client = initialize_heavy_client() def handler(event, context):
# Use pre-initialized client
result = heavy_client.process(event)
return {
'statusCode': 200,
'body': json.dumps(result)
}
python
`app.py
Global scope initialization
$1
Memory vs performance trade-offs:
` Resources:
ContainerFunction:
Type: AWS::Lambda::Function
Properties:
MemorySize: 1024 # Optimal for most container workloads
Timeout: 30
EphemeralStorage:
Size: 512 # MB
yaml
`Resource configuration example
$1
$1
` import logging logger = logging.getLogger()
logger.setLevel(logging.INFO) def handler(event, context):
logger.info(f"Container function invoked with event: {event}")
# Function logic here
python
`
$1
` from aws_xray_sdk.core import patch_all
import boto3 patch_all() def handler(event, context):
# Function is automatically traced
pass
python
`
$1
$1
Enable ECR image scanning:
` aws ecr put-image-scanning-configuration \
--repository-name my-lambda-function \
--image-scanning-configuration scanOnPush=true
bash
`
$1
` {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ecr:GetDownloadUrlForLayer",
"ecr:BatchGetImage"
],
"Resource": "arn:aws:ecr:region:account-id:repository/my-lambda-function"
}
]
}
json
`
$1
$1
` FROM public.ecr.aws/lambda/python:3.9-slim COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt COPY app.py ${LAMBDA_TASK_ROOT}
CMD [ "app.handler" ]
dockerfile
`Optimize image size
Only install production dependencies
$1
Optimize memory and timeout settings:
` Resources:
OptimizedFunction:
Type: AWS::Lambda::Function
Properties:
MemorySize: 1024
Timeout: 30
EphemeralStorage:
Size: 512
Environment:
Variables:
POWERTOOLS_SERVICE_NAME: MyService
LOG_LEVEL: INFO
yaml
``
$1
Common issues and solutions:
1. Image Pull Errors
- Check ECR permissions
- Verify image tags
- Validate repository access
2. Container Runtime Issues
- Check Lambda runtime logs
- Verify entry point configuration
- Validate environment variables
$1
1. Image Management
- Use multi-stage builds
- Implement proper tagging
- Regular security scanning
- Clean up unused images
2. Performance
- Optimize cold starts
- Configure appropriate memory
- Use layer caching
- Monitor execution metrics
3. Security
- Implement least privilege
- Regular vulnerability scanning
- Secure secrets management
- Enable audit logging
$1
1. [AWS Lambda Container Image Support](https://docs.aws.amazon.com/lambda/latest/dg/lambda-images.html)
2. [Container Image Security](https://docs.aws.amazon.com/lambda/latest/dg/security-container-images.html)
3. [Lambda Runtime Interface](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-api.html)
4. [ECR Best Practices](https://docs.aws.amazon.com/AmazonECR/latest/userguide/best-practices.html)
$1
Why This Matters
Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.
Trade-offs to Consider
Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.
When NOT to Use This
Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.
Decision Framework
Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.