How to build and package Node.js Lambda code along with dependencies in Docker
I found the approach to build the code described in the AWS blog post quite sophisticated and not really reusable across different projects, searching through the internet also didn’t provide me with convenient options, so I decided to create a GitHub template repository that has all the needed operations encapsulated in a single command:
npm run package
And this is a short post explaining how it works so anyone can use it.
It is important to understand that this approach enables the compilation of the Node.js code with any libraries and runtime dependencies needed within the Docker container without using the Docker in AWS Lambda at all. The result is a zip archive that can be easily uploaded to AWS.
The BASE image is based on the official Amazon Linux image to have the most similar setup to what will be used to run the Lambda code.
First, only required OS packages installed as well as nvm to have the actual Node.js runtime version — the one, that you configured for the AWS Lambda.
Next, in the BUILD image, the dependencies are installed and the
npm run build command is executed to compile the code.
After that, the APPLICATION image installs runtime dependencies only and gets the artifact from the BUILD image (
Eventually, all the code in the APPLICATION image, including the
node_modules directory (containing runtime dependencies only), is packaged into the
Unfortunately, I haven’t found a working way to avoid
source ~/.bashrc before when triggering npm scripts in this Dockerfile.
The following npm scripts are configured to do the work:
docker:buildto build the image;
docker:createto create a temporary container without starting it;
function.ziparchive from the container;
docker:cleanremoves the temporary container;
packageruns the commands above in a sequence.
GitHub template repository: https://github.com/loginov-rocks/Build-Lambda-in-Docker
That’s all Folks!
Update on December 25, 2023
Upgraded GitHub repository to use Node.js 18, AWS SDK v3, Amazon Linux 2023, and all the latest dependencies.