Hoonio
Published in

Hoonio

It has been almost a year since Amazon announced the support for container images on AWS Lambda, but so far, it hasn’t seem to gain much traction, and neither has serverless computing in general. Though there is no better place to get hands on with deploying serverless containers, along with the handy templates, I haven’t yet found anything straight forward to follow, so here goes a comprehensive guideline for those who want to run a Flask app inside the container.

Create a Flask App

No need to explain this part. A minimal example will do. Call it app.py

#app.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"

Next, in order to service Flask app through AWS Lambda, we will integrate the WSGI plugin into the application instead of installing the npm package. Add the following lines to app.py

import serverless_wsgi
from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"

def handler(event, context):
return serverless_wsgi.handle_request(app, event, context)

And these are the two packages required for the app to run.

#requirements.txtFlask>=1.1.2
serverless-wsgi>=2.0.2

Docker Container

Next step, let’s package everything inside a container. The dockerfile should look something like the following. Notice the command in the last line calls the WSGI handler in app.py LAMBDA_TASK_ROOT points to /var/task

#DockerfileFROM public.ecr.aws/lambda/python:3.7
COPY . ${LAMBDA_TASK_ROOT}
COPY requirements.txt .
RUN pip3 install -r requirements.txt --target "${LAMBDA_TASK_ROOT}"

CMD ["app.handler"]

Create another file to skip unnecessary files and folders

#.dockerignore__pycache__/
.git/
.serverless/
.gitignore
.dockerignore
serverless.yml

Serverless Framework Configuration

Now time to configure serverless YAML file. Firstly, ECR image should be defined under the provider section, then attach it to the function in place of handler definition.

#serverless.ymlservice: serverless-flask-container

provider:
name: aws
ecr:
images:
appimage:
path: ./

functions:
app:
image:
name: appimage
timeout: 30
events:
- http: ANY /
- http: 'ANY /{proxy+}'

Deployment

Back to the command line, simply run the command. It should initiate Docker build before uploading to ECR and the usual Serverless configuration procedure.

$ sls deploy
Serverless: Packaging service...
Sending build context to Docker daemon 5.12kB
Step 1/5 : FROM public.ecr.aws/lambda/python:3.7
---> 75b3ab837ba6
Step 2/5 : COPY . ${LAMBDA_TASK_ROOT}
---> 6656ae8387d2
Step 3/5 : COPY requirements.txt .
---> de0fa7d4d92d
Step 4/5 : RUN pip3 install -r requirements.txt --target "${LAMBDA_
TASK_ROOT}"
---> Running in e87f72b35fff
Collecting Flask>=1.1.2
Downloading Flask-2.0.2-py3-none-any.whl (95 kB)
Collecting serverless-wsgi>=2.0.2
Downloading serverless_wsgi-2.0.2-py2.py3-none-any.whl (10 kB)
...
Successfully installed Flask-2.0.2 Jinja2-3.0.3 MarkupSafe-2.0.1 Wer
kzeug-2.0.2 click-8.0.3 importlib-metadata-4.8.2 itsdangerous-2.0.1
serverless-wsgi-2.0.2 typing-extensions-4.0.0 zipp-3.6.0
Removing intermediate container e87f72b35fff
---> 46fa4a5a5d30
Step 5/5 : CMD ["app.handler"]
---> 4dd426f4a273
Successfully built 4dd426f4a273
Successfully tagged serverless-flask-container-dev:appimage
The push refers to repository [************.dkr.ecr.us-east-1.amazon
aws.com/serverless-serverless-flask-container-dev]
...
2f0fdaf386f8: Pushed
appimage: digest: sha256:**** size: 2206
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
..............
Serverless: Stack update finished...
Service Information
service: serverless-flask-container
stage: dev
region: us-east-1
stack: serverless-flask-container-dev
resources: 12
api keys:
None
endpoints:
ANY - https://3wlpc5h37a.execute-api.us-east-1.amazonaws.com/dev
ANY - https://3wlpc5h37a.execute-api.us-east-1.amazonaws.com/dev/{
proxy+}
functions:
app: serverless-flask-container-dev-app
layers:
None
Serverless: Removing old service artifacts from S3...
Hello World from the Containerized Lambda

Thanks for reading and checkout the GitHub repo for this tutorial!

--

--

--

New generation of blogging

Recommended from Medium

Data Analyst for B2B Retail use SQL

TryHackMe: Mr. Robot CTF Writeup

Interacting with your UI elements

Certified Kubernetes Deployments Made Easy with WebSphere Liberty Cloud Pak

How to create your first HoloLens app with Unity

Python3.9 SSL Error when compile ResNet50/VGG16 (Solved)

The Architect’s Guide to Digital Banking

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Hoonio

Hoonio

Software Engineer by profession. A Classicist, Stoic, Fiddler & Wanderer. Bridging the gap between ideas & technology

More from Medium

AWS Lambda: Environment variables

Managing environment variables in Serverless using AWS SSM Parameter Store

Invoke AWS Services Cross Account from Lambda (with AWS CDK and AWS SDK v3)

Create a elasticsearch or opensearch backed application using docker with no code