Lambda and Docker
Introduction
We saw in previous classes why Docker is important for ML. In this class, we will see how to create Docker images and deploy Lambda functions from them.
Create Source Code
Consider the following lambda function code:
import sys
def hello_from_docker(event, context):
return {
"created_by": "your name",
"message": "Hello World!",
"version": sys.version
}
Our goal is to deploy this function with Docker + Lambda.
Important!
Create a folder for today's class and store the suggested files in the root of this folder
Question 1
Question 2
Create Image
Question 3
Let's name the image lambda-ex-image
and give it the test
tag:
Test locally
Before deploying, let's test the function locally.
Start the Docker image with the docker run
command:
Let's make a request with:
Question 4
If that doesn't work, try with double quotes:
Tip! 1
If you prefer, make the request from Python with the requests
library!
Click to see
import requests
import json
url = "http://localhost:9500/2015-03-31/functions/function/invocations"
data = {}
response = requests.post(url, json=data, timeout=2)
response_json = response.json()
print(f"Status code: {response.status_code}")
print("Response:")
print(json.dumps(response_json, indent=4))
Container Registry
The Amazon Elastic Container Registry (ECR) is a fully managed service that allows you to store, manage, and deploy container images. With ECR, you can securely store and manage your Docker container images.
Let's upload our image to ECR. But first, we need to create a container repository:
Atention!
Change the repository_name
variable.
Provide a name in the pattern test1-mlops-<INSPER_USERNAME>
import boto3
import os
from dotenv import load_dotenv
load_dotenv()
# Provide a name like test1-mlops-<INSPER_USERNAME>
repository_name = "test1-mlops-xxxxx"
# Create a Boto3 client for ECR
ecr_client = boto3.client(
"ecr",
aws_access_key_id=os.getenv("AWS_ACCESS_KEY_ID"),
aws_secret_access_key=os.getenv("AWS_SECRET_ACCESS_KEY"),
region_name=os.getenv("AWS_REGION"),
)
response = ecr_client.create_repository(
repositoryName=repository_name,
imageScanningConfiguration={"scanOnPush": True},
imageTagMutability="MUTABLE",
)
print(response)
print(f"\nrepositoryArn: {response['repository']['repositoryArn']}")
print(f"repositoryUri: {response['repository']['repositoryUri']}")
If you want to use AWS CLI, remember to Activate MLOps Profile
Important!
Write down the repositoryUri
Upload Image to ECR
Before uploading our Docker image to ECR, we need to configure the AWS Command Line Interface (AWS CLI). If you didn't, check this out in our previous class.
Let's authenticate and login to ECR using the Docker CLI:
Atention!
Change the <AWS_ACCOUNT_ID>
for the <AWS_ACCOUNT_ID>
used during classes, for example 123456789012
Check if the AWS profile name, set with aws configure
, really is mlops
. Change if necessary.
Then, we will run the docker tag
command to tag our local Docker image into your Amazon ECR repository as the latest version by doing:
Atention!
Provide the <REPOSITORY_URI>
from before.
Example of <REPOSITORY_URI>
(notice the AWS_ACCOUNT_ID
, AWS_REGION
and REPOSITORY_NAME
):
AWS_ACCOUNT_ID.dkr.ecr.AWS_REGION.amazonaws.com/REPOSITORY_NAME
And push image to ECR with:
Atention!
Provide the <REPOSITORY_URI>
from before.
Example of <REPOSITORY_URI>
(notice the AWS_ACCOUNT_ID
, AWS_REGION
and REPOSITORY_NAME
):
AWS_ACCOUNT_ID.dkr.ecr.AWS_REGION.amazonaws.com/REPOSITORY_NAME
Create Function
Now we can create the lambda function from the image already stored in the ECR.
To do this, run:
Atention!
Change the function_name
and image_uri
.
The image_uri
will follow the pattern <repositoryUri>:<imageTag>
, for example: 123456789012.dkr.ecr.us-east-2.amazonaws.com/test1-mlops-joaoxr:latest
Tip! 2
You can copy the image_uri
from the last docker push
command!
import boto3
import os
from dotenv import load_dotenv
load_dotenv()
# Provide function name: "ex_docker_<INSPER_USERNAME>"
function_name = ""
# Provide Image URI from before
image_uri = ""
lambda_role_arn = os.getenv("AWS_LAMBDA_ROLE_ARN")
# Create a Boto3 client for AWS Lambda
lambda_client = boto3.client(
"lambda",
aws_access_key_id=os.getenv("AWS_ACCESS_KEY_ID"),
aws_secret_access_key=os.getenv("AWS_SECRET_ACCESS_KEY"),
region_name=os.getenv("AWS_REGION"),
)
response = lambda_client.create_function(
FunctionName=function_name,
PackageType="Image",
Code={"ImageUri": image_uri},
Role=lambda_role_arn,
Timeout=30, # Optional: function timeout in seconds
MemorySize=128, # Optional: function memory size in megabytes
)
print("Lambda function created successfully:")
print(f"Function Name: {response['FunctionName']}")
print(f"Function ARN: {response['FunctionArn']}")
Question 5
Proceed to the APS!