Rob Keplin - Software Engineer

# AWS – PHP Lambda Function, A Quickstart Guide

Category: AWS PHP

Creating a lambda container image is pretty cool. If you need to run a piece of software that is limited to a certain OS, you can. If you want to write in a certain language, you can. This opens up a list of possibilities. The lead engineer on my team at work had introduced me to this concept, and it turned out really well for our use-case.

In this blog post, I will show how to get PHP running on Fedora 34 in an AWS lambda function. But the same pattern may be used for any programming language or OS.

All the code is available on my GitHub.

Prerequesites

You’ll need to have the following installed and working in order to follow this guide. Serverless is not required for running a dockerized lambda function, but it certainly makes it a lot easier.

docker -v
Docker version 19.03.12, build 48a6621
sls -v
Framework Core: 2.57.0
Plugin: 5.4.4
SDK: 4.3.0
Components: 3.16.0
  • Download REI runtime (if you want to be able to test your lambda function locally)
mkdir -p ~/.aws-lambda-rie && curl -Lo ~/.aws-lambda-rie/aws-lambda-rie \
https://github.com/aws/aws-lambda-runtime-interface-emulator/releases/latest/download/aws-lambda-rie \
&& chmod +x ~/.aws-lambda-rie/aws-lambda-rie

Setup the project

On your local machine, create a new directory and download the source code from the repository that I’ve setup.

git clone https://github.com/rkeplin/lambda-php-dockerized.git php-lambda
cd php-lambda

The bootstrap is the glue for how this will work. This file may be written in any language, as long as it can handle cURL requests to the AWS_LAMBDA_RUNTIME_API. More information regarding custom lambda runtimes can be found here.

The Dockerfile installs PHP on the OS of choice, and contains a couple of LAMBDA environment variables. The bootstrap file is referenced as the ENTRYPOINT.

The requests that go through the bootstrap file will end up executing handler.php

Build the image

docker image build -t phplambda .

Test Locally

Spin up the container.

docker run -v ~/.aws-lambda-rie:/aws-lambda --entrypoint /aws-lambda/aws-lambda-rie  -p 9000:8080 phplambda:latest /var/runtime/bootstrap handler.process

Test the local lambda function.

curl "http://127.0.0.1:9000/2015-03-31/functions/function/invocations" -d '{"name":"Test"}'

Test on AWS

Deploy the lambda function

This will build the image locally, upload it to the AWS ECR service and deploy the lambda function among a few other things.

sls deploy

Test the lambda

sls invoke -f hello -d '{"name":"Test"}'

Leave a Reply

Your email address will not be published.

*

*

*