Skip to content

Instantly share code, notes, and snippets.

@adamjkeller
Last active October 29, 2022 04:34
Show Gist options
  • Save adamjkeller/f6712b3d9681e1cac2d836614db92a90 to your computer and use it in GitHub Desktop.
Save adamjkeller/f6712b3d9681e1cac2d836614db92a90 to your computer and use it in GitHub Desktop.
Lambda Docker Image Support CDK Sample

Lambda container image support

Docs

https://docs.aws.amazon.com/lambda/latest/dg/images-create.html

Dockerfile

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

RUN pip install wikipedia

# Copy function code
COPY demo.py ${LAMBDA_TASK_ROOT}

# Set the CMD to your handler (could also be done as a parameter override outside of the Dockerfile)
CMD [ "demo.handler" ]

demo.py

#!/usr/bin/env python3

import wikipedia

def handler(event, context):
    if event:
        result = wikipedia.page(event.get('wiki', 'los angeles'))
        return "{}".format(result.summary)
    else:
        return "Hello from CFTC! You didn't tell me to look anything up, much sad."

Build:

docker build -t test .

Run:

docker run -p 8080:8080 test

Test:

curl -XPOST "http://localhost:9000/2015-03-31/functions/function/invocations" -d '{"wiki": "los angeles"}'

CDK Code

from aws_cdk import core, aws_lambda


class LambdaContainerImageSupportStack(core.Stack):

    def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # I <3 Lambda
        self.lambda_function = aws_lambda.Function(
            self, "ContainerImageDemo",
            code=aws_lambda.Code.from_asset_image(directory="./", exclude=["cdk.out"]),
            handler=aws_lambda.Handler.FROM_IMAGE,
            runtime=aws_lambda.Runtime.FROM_IMAGE,
            function_name="cftc_wiki_lambda"
        )

app = core.App()
LambdaContainerImageSupportStack(app, "lambda-container-image-support")
app.synth()

Deploy Lambda and container image to aws

cdk deploy --require-approval never

Console

Create test event, json '{"wiki": "amazon web services"}'

CLI

aws lambda invoke --function-name cftc_wiki_lambda --payload '{"wiki": "amazon web services"}' lambda_out

@Sabiner
Copy link

Sabiner commented Oct 29, 2022

docker run with port 8080, but curl with 9000

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment