Introduction
In this post, we’ll turn a simple AWS Lambda function into a running Docker container so you can test your functions locally on your own machine. This greatly improves efficiency testing and speeds up your development process.
The setup
Debugging Lambdas is not easy. How can we run functions locally for easier testing?
Let’s say you have a folder that contains just two files for an AWS function:
|
|
Contents of index.js
:
|
|
Adding a Dockerfile
First, add a Docker file with Amazon’s basic Node.js Lambda image, as you see on line 1:
|
|
- On line 3, we copy
package.json
into the container. - On line 4, we run the command to install any packages required for your function.
- On line 6, we add your
index.js
file. - Finally, on line 8, we define what our function
"handler"
is.
Note: ${LAMBDA_TASK_ROOT}
is a variable that’s defined in the base Amazon image, so you don’t need to define it.
AWS automatically detects which of their supported languages you’re using based on the image specified on line 1 of the Docker file.
Building and Running the container
Now that we have a Docker file we can build this image with:
|
|
And execute it by running:
|
|
If everything went well, you should see something in the likes of:
|
|
You now have you lambda running! Perfect, let’s restart, but now we’ll connect Lambdas’ default port to our host so we can interact with it.
|
|
Intuitively, you’re inclined to open your browser and go directly to the page. However, that’s not how Amazon’s Lambdas work. They’re routed internally, so we can’t directly access them. Instead, we have to use a tool like Postman for example to execute a post request to a specific URL (someone from Amazon, please explain to me why this works like this):
|
|
We need that URL to send the json
contents we want the function to execute.
Interacting with your function
So we just learned that functions are a little hidden. No stress, we can still reach the function.
Here’s a simple curl
call that will just invoke the function without anything else:
|
|
Response
If your container is running correctly, your function shell should now show a few extra lines with Amazon information, plus any other logging you might have added.
|
|
That’s it!
Note: I added a console.log in the index.js
file, which is the reason you will see the body stringified
text in the response. It should contain the result of your executed code. Results may vary depending on your index.js
contents.
Sadly, the solution feels rather hacky, and if you know of a better way to do this, we’re all ears. Share your thoughts with us!
We have also written a tutorial to run a Cloudflare Worker Locally
If you like this kind of content and would like more detailed or complex scenarios, help us by sharing this article or reaching out via the contact form!