Aws
AwsIntermediate

AWS Lambda Container Support: A Comprehensive Guide

DevHub Team
5 min read
LambdaContainersDockerServerless

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:

  • Use familiar container tooling
  • Package large dependencies
  • Standardize deployment artifacts
  • Reuse container images across services
  • ``mermaid

    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

    `

    $1

    $1

    AWS provides optimized base images for Lambda:

    `dockerfile

    Python example

    FROM public.ecr.aws/lambda/python:3.9

    Copy function code

    COPY app.py ${LAMBDA_TASK_ROOT}

    Install dependencies

    COPY requirements.txt .

    RUN pip install -r requirements.txt

    Set the handler

    CMD [ "app.handler" ]

    `

    $1

    Creating a custom runtime:

    `dockerfile

    Custom runtime example

    FROM public.ecr.aws/amazonlinux/amazonlinux:2

    Install required dependencies

    RUN yum install -y python39 pip

    Set up Lambda Runtime Interface Emulator

    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 function code

    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" ]

    `

    $1

    $1

    `bash

    Build the image

    docker build -t my-lambda-function .

    Tag the image

    docker tag my-lambda-function:latest ${AWS_ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com/my-lambda-function:latest

    Push to ECR

    docker push ${AWS_ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com/my-lambda-function:latest

    `

    $1

    Using AWS CLI:

    `bash

    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

    `

    Using AWS CDK:

    `typescript

    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),

    });

    `

    $1

    $1

    `dockerfile

    Multi-stage build example

    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" ]

    `

    $1

    Using layers with container images:

    `yaml

    SAM template example

    Resources:

    MyFunction:

    Type: AWS::Serverless::Function

    Properties:

    PackageType: Image

    ImageUri: my-function.ecr.repo

    ImageConfig:

    Command: ["app.handler"]

    Layers:

    - !Ref MyLayer

    `

    $1

    $1

    `python

    app.py

    import os

    import json

    Global scope initialization

    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)

    }

    `

    $1

    Memory vs performance trade-offs:

    `yaml

    Resource configuration example

    Resources:

    ContainerFunction:

    Type: AWS::Lambda::Function

    Properties:

    MemorySize: 1024 # Optimal for most container workloads

    Timeout: 30

    EphemeralStorage:

    Size: 512 # MB

    `

    $1

    $1

    `python

    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

    `

    $1

    `python

    from aws_xray_sdk.core import patch_all

    import boto3

    patch_all()

    def handler(event, context):

    # Function is automatically traced

    pass

    `

    $1

    $1

    Enable ECR image scanning:

    `bash

    aws ecr put-image-scanning-configuration \

    --repository-name my-lambda-function \

    --image-scanning-configuration scanOnPush=true

    `

    $1

    `json

    {

    "Version": "2012-10-17",

    "Statement": [

    {

    "Effect": "Allow",

    "Action": [

    "ecr:GetDownloadUrlForLayer",

    "ecr:BatchGetImage"

    ],

    "Resource": "arn:aws:ecr:region:account-id:repository/my-lambda-function"

    }

    ]

    }

    `

    $1

    $1

    `dockerfile

    Optimize image size

    FROM public.ecr.aws/lambda/python:3.9-slim

    Only install production dependencies

    COPY requirements.txt .

    RUN pip install --no-cache-dir -r requirements.txt

    COPY app.py ${LAMBDA_TASK_ROOT}

    CMD [ "app.handler" ]

    `

    $1

    Optimize memory and timeout settings:

    `yaml

    Resources:

    OptimizedFunction:

    Type: AWS::Lambda::Function

    Properties:

    MemorySize: 1024

    Timeout: 30

    EphemeralStorage:

    Size: 512

    Environment:

    Variables:

    POWERTOOLS_SERVICE_NAME: MyService

    LOG_LEVEL: INFO

    ``

    $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)

  • [Understanding AWS Lambda: Use Cases, Setup, and Best Practices](/posts/aws/understanding-lambda) - Learn the fundamentals of AWS Lambda
  • [AWS App Runner: Simplified Container and Source Code Deployment](/posts/aws/app-runner) - Explore another serverless container deployment option
  • [AWS ECS vs EKS in 2024: A Comprehensive Comparison](/posts/aws/ecs-vs-eks-2024) - Compare container orchestration services
  • [AWS Graviton3: Next-Generation ARM-based Computing](/posts/aws/graviton3) - Learn about optimizing Lambda with Graviton3 processors
  • 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.