Author: Lian Zheren

This article is selected from the "Serverless Functional Computing Call for Papers"

Take advantage of serverless's horizontal expansion and pay-as-you-go advantages, combined with custom runtime, to achieve rapid migration of web applications. The Deno runtime is a new generation of JS runtime. Using the combination of Alibaba Cloud Serverless + Deno, we can quickly develop modern web applications.

Deno works with Serverless Devs tools to quickly implement code deployment. So far, the combination of Alibaba Cloud Function Compute + Serverless Devs + Deno + TypeScript has achieved rapid software development, rapid iteration, rapid deployment, and rapid scaling, taking advantage of the cloud to quickly solve business problems.

Why Serverless

In the field of web development, the biggest advantage of serverless over traditional methods is that it can achieve horizontal expansion under the premise of low operation and maintenance. In this way, developers can focus on business instead of paying too much attention to complicated technical details in order to support possible high concurrency, because focusing on business greatly improves development efficiency and reduces development costs.

At the same time, the elastic horizontal expansion can support the business needs of any access frequency, without worrying about the problem of cost-benefit mismatch. Applications ranging from 1 PV per day to 1,000,000 PV per day can be supported without additional configuration, without having to do cluster management by yourself, and without incurring fixed fees, just pay according to usage.

We can understand serverless as an on-demand scaling container cluster that does not need to be managed by itself. In the development of web applications, both from a technical perspective and a cost perspective, serverless has more advantages.

So, how to realize the migration of traditional web applications to serverless?

In theory, any programming language can be used on Serverless. However, in terms of specific implementation, Serverless provides the following methods:

  1. Run the scripting language directly (the serverless container already carries the target language runtime, just upload the code)
  2. Runtime + language scripts (all uploaded to Serverless)
  3. Executable (compiled locally to executable, then uploaded to Serverless)
  4. Custom container (currently, Alibaba Cloud Serverless supports Docker images to generate containers)

The above methods are all supported on Alibaba Cloud Serverless. Compare the advantages and disadvantages of the above methods:

  • Running the scripting language directly has the shortest cold start time (that is, the preparation time of the serverless container before code execution);
  • Custom containers are the most compatible, and what we're using here is a balancing act: a custom runtime.

The custom runtime was chosen because our runtime is Deno, a modern JS/TS runtime. On the one hand, although JS is a scripting language, Alibaba Cloud does not currently support the Deno runtime, so it is impossible to run applications on Serverless by directly running the scripting language.

On the other hand, Deno provides Go-like package-as-executable functionality that enables cross-platform code execution without the use of containers.

Why Deno

Deno, a JS/TS runtime, uses V8 as the JS interpreter like Node.js to ensure speed. Unlike Node.js, it uses Rust instead of C++ as the development language to communicate with the operating system. (The other thing that the two are the same is that the originator and the original main developer are Ry, Ryan Dahl)

Node.js as a backend JS runtime has undoubtedly been hugely influential and successful. But Node.js was born many years ago. With the development of ECMAScript, JavaScript (JS) has changed. In order to ensure ecological compatibility, Node.js is difficult to carry out drastic reforms. This is the background of Deno's birth.

For developers, in addition to better ECMAScript compatibility, Deno also provides out-of-the-box TypeScript (TS) support, which provides more robust type constraints and greatly reduces unnecessary consumption such as development environment configuration.

At present, with the continuous iteration of Deno versions, in the web development scenario, Deno can already implement most of the functions that Node.js can achieve. Using Deno as a runtime is a quick and easy way for JS developers to get started without too much burden. Compared with Node.js, Deno has two biggest advantages:

  1. Supports Web APIs (such as fetch, crypto, etc.).
  2. Supports file referencing without the need to use a package manager like npm.

Supporting Web API can open up the front-end and back-end technology stacks, and npm has been suffering developers for a long time.

Simple Deno Web Use Case

Using Deno to develop web applications is very simple, let's quickly create a simple web application to implement UA display.

 import { serve } from "https://deno.land/std@0.148.0/http/server.ts";

function handler(req: Request): Response {
  return new Response(
    ["Hello, World!", req.method, req.url, req.headers.get("user-agent")].join(
      "\n"
    )
  );
}

serve(handler, { port: 9000 });

Now we save the above code in /User/zsqk/web/main.ts address.

Create serverless functions

With the code, we also need the deployment address. Here we take Alibaba Cloud Function Compute FC as an example. The first step is to create a custom runtime function:

  1. Enter the Alibaba Cloud Function Compute Web Console
  2. Click "Services and Functions" in the left navigation bar
  3. Click "Create Service" to create the service
  4. Click "Service Name" to enter the service interface
  5. Click "Create Function"
  6. When creating a function, select "Smoothly migrate Web Server with a custom runtime", then proceed to function creation

Then you need to bind the domain name:

  1. After returning to the Function Compute home page, click "Domain Name Management" in the left navigation bar
  2. Click "Add Custom Domain"
  3. When adding a custom domain name, select the service and function we just created

At this point, we have completed all the basic configuration and got the required parameters:

  1. Service Name

2. Function name

3. Access the domain name

Deploy Deno Web Apps on Serverless with One Click

It is very convenient to deploy Deno Web applications on Serverless. We can implement one-click deployment, use Alibaba Cloud Serverless's custom runtime to build an executable file locally, and then deploy the code to Function Compute through the Serverless Devs tool. It can be executed on Serverless.

Here we assume that Deno and s tools have been installed in the local environment, now create the following configuration file and put it in /User/zsqk/web/s.yaml.

 edition: 1.0.0
name: zsqk-fc
access: default
services:
  fc-z1-deno:
    component: devsapp/fc
    props:
      region: ${地区}
      service:
        name: ${服务名}
      function:
        name: ${函数名}
        instanceConcurrency: 5
        instanceType: e1
        memorySize: 128
        runtime: custom
        timeout: 3
        codeUri: "./dist"

The code and deployment configuration files are ready, just build and upload the code. First go to the /User/zsqk/web/ directory and use the following example to run build and upload commands using Deno:

 // 构建 deno 文件
const r = Deno.run({
  cmd: [
    `deno`,
    "compile",
    "--output",
    "dist/bin/zsqk",
    "--target",
    "x86_64-unknown-linux-gnu",
    "--allow-all",
    "/User/zsqk/web/main.ts",
  ],
});
await r.status();
r.close();
Deno.writeTextFileSync(
  `/User/zsqk/web/dist/bootstrap`,
  "#!/bin/bash\n./bin/zsqk --allow-all"
);
 // 准备上传
const r = Deno.run({
  cmd: ["s", "deploy", "function", "--use-local"],
});
await r.status();
r.close();

When the above command is executed successfully, we have completed the whole process of deploying Deno Web application to Aliyun Serverless with one click. Then we can use the access domain name configured above to see if our UA Web is working properly.

At this point, we have completed the entire work, and if we need to apply code changes every time, we only need to re-execute the build and deployment commands.

Read the original text: https://developer.aliyun.com/article/986503

阿里云云原生
1k 声望302 粉丝