Docker has changed how we build and deploy software, and every major cloud provider supports it, including AWS. If you’ve containerized your app but deploying it to ECS (Elastic Container Service) or EKS (Elastic Kubernetes Service) feels like too much, there’s a simpler option: running containers on AWS Lambda (opens in new tab).
In this post, I’ll show you how to deploy a container to Lambda and share dependencies between functions with container layers, the container version of Lambda layers, all deployed by a CI/CD pipeline.
Project Setup
Our example is a basic Python app that runs whenever it receives an event. We’ll trigger that event from the AWS console.
The app does two things: it stores the event’s data in a DynamoDB table under a unique ID, then returns HTTP 200.
To talk to DynamoDB, we’ll use Boto3.
import os
import json
import uuid
import boto3
dynamodb = boto3.resource("dynamodb")
database = dynamodb.Table("lambda-docker")
def handler(event, context):
object_uuid = str(uuid.uuid4())
body = {
"uuid": object_uuid,
"event": json.dumps(event),
}
database.put_item(Item=body)
return {"statusCode": 200, "body": json.dumps(body)}
We also need a requirements.txt file that lists the app’s dependencies:
boto3==1.26.86
Werkzeug==1.0.1
markupsafe==2.0.1
Before we get to Docker, let’s set up deployments. We’ll create a new app with the Serverless Framework.
I won’t cover setting up a Serverless account or linking it to AWS, but you can follow their official getting-started guide (opens in new tab).
Once your account is set up, create a new app:
npm i -g serverless && serverless \
--org=yourorgname \
--app=aws-lambda-docker \
--name=aws-lambda-docker \
--template=aws-python
Next, create the AWS resources: a DynamoDB table and two ECR (Elastic Container Registry) repositories, one for the function image and one for the layer. AWS has guides for both:
- How to Create a DynamoDB Table (opens in new tab)
- How to Create a Private ECR Repository (opens in new tab)
Then add a serverless.yml file. It gives your Serverless app permission to use DynamoDB and ECR:
org: yourorgname
app: aws-lambda-docker
service: aws-lambda-docker
frameworkVersion: '3'
provider:
name: aws
iam:
role:
statements:
- Effect: "Allow"
Action:
- "ecr:InitiateLayerUpload"
- "ecr:SetRepositoryPolicy"
- "ecr:GetRepositoryPolicy"
# Replace 'accountid' with your own account
Resource: ["arn:aws:ecr:us-east-1:accountid:repository/*"]
- Effect: "Allow"
Action:
- "dynamodb:DescribeTable"
- "dynamodb:Query"
- "dynamodb:Scan"
- "dynamodb:GetItem"
- "dynamodb:PutItem"
- "dynamodb:UpdateItem"
- "dynamodb:DeleteItem"
# Replace 'accountid' with your own account
Resource: ["arn:aws:dynamodb:us-east-1:accountid:table/lambda-docker"]
functions:
handler:
# Replace with your function image repository url (grab it from ECR)
image: accountid.dkr.ecr.us-east-1.amazonaws.com/lambda-docker-function-repository:latest
Why ECR? The last lines of the config tell the framework to deploy the function from a container image instead of a .zip file. The Serverless Framework supports Lambda containers out of the box (opens in new tab), and ECR is where those images live.
functions:
handler:
image: accountid.dkr.ecr.us-east-1.amazonaws.com/lambda-docker-function-repository:latest
The project is set up, but we can’t run it yet because the repository is still empty. Next, we’ll build an image to put in it.
Building the Docker Image and Layer
Most of our apps bundle boto3, since they all talk to AWS. Instead of bundling it into every app, how can we turn it, and any other shared dependency, into a reusable layer?
Docker builds images in layers, so we can put the shared dependencies in their own image and reuse it across functions. We’ll write two Dockerfiles.
layer.Dockerfile
We’ll build the layer as a container image. Just as a Lambda layer attaches to a .zip function, a container layer gets copied into other container images.
To match the paths Lambda layers use, the layer’s files must live in /opt. Python libraries go in /opt/python, which Lambda adds to the Python path, so the function finds them where it expects them.
FROM python:3.8-alpine AS installer
# Copy requirements.txt
COPY requirements.txt /opt/
# Install layer dependencies where Lambda's Python runtime looks for them
RUN pip install -r /opt/requirements.txt -t /opt/python
FROM scratch AS base
# Each runtime looks for libraries location under /opt
WORKDIR /opt/
COPY --from=installer /opt/ .
The layer installs the packages in requirements.txt with pip install during docker build. That needs Python, so the installer stage uses a small base image, python:3.8-alpine.
Because each layer is its own image, you can add it to as many functions as you want, just like Lambda layers.
function.Dockerfile
The function’s Dockerfile pulls the layer image from ECR and copies its files into the function image.
# Replace 'accountid' with your own account
FROM accountid.dkr.ecr.us-east-1.amazonaws.com/lambda-docker-layer-repository:latest AS layer
# Use the existing AWS Python image for Lambda compatibility (https://docs.aws.amazon.com/lambda/latest/dg/python-image.html)
FROM public.ecr.aws/lambda/python:3.8
# Layer code
WORKDIR /opt
COPY --from=layer /opt/ .
ARG FUNCTION_DIR="/var/task"
# Create function directory
RUN mkdir -p ${FUNCTION_DIR}
WORKDIR ${FUNCTION_DIR}
# Copy the handler function
COPY app.py .
# Set the CMD to your handler
CMD [ "app.handler" ]
There’s no pip install here, because the function gets all its dependencies from the layer.
Deploying with GitHub Actions
To avoid pushing images to ECR by hand, we’ll use GitHub Actions for CI/CD.
Like the Dockerfiles, there are two workflow files, both in .github/workflows. They’re based on GitHub’s guide for deploying to Amazon ECS (opens in new tab).
layer.yml
The layer workflow only runs when the dependencies in requirements.txt change. If you upgrade Boto3, change a dependency or add a library, the layer gets rebuilt with it.
It also saves time. If you only changed your code, there’s no need to rebuild the layer, and the function uses the latest layer already in ECR.
name: Deploy Lambda Docker Layer to ECR
on:
push:
branches:
- main
paths:
- requirements.txt
workflow_dispatch:
env:
ECR_REPOSITORY: lambda-docker-layer-repository
permissions:
contents: read
jobs:
deploy:
name: Build Lambda Layer Image
runs-on: ubuntu-latest
environment: production
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v1
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: ${{ secrets.AWS_REGION }}
- name: Login to Amazon ECR
id: login-ecr
uses: aws-actions/amazon-ecr-login@v1
- name: Build, tag, and push image to Amazon ECR
id: build-image
env:
ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
IMAGE_TAG: latest
run: |
docker build --platform linux/amd64 -f layer.Dockerfile -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG .
docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
echo "::set-output name=image::$ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG"
Before you run these workflows, add these secrets to your GitHub repository: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_REGION. The function workflow also needs SERVERLESS_ACCESS_KEY.
For the AWS credentials, you can reuse the ones you set up for Serverless or create a separate set just for CI/CD.
function.yml
The function workflow runs in two cases: when a push to main changes the app code, and when the layer workflow finishes.
The second case matters because the function image copies in the layer when it’s built. When the layer changes, the function has to be rebuilt to pick up the new dependencies.
name: Deploy Lambda Docker Function to AWS
on:
workflow_run:
workflows: ["Deploy Lambda Docker Layer to ECR"]
types:
- completed
push:
branches:
- main
paths:
- app.py # or a folder containing the function code
workflow_dispatch:
env:
ECR_REPOSITORY: lambda-docker-function-repository
permissions:
contents: read
jobs:
deploy:
name: Build Lambda Function Image
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [16.x]
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v1
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: ${{ secrets.AWS_REGION }}
- name: Login to Amazon ECR
id: login-ecr
uses: aws-actions/amazon-ecr-login@v1
- name: Build, tag, and push image to Amazon ECR
id: build-image
env:
ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
IMAGE_TAG: latest
run: |
docker build --platform linux/amd64 -f function.Dockerfile -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG .
docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
echo "::set-output name=image::$ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG"
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
- run: npm ci
- name: Serverless Deploy
uses: serverless/github-action@v3
with:
args: deploy
env:
SERVERLESS_ACCESS_KEY: ${{ secrets.SERVERLESS_ACCESS_KEY }}
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
The function workflow also deploys the function to Lambda. The Serverless Framework keeps this simple: install Node.js, run npm ci to get the Serverless dependencies, then run serverless deploy through the official GitHub action.
That command reads serverless.yml and deploys the new version of the function to your AWS account.
Testing Everything
To test the setup:
- Run the layer workflow from GitHub. When it finishes, it starts the function workflow automatically.
- Once both are done, sign in to AWS and open Lambda.
- Open the new function with the name you chose and go to the “Test” tab.
- Run a test event with the default payload.
- Open DynamoDB and find the table you created earlier.
- Query the table, and you should see the item you just created.
Now try changing things:
- Add a
printstatement toapp.pyand commit it tomain. Only the function workflow runs. - Upgrade boto3 to version 1.26.87 and commit the change. The layer workflow runs first, then the function workflow.
Each change rebuilds only what it needs to.
Closing Comments
I hope this guide helps you combine Docker and serverless. If anything is unclear, feel free to email me.