Creating the Node.js Runtime Layer
In this section, we create a dedicated layer for the Node.js runtime. Here, we download and extract Node.js into a specified directory. The runtime layer’s metadata is configured in a TOML file to ensure it is available at launch.node_js_layer variable. To ensure that this runtime is available for subsequent build steps and the final image, update the PATH to include the Node.js binary directory:
Installing Application Dependencies in a Separate Node Modules Layer
Next, we focus on installing your application’s dependencies in a distinct layer. This separation allows you to cache Node modules separately, improving build times and resource utilization. Since dependency installation normally occurs in the current directory, we copy the package files into a new directory, install the dependencies there withnpm ci, and then create a symbolic link back to the workspace.
First, capture the current working directory to reference later:
node_modules folder during runtime.
Resolving the Node.js Executable Path
During preliminary testing, you might encounter an error similar to:This error occurs because Node.js is installed in a separate layer, and the PATH variable has not been updated to include the binary location.
- First, add the Node.js runtime layer (and its
binfolder) to your PATH: - Ensure the launch process is correctly configured. In the final launch TOML, reference the proper command as shown below:
node and npm are recognized.
Final Build and Verification
After configuring both layers, you are ready to build the image. During the export stage, you should see that both the Node.js runtime layer and the node modules layer have been added:By following these steps, you have successfully separated the Node.js runtime and Node modules into individual layers. This modular approach optimizes caching and ensures that your final runtime image includes only the necessary components, enhancing both build performance and deployability.