Mastering Alibaba Cloud Function Compute Layers: Custom & Public Layer Best Practices
This guide explains how to use Alibaba Cloud Function Compute layers—including custom and official public layers—to overcome large dependency packages, reduce deployment size, share code across functions, handle OS/architecture constraints, and provides step‑by‑step examples for Node.js Puppeteer and .NET 6 custom runtimes.
Why Use Layers in Function Compute?
When deploying functions on Alibaba Cloud Function Compute, developers often face issues such as oversized third‑party dependencies, long upload times, code‑package size limits (500 MB per package, 2 GB total for up to five layers), and inconsistencies between local runs and cloud execution.
Custom Layers
In January 2021 Alibaba Cloud introduced custom layers , allowing users to package shared code or data into a ZIP file and attach it to multiple functions. In August 2022 public layers were added, offering official, ready‑to‑use layers.
Creating a Custom Layer
Package the required files (e.g., a Python requests library) into a ZIP with the correct directory layout, such as python/requests.
Upload the ZIP as a custom layer; the platform mounts it under /opt and adds the appropriate paths (e.g., /opt/python) to the runtime’s sys.path.
If the ZIP does not follow the layout, you must manually adjust the search path in your code.
Custom layers support up to 100 immutable versions; each version is read‑only and can be shared across functions within the same account and region.
Advantages of Layers
Cross‑function code reuse : Common libraries or data are packaged once and referenced by many functions.
Smaller deployment packages : Functions only contain core logic, reducing upload time and staying within size limits.
Faster deployments : Updating a layer version does not require redeploying every function that uses it.
Limitations include a 500 MB size cap per layer, a maximum of five layers per function, and the inability to share custom layers across accounts (public layers can).
Public Layers
Official public layers provide pre‑built runtimes (Python 3.10, Node.js 17, PHP 8.1, Java 17, .NET 6) and popular libraries (PyTorch, SciPy, Puppeteer) as well as the Alibaba Cloud SDK (DataX). They can be added to functions without building your own ZIP.
Example 1: Node.js 16 + Puppeteer Screenshot
Create a function named start-puppeteer with HTTP request handling.
Set memory to 1 GB (typical usage ~550 MB).
Replace index.js with the following code:
const fs = require('fs');
const puppeteer = require('puppeteer');
function autoScroll(page) {
return page.evaluate(() => {
return new Promise((resolve, reject) => {
var totalHeight = 0;
var distance = 100;
var timer = setInterval(() => {
var scrollHeight = document.body.scrollHeight;
window.scrollBy(0, distance);
totalHeight += distance;
if (totalHeight >= scrollHeight) {
clearInterval(timer);
resolve();
}
}, 100);
});
});
}
module.exports.handler = async function (request, response, context) {
console.log('Node version is: ' + process.version);
const browser = await puppeteer.launch({
headless: true,
args: [
'--disable-gpu',
'--disable-dev-shm-usage',
'--disable-setuid-sandbox',
'--no-first-run',
'--no-zygote',
'--no-sandbox'
]
});
let url = request.queries['url'] || 'https://www.serverless-devs.com';
if (!url.startsWith('https://') && !url.startsWith('http://')) {
url = 'http://' + url;
}
const page = await browser.newPage();
await page.emulateTimezone('Asia/Shanghai');
await page.goto(url, { waitUntil: 'networkidle2' });
await page.setViewport({ width: 1200, height: 800 });
await autoScroll(page);
const path = '/tmp/example';
const contentType = 'image/png';
await page.screenshot({ path, fullPage: true, type: 'png' });
await browser.close();
response.setStatusCode(200);
response.setHeader('content-type', contentType);
response.send(fs.readFileSync(path));
};Configure the function to use the official public layer Puppeteer17x (version 1) and set the environment variable LD_LIBRARY_PATH=/opt/lib/x86_64-linux-gnu:/opt/lib if required.
Test via the console’s test address or by invoking the HTTP endpoint; the function returns a PNG screenshot.
Example 2: .NET 6 Custom Runtime
Create a .NET 6 custom runtime function, selecting “Use custom runtime” and “Handle HTTP requests”.
Deploy the sample Program.cs (shown in the console) which:
Listens on 0.0.0.0:9000 (required for custom runtimes).
Exposes / returning “Hello World!”.
Exposes /invoke for POST requests (event handler).
Exposes /initialize as the initializer callback.
Test the routes using the console’s “Test address” and curl -XPOST for /invoke.
Enable the initializer callback in the function configuration; the platform automatically calls it on instance start.
Best‑Practice Recommendations
Prefer custom layers for building and sharing custom runtimes.
Use official public layers whenever they provide the needed runtime or library.
Package large, rarely‑changed dependencies into layers to keep function packages small.
If a library requires additional shared dynamic libraries (e.g., Puppeteer), include them under a lib directory in the layer ZIP; the platform adds /opt/lib to LD_LIBRARY_PATH.
When sharing code across multiple functions or accounts, use public layers (custom layers are limited to the same account/region).
Layer vs. Code Package
Layers have independent versioning (auto‑incremented, up to 100 versions) and are immutable; code packages have no native versioning.
Layer versions are read‑only, preventing accidental changes that could break functions.
Layers can be shared across functions and accounts (public layers), whereas code packages cannot.
Deleted layer versions are soft‑deleted: they remain usable by functions that already reference them until no function uses them.
Similar Features: NAS and OSS Mounts
Function Compute also offers NAS file‑system mounts and OSS object‑storage mounts. Use these when the data or code size exceeds layer limits or when the content changes frequently, as they provide mutable storage.
Future Enhancements
Expand the catalog of official public layers with more runtimes and common libraries.
Provide clearer contribution guidelines and examples for community‑maintained public layers.
Overall, layers act as an immutable infrastructure layer that simplifies dependency management, reduces deployment size, and enables safe versioning and sharing across functions.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Alibaba Cloud Native
We publish cloud-native tech news, curate in-depth content, host regular events and live streams, and share Alibaba product and user case studies. Join us to explore and share the cloud-native insights you need.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
