关于serverless:如何使用-Serverless-Devs-部署静态网站到函数计算

11次阅读

共计 2361 个字符,预计需要花费 6 分钟才能阅读完成。

作者 | 邓超 Serverless Devs 开源贡献者

前言

公司常常有一些网站须要公布上线,比照了几款不同的产品后,决定应用阿里云的函数计算(FC)来托管构建进去的动态网站。FC 弹性实例自带的 500 Mb 存储空间 [1] 对动态网站来说几乎是太短缺了。

函数计算资源应用:https://help.aliyun.com/docum…

部署动态网站到 Custom Runtime 函数

假如咱们当初有如下构造的前端工程:

/
├ dist/ 待部署的构建产物
│  └ index.html 
├ src/
└ package.json

### step 1. 编写一个简略的 HTTP 服务器

以 Express 为例, 首先增加依赖到工程:

yarn add express

而后新建 app.js 并写入:

let Express = require("express");
let app = new Express();
app.use(Express.static('dist'));
 // 应用 dist 文件夹中的内容对外提供动态文件拜访
app.use((req, res) => {res.redirect("/"); }); 
// 重定向无奈解决的申请到网站的根目录
let port = 9000;
app.listen(port, () => {console.log(`App started on port ${port}`); }); 
// 监听 FC custom 运行时默认的 9000 端口

通过 node app.js 启动这个简略的 Express 服务器, 并问 http://localhost:9000 确认 /dist/index.html 能被拜访到。

接下来就是把 app.js 和 dist 一起公布到函数计算上就行了。

step 2. 编写 bootstrap

函数计算 custom 运行时要求用户提供一个 bootstrap 文件用于启动自定义的 HTTP 服务器, 所以咱们须要在根目录下创立这个文件:

#! /bin/bash
node app.js

留神第一行的 #! /bin/bash 是必须的, 不然函数计算不晓得该用哪一个解释器来执行脚本中的内容。Windows 用户记得把这个文件的换行符从 /r/n 改成 /n , 不然会遇到函数计算启动超时的问题。

step 3. 装置 @serverless-devs/s 并编写 s.yaml

增加 @serverless-devs/s 命令行工具到工程:

yarn add @serverless-devs/s -D

而后在根目录下创立一个根底的 s.yaml 配置文件:

# https://github.com/devsapp/fc/blob/main/docs/zh/yaml/
edition: 1.0.0
name: my-awesome-website-project
services:
  my-service: # 任意的名称
    component: devsapp/fc       # 应用 fc 组件
    props:
      region: cn-shenzhen       # 部署到任意的可用区, 例如深圳.
      service:
        name: my-awesome-websites   # 深圳可用区的 my-awesome-websites 服务
      function:
        name: www-example-com     # my-awesome-websites 服务下的一个函数
        runtime: custom        # 应用 custom 运行环境
        handler: dummy-handler     # 因为应用了 custom 运行环境, 所以这里能够轻易填
        codeUri: ./          # 部署以后文件夹下的全部内容
      triggers:
        - name: http
          type: http        # 创立一个 HTTP 类型的触发器, 以便客户端能够通过 HTTP 协定进行拜访
          config:
            authType: anonymous    # 容许匿名拜访
            methods: [HEAD, GET]  # 动态网站只须要解决 HEAD 和 GET 申请就够了

step 4. 部署到函数计算

配置好 AccessKey 和 AccessSecret[2] 后,执行命令:

s deploy

你的网站就部署下来了。

接下来就是配置自定义域名了, 配置好当前就能够通过你本人的域名拜访到这个网站了。

step 5. 配置自定义域名

以自定义域名 deploy-static-website-to-fc.example.dengchao.fun 为例;
首先增加 CNAME 记录, 解析值填写 ${UID}.${REGION}.fc.aliyuncs.com. 因为咱们的 s.yaml 中设置的 region 是 cn-shenzhen, 所以对应的值就是 xxxxxx.cn-shenzhen.fc.aliyuncs.com .

接下来设置函数计算管制台上的自定义域名:

拜访一下试试看:
http://deploy-static-website-…(opens new window)

样本工程

本文中的样本工程曾经上传到 GitHub:
https://github.com/DevDengCha…(opens new window)

参考及相干链接

[1] 500 Mb 存储空间
https://help.aliyun.com/docum…

[2] 配置好 AccessKey 和 AccessSecret
https://www.serverless-devs.c…

[3] 阿里云函数计算 - 产品简介
https://help.aliyun.com/docum…

[4] 资源应用限度
https://help.aliyun.com/docum…

[5] 自定义运行环境
https://help.aliyun.com/docum…

[6] 配置自定义域名
https://help.aliyun.com/docum…

[7] Serverless devs 官网
https://www.serverless-devs.com/

点击此处,理解 Serverless Devs 官网更多资讯!

正文完
 0