Serverless Functions: Node.js Code Execution with ROMs
Serverless functions let you deploy small pieces of business logic without managing servers or runtimes. This example implements that model for Node.js, keeping the function code separate from the runtime image that executes it, so you update a function without rebuilding the runtime.
This guide explains how to deploy TypeScript/JavaScript functions as auxiliary Read-Only Memory (ROM) images, then load them dynamically in a Node.js runtime. With Unikraft Cloud, you can create a base image with a generic runtime, package custom code as ROMs, and attach different ROMs to instances of the same base image.
Prerequisites
-
Install the CLI: Use the unikraft CLI or the legacy kraft CLI. You need a BuildKit builder. The easiest way is via Docker. Alternatively, set up and use BuildKit directly, see the quick start.
-
Clone the
examplesrepository andcdinto theexamples/node-code-executiondirectory:Code
Make sure to log into Unikraft Cloud and pick a metro close to you.
This guide uses fra (Frankfurt, 🇩🇪):
Deployment Workflow
Package the base image
First, package and push the base Node.js image (see server.ts for the runtime implementation):
The server implementation in server.ts is a simple Node.js application that listens for HTTP requests and executes JavaScript code from the attached ROM, if available.
There is a little tweak—right before loading the ROM code and starting the server, it writes 1 to the special file /uk/libukp/template_instance (see /platform/instances#instance-templates), triggering a conversion of the instance into a template.
Create an instance template from the base image
Create an instance that uses the base Node.js image without any ROM attached:
The output shows the instance details:
This instance is short-lived, since right before the server starts, it triggers a conversion into a template. To check that the template is ready, run:
Package the ROMs
Create and push the ROMs with the code (see rom1/fs/rom.js and rom2/fs/rom.ts):
Create instances from the template with different ROMs attached
Create a new instance from the template, attaching the first ROM:
Create another instance from the same template, but with the second ROM attached:
List the instances and note their FQDN values:
Test both instances:
Code
Code
Learn more
Use the --help option for detailed information on using Unikraft Cloud:
Or visit the CLI Reference or the legacy CLI Reference.