Full example of Lambda Docker container?

435 Views Asked by At

I am looking for a full round-trip example of:

  1. creating a custom docker image (that lambda will use - I have a working Dockerfile)
  2. pushing the image to the AWS container registry
  3. Having AWS lambda manually invoked that will pull the image from the AWS container registry (and instantiate the container)
  4. and invoke a task in the container that will run (a specific bash script)
  5. then have all resources released (container removed, lambda completes), after container runs

Is this possible? Is there an example anywhere?

1

There are 1 best solutions below

0
On

I managed to deploy a Lambda for instantiating Docker containers in this manner:

0.Make sure Docker Desktop is installed on your PC and is running (https://docs.docker.com/engine/install/)

1.Set up your AWS account credentials by running aws configure in the terminal

2.Prepare a python script, named main.py. Include an output function in your script similar to the following:

def lambda_handler(event, context):
    <your code here>
    responseBody = <some output from your code>
    return {
        "statusCode": 200,
        "body": responseBody
        }

3.Prepare a list of python modules you need to have installed inside the container and put them in a file named requirements.txt.

4.Prepare a SAM template, named template.yaml, of a similar format to:

  Transform: 'AWS::Serverless-2016-10-31'
  Description: An AWS Serverless Specification template for deploying lambda functions using a Docker container image
  Resources:
    Function:
      Type: 'AWS::Serverless::Function'
      Properties:
        FunctionName: <lambda function name>
        Description: <description about lambda function>
        PackageType: Image
        Timeout: 60
      Metadata:
        Dockerfile: Dockerfile
        DockerContext: .

(Refer to https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-function.html for a list of other properties you might need for your lambda function.)

5.Prepare a Dockerfile in a similar format:

FROM public.ecr.aws/lambda/python:3.7
WORKDIR /app
COPY main.py .
COPY requirements.txt .
RUN pip install -r requirements.txt
CMD [ "/app/main.lambda_handler" ]
  1. In the terminal, run sam build -u to build the Docker image.

  2. In the terminal, run sam deploy -g then follow on-screen steps to generate a configuration file called samconfig.toml and deploy the lambda function and ECR Docker image to AWS.

  3. Once deployed, in the Lambda console on the AWS site you can test the new lambda function. As the lambda has been deployed as a container image, each time it is invoked the Docker container will be instantiated.