AWS CDK: Deploy Lambda with Docker

December 5th, 2020 195 Words

The AWS Cloud Development Kit supports building docker images for AWS Lambda. With the most recent version, the CDK builds your docker images if needed and can push the image directly to AWS Elastic Container Registry. Personally, I think this is a great feature. With supporting docker images, AWS Lambda has immutable deployment artifacts!

You need to configure a Dockerfile with these basics, create a handler.js file and use the DockerImageFunction class with AWS Cloud Development Kit.

# Dockerfile

FROM amazon/aws-lambda-nodejs:12

ARG FUNCTION_DIR="/var/task"

RUN mkdir -p ${FUNCTION_DIR}

COPY handler.js ${FUNCTION_DIR}

CMD [ "handler.run" ]
// handler.js

exports.run = async (event, context) => {
  return "Done";
};
// TypeScript CDK

import * as path from "path";

import * as cdk from "@aws-cdk/core";
import * as Lambda from "@aws-cdk/aws-lambda";

export class CDKLambdaDocker extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // Configure path to Dockerfile
    const dockerfile = path.join(__dirname, "../src");

    // Create AWS Lambda function and push image to ECR
    new Lambda.DockerImageFunction(this, "function", {
      code: Lambda.DockerImageCode.fromImageAsset(dockerfile),
    });
  }
}

With running cdk deploy, the CDK will build and push your docker image and create a new AWS Lambda function using the image.