Create Lambda with Container Based Runtime

   Go back to the Task List

  « 3: Launch Cloud9 Environment    5: Create and Run Lambda Function »

4: Create Container Image

You create a container image and then upload to the AWS ECR repository. The image is used as the runtime for the Lambda Function in the next step.

  1. In AWS Cloud9 IDE, you create a new file app.py and save it with the following code. It is the handler code for the Lambda Function. It is not doing much and just returning a success message.

    import json
    
    def handler(event, context):
        body = {
            "message": "You reached to the container runtime"
        }
           
        response = {
            "statusCode": 200,
            "body": json.dumps(body)
        }
        return response
    

    `

    Cloud9

  2. In AWS Cloud9 IDE, Create another file named Dockerfile which holds the docker script for the image.

    FROM public.ecr.aws/lambda/python:3.8
    ADD app.py /var/task/
    CMD [ "app.handler" ]
    

    `

    Cloud9

  3. The code above is very simple. You use public.ecr.aws/lambda/python:3.8 as the base image and add the handle file app.py to the /var/task/ folder. Finally the app handler is started.

  4. The files are ready. You will use the push commands from the AWS ECR repository to create and upload the container image. Run the following command in the console to authenticate to the ECR registry. Replace with the code of the region you are using for the workshop. Replace with the account number of the AWS account you are using.

        aws ecr get-login-password --region <Region-Code> | docker login --username AWS --password-stdin <Account-Number>.dkr.ecr.<Region-Code>.amazonaws.com
    

    `

    Cloud9

  5. Next you run the following command in the console to create the container image. There is a dot in the end of the command, copy the complete command.

     docker build -t dojorepo .
    

    ` Cloud9

  6. Next you run the following command to tag the image so you can push the image to the repository. Replace with the code of the region you are using for the workshop. Replace with the account number of the AWS account you are using.

     docker tag dojorepo:latest <Account-Number>.dkr.ecr.<Region-Code>.amazonaws.com/dojorepo:latest
    

    `

  7. Finally, run the following command to push the image to the AWS ECR repository. Replace with the code of the region you are using for the workshop. Replace with the account number of the AWS account you are using.

     docker push <Account-Number>.dkr.ecr.<Region-Code>.amazonaws.com/dojorepo:latest
    

    ` Cloud9

  8. The Docker image has been pushed to the AWS ECR repository. You can verify it by opening the dojorepo repository in the AWS ECS console.

    Cloud9

  9. The container image is ready. Time to configure Lambda Function using this container image as the runtime.