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 everyone can use it.
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 needed 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
npm run build command 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
node_modules the directory (containing runtime dependencies only), is being packaged into the
Unfortunately, I haven’t found a working way to avoid
source ~/.bashrc before when triggering npm scripts in this Dockerfile.
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 commands above in a sequence.
That’s all Folks!
GitHub template repository: https://github.com/loginov-rocks/Build-Lambda-in-Docker