如何在DigitalOcean Kubernetes上使用OpenFaaS运行无服务器功能

介绍 (Introduction)

Typically, hosting a software application on the internet requires infrastructure management, planning, and monitoring for a monolithic system. Unlike this traditional approach, the serverless architecture (also known as function as a service, or FaaS) breaks down your application into functions. These functions are stateless, self contained, event triggered, functionally complete entities that communicate via APIs that you manage, instead of the underlying hardware and explicit infrastructure provisioning. Functions are scalable by design, portable, faster to set up and easier to test than ordinary apps. For the serverless architecture to work in principle, it requires a platform agnostic way of packaging and orchestrating functions.

通常,在Internet上托管软件应用程序需要对整体系统进行基础结构管理,规划和监视。 与这种传统方法不同, 无服务器架构(也称为功能即服务 ,即FaaS)将您的应用程序分解为功能 。 这些功能是无状态的,自包含的,事件触发的,功能完整的实体,它们通过您管理的API进行通信,而不是底层硬件和显式基础结构配置。 与普通应用程序相比,功能可以通过设计进行扩展,可移植,设置更快,更易于测试。 为了使无服务器架构能够正常工作,它需要一种与平台无关的方式来打包和协调功能。

OpenFaaS is an open-source framework for implementing the serverless architecture on Kubernetes, using Docker containers for storing and running functions. It allows any program to be packaged as a container and managed as a function via the command line or the integrated web UI. OpenFaaS has excellent support for metrics and provides autoscaling for functions when demand increases.

OpenFaaS是一个开源框架,用于使用Docker容器存储和运行功能在Kubernetes上实现无服务器架构。 它允许将任何程序打包为容器,并通过命令行或集成的Web UI作为功能进行管理。 OpenFaaS对指标提供了出色的支持,并在需求增加时为功能提供了自动扩展功能。

In this tutorial, you will deploy OpenFaaS to your DigitalOcean Kubernetes cluster at your domain and secure it using free Let’s Encrypt TLS certificates. You’ll also explore its web UI and deploy existing and new functions using the faas-cli, the official command line tool. In the end, you’ll have a flexible system for deploying serverless functions in place.

在本教程中,您将OpenFaaS部署到域中的DigitalOcean Kubernetes集群,并使用免费的Let's Encrypt TLS证书对其进行保护。 您还将探索其Web UI,并使用官方命令行工具faas-cli部署现有功能和新功能。 最后,您将拥有一个灵活的系统来部署无服务器功能。

先决条件 (Prerequisites)

  • A DigitalOcean Kubernetes cluster with your connection configured as the kubectl default. The cluster must have at least 8GB RAM and 4 CPU cores available for OpenFaaS (more will be required in case of heavier use). Instructions on how to configure kubectl are shown under the Connect to your Cluster step when you create your cluster. To create a Kubernetes cluster on DigitalOcean, see Kubernetes Quickstart.

    一个DigitalOcean Kubernetes集群,其连接配置为kubectl默认。 群集必须至少具有8GB RAM和4个CPU内核可用于OpenFaaS(如果大量使用,则需要更多)。 创建集群时,“如何连接到集群”步骤下会显示有关如何配置kubectl说明。 要在DigitalOcean上创建Kubernetes集群,请参阅Kubernetes Quickstart

  • Docker installed on your local machine. Following Steps 1 and 2 for your distribution, see How To Install Docker.

    Docker安装在您的本地计算机上。 按照分发的步骤1和2,请参阅如何安装Docker

  • An account at Docker Hub for storing Docker images you’ll create during this tutorial.

    Docker Hub上的一个帐户,用于存储您将在本教程中创建的Docker映像。

  • faas-cli, the official CLI tool for managing OpenFaaS, installed on your local machine. For instructions for multiple platforms, visit the official docs.

    faas-cli ,用于管理OpenFaaS的官方CLI工具,安装在本地计算机上。 有关多个平台的说明,请访问官方文档

  • The Helm package manager installed on your local machine. To do this, complete Step 1 and add the stable repo from Step 2 of the How To Install Software on Kubernetes Clusters with the Helm 3 Package Manager tutorial.

    安装在本地计算机上的Helm软件包管理器。 为此,请完成步骤1并使用Helm 3 Package Manager教程添加如何在Kubernetes群集上安装软件的步骤2中的stable 仓库

  • The Nginx Ingress Controller and Cert-Manager installed on your cluster using Helm in order to expose OpenFaaS using Ingress Resources. For guidance, follow How to Set Up an Nginx Ingress on DigitalOcean Kubernetes Using Helm.

    使用Helm在群集上安装了Nginx Ingress控制器和Cert-Manager,以便使用Ingress资源公开OpenFaaS。 有关指导,请遵循如何使用Helm在DigitalOcean Kubernetes上设置Nginx入口

  • A fully registered domain name to host OpenFaaS, pointed at the Load Balancer used by the Nginx Ingress. This tutorial will use openfaas.your_domain throughout. You can purchase a domain name on Namecheap, get one for free on Freenom, or use the domain registrar of your choice.

    托管OpenFaaS的完整注册域名,指向Nginx Ingress使用的负载均衡器。 本教程将始终使用openfaas.your_domain 。 你可以购买一个域名Namecheap ,免费获得一个在Freenom ,或使用你选择的域名注册商。

Note: The domain name you use in this tutorial must differ from the one used in the “How To Set Up an Nginx Ingress on DigitalOcean Kubernetes” prerequisite tutorial.

注意:在本教程中使用的域名必须与“如何在DigitalOcean Kubernetes上设置Nginx入口”先决条件教程中使用的域名不同。

第1步-使用Helm安装OpenFaaS (Step 1 — Installing OpenFaaS using Helm)

In this step, you will install OpenFaaS to your Kubernetes cluster using Helm and expose it at your domain.

在此步骤中,您将使用Helm将OpenFaaS安装到Kubernetes集群,并将其公开到您的域。

As part of the Nginx Ingress Controller prerequisite, you created example Services and an Ingress. You won’t need them in this tutorial, so you can delete them by running the following commands:

作为Nginx Ingress Controller前提条件的一部分,您创建了示例服务和一个Ingress。 在本教程中,您将不需要它们,因此可以通过运行以下命令将其删除:

  • kubectl delete -f hello-kubernetes-first.yaml

    kubectl删除-f hello-kubernetes-first.yaml
  • kubectl delete -f hello-kubernetes-second.yaml

    kubectl删除-f hello-kubernetes-second.yaml
  • kubectl delete -f hello-kubernetes-ingress.yaml

    kubectl删除-f hello-kubernetes-ingress.yaml

Since you’ll be deploying functions as Kubernetes objects, it’s helpful to store them and OpenFaaS itself in separate namespaces in your cluster. The OpenFaaS namespace will be called openfaas, and the functions namespace will be openfaas-fn. Create them in your cluster by running the following command:

由于您将功能部署为Kubernetes对象,因此将它们和OpenFaaS本身存储在集群中单独的命名空间中会很有帮助。 OpenFaaS命名空间将被称为openfaas ,而函数命名空间将被称为openfaas-fn 。 通过运行以下命令在您的集群中创建它们:

  • kubectl apply -f https://raw.githubusercontent.com/openfaas/faas-netes/master/namespaces.yml

    kubectl适用-f https://raw.githubusercontent.com/openfaas/faas-netes/master/namespaces.yml

You’ll see the following output:

您将看到以下输出:


   
   
Output
namespace/openfaas created namespace/openfaas-fn created

Next, you’ll need to add the OpenFaaS Helm repository, which hosts the OpenFaaS chart. To do this, run the following command:

接下来,您需要添加托管OpenFaaS图表的OpenFaaS Helm存储库。 为此,请运行以下命令:

  • helm repo add openfaas https://openfaas.github.io/faas-netes/

    舵库添加openfaas https://openfaas.github.io/faas-netes/

Helm will display the following output:

Helm将显示以下输出:


   
   
Output
"openfaas" has been added to your repositories

Refresh Helm’s chart cache:

刷新Helm的图表缓存:

  • helm repo update

    头盔回购更新

You’ll see the following output:

您将看到以下输出:


   
   
Output
Hang tight while we grab the latest from your chart repositories... ...Successfully got an update from the "openfaas" chart repository ...Successfully got an update from the "jetstack" chart repository ...Successfully got an update from the "stable" chart repository Update Complete. ⎈ Happy Helming!⎈

Before installing OpenFaaS, you’ll need to customize some chart parameters. You’ll store them on your local machine, in a file named values.yaml. Create and open the file with your text editor:

在安装OpenFaaS之前,您需要自定义一些图表参数。 您会将它们存储在本地计算机上的名为values.yaml的文件中。 使用文本编辑器创建并打开文件:

  • nano values.yaml

    纳米值

Add the following lines:

添加以下行:

values.yaml
values.yaml
functionNamespace: openfaas-fn
generateBasicAuth: true

ingress:
  enabled: true
  annotations:
    kubernetes.io/ingress.class: "nginx"
  hosts:
    - host: openfaas.your_domain
      serviceName: gateway
      servicePort: 8080
      path: /

First, you specify the namespace where functions will be stored by assigning openfaas-fn to the functionNamespace variable. By setting generateBasicAuth to true, you order Helm to set up mandatory authentication when accessing the OpenFaaS web UI and to generate an admin username and password login combination for you.

首先,通过将openfaas-fn分配给functionNamespace变量来指定将存储函数的名称空间。 通过将generateBasicAuth设置为true ,您可以命令Helm在访问OpenFaaS Web UI时设置强制身份验证,并为您生成管理员用户名和密码登录组合。

Then, you enable Ingress creation and further configure it to use the Nginx Ingress Controller and serve the gateway OpenFaaS service at your domain.

然后,启用Ingress创建并将其进一步配置为使用Nginx Ingress Controller并在您的域中提供gateway OpenFaaS服务。

Remember to replace openfaas.your_domain with your desired domain from the prerequisites. When you are done, save and close the file.

请记住,从前提条件openfaas.your_domain替换为所需的域。 完成后,保存并关闭文件。

Finally, install OpenFaaS into the openfaas namespace with the customized values:

最后,使用自定义值将openfaas安装到openfaas命名空间中:

  • helm upgrade openfaas --install openfaas/openfaas --namespace openfaas -f values.yaml

    掌舵升级openfaas --install openfaas / openfaas --namespace openfaas -f values.yaml

You will see the following output:

您将看到以下输出:


   
   
Output
Release "openfaas" does not exist. Installing it now. NAME: openfaas LAST DEPLOYED: ... NAMESPACE: openfaas STATUS: deployed REVISION: 1 TEST SUITE: None NOTES: To verify that openfaas has started, run: kubectl -n openfaas get deployments -l "release=openfaas, app=openfaas" To retrieve the admin password, run: echo $(kubectl -n openfaas get secret basic-auth -o jsonpath="{.data.basic-auth-password}" | base64 --decode)

The output shows that the installation was successful. Run the following command to reveal the password for the admin account:

输出显示安装成功。 运行以下命令以显示admin帐户的密码:

  • echo $(kubectl -n openfaas get secret basic-auth -o jsonpath="{.data.basic-auth-password}" | base64 --decode) | tee openfaas-password.txt

    echo $(kubectl -n openfaas get secret basic-auth -o jsonpath =“ {。data.basic-auth-password}” | base64 --decode)| tee openfaas-password.txt

The decoded password is written to the output and to a file called openfaas-password.txt at the same time using tee. Note the output, which is your OpenFaaS password for the admin account.

解码后的密码使用tee同时写入输出和名为openfaas-password.txt的文件。 注意输出,这是您的admin帐户的OpenFaaS密码。

You can watch OpenFaaS containers become available by running the following command:

您可以通过运行以下命令来观看OpenFaaS容器变得可用:

  • kubectl -n openfaas get deployments -l "release=openfaas, app=openfaas"

    kubectl -n openfaas获取部署-l“ release = openfaas,app = openfaas”

When all listed deployments become ready, type CTRL + C to exit.

当所有列出的部署都ready ,键入CTRL + C退出。

You can now navigate to the specified domain in your web browser. Input admin as the username and the accompanying password when prompted. You’ll see the OpenFaaS web UI:

现在,您可以在Web浏览器中导航到指定的域。 出现提示时,输入admin作为用户名和随附的密码。 您将看到OpenFaaS Web UI:

You’ve successfully installed OpenFaaS and exposed its control panel at your domain. Next, you’ll secure it using free TLS certificates from Let’s Encrypt.

您已经成功安装了OpenFaaS,并在您的域中公开了它的控制面板。 接下来,您将使用来自Let's Encrypt的免费TLS证书对其进行保护。

步骤2 —为您的域启用TLS (Step 2 — Enabling TLS for Your Domain)

In this step, you’ll secure your exposed domain using Let’s Encrypt certificates, provided by cert-manager.

在此步骤中,您将使用cert-manager提供的“让我们加密”证书来保护您的公开域。

To do this, you’ll need to edit the ingress config in values.yaml. Open it for editing:

为此,您需要在values.yaml编辑入口配置。 打开它进行编辑:

  • nano values.yaml

    纳米值

Add the highlighted lines:

添加突出显示的行:

values.yaml
values.yaml
generateBasicAuth: true

ingress:
  enabled: true
  annotations:
    kubernetes.io/ingress.class: "nginx"
    cert-manager.io/cluster-issuer: letsencrypt-prod
  tls:
    - hosts:
        - openfaas.your_domain
      secretName: openfaas-crt
  hosts:
    - host: openfaas.your_domain
      serviceName: gateway
      servicePort: 8080
      path: /

The tls block defines in what Secret the certificates for your sites (listed under hosts) will store their certificates, which the letsencrypt-prod ClusterIssuer issues. Generally, the specified Secret must be different for every Ingress in your cluster.

tls块定义了您的站点(在hosts )的证书将在哪个Secret中存储它们的证书,由letsencrypt-prod ClusterIssuer颁发。 通常,对于集群中的每个Ingress,指定的Secret都必须不同。

Remember to replace openfaas.your_domain with your desired domain, then save and close the file.

请记住将openfaas.your_domain替换为所需的域,然后保存并关闭文件。

Apply the changes to your cluster by running the following command:

通过运行以下命令将更改应用于集群:

  • helm upgrade openfaas --install openfaas/openfaas --namespace openfaas -f values.yaml

    掌舵升级openfaas --install openfaas / openfaas --namespace openfaas -f values.yaml

You’ll see the following output:

您将看到以下输出:


   
   
Output
Release "openfaas" has been upgraded. Happy Helming! NAME: openfaas LAST DEPLOYED: ... NAMESPACE: openfaas STATUS: deployed REVISION: 2 TEST SUITE: None NOTES: To verify that openfaas has started, run: kubectl -n openfaas get deployments -l "release=openfaas, app=openfaas" To retrieve the admin password, run: echo $(kubectl -n openfaas get secret basic-auth -o jsonpath="{.data.basic-auth-password}" | base64 --decode)

You’ll need to wait a few minutes for the Let’s Encrypt servers to issue a certificate for your domain. In the meantime, you can track its progress by inspecting the output of the following command:

您需要等待几分钟,让我们加密服务器为您的域颁发证书。 同时,您可以通过检查以下命令的输出来跟踪其进度:

  • kubectl describe certificate openfaas-crt -n openfaas

    kubectl描述证书openfaas-crt -n openfaas

The end of the output will look similar to this:

输出的结尾将类似于以下内容:


   
   
Output
Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal GeneratedKey 24m cert-manager Generated a new private key Normal Requested 16m cert-manager Created new CertificateRequest resource "openfaas-crt-1017759607" Normal Issued 16m cert-manager Certificate issued successfully

When the last line of output reads Certificate issued successfully, you can exit by pressing CTRL + C. Refresh your domain in your browser to test. You’ll see the padlock to the left of the address bar in your browser, signifying that your connection is secure.

当输出的最后一行显示Certificate issued successfully ,可以按CTRL + C退出。 在浏览器中刷新您的域以进行测试。 您将在浏览器中地址栏的左侧看到挂锁,表示您的连接是安全的。

You’ve secured your OpenFaaS domain using free TLS certificates from Let’s Encrypt. Now you’ll use the web UI and manage functions from it.

您已使用Let's Encrypt提供的免费TLS证书保护了OpenFaaS域。 现在,您将使用Web UI并从中管理功能。

步骤3 —通过Web UI部署功能 (Step 3 — Deploying Functions via the Web UI)

In this section, you’ll explore the OpenFaaS web UI and then deploy, manage, and invoke functions from it.

在本节中,您将探索OpenFaaS Web UI,然后从中部署,管理和调用功能。

The OpenFaaS web UI has two main parts: on the left-hand side, a column where the deployed functions will be listed, and the central panel, where you’ll see detailed info about a selected function and be able to interact with it.

OpenFaaS Web UI有两个主要部分:在左侧,将列出已部署功能的列,以及在中央面板中,您将看到有关所选功能并能够与其交互的详细信息。

To deploy a new function, click the Deploy New Function button underneath the OpenFaaS logo on the upper left. You’ll see a dialog asking you to choose a function:

要部署新功能,请单击左上方OpenFaaS徽标下方的Deploy New Function按钮。 您会看到一个对话框,要求您选择一个功能:

The FROM STORE tab lists pre-made functions from the official OpenFaaS function store that you can deploy right away. Each function is shown with a short description, and you can select the link icon on the right of a function to take a look at its source code. To deploy a store function from this list, select it, and then click the DEPLOY button.

FROM STORE”选项卡列出了您可以立即部署的官方OpenFaaS功能存储库中的预制功能 。 每个功能均以简短说明显示,您可以选择功能右侧的链接图标以查看其源代码。 要从此列表部署存储功能,请选择它,然后单击DEPLOY按钮。

You can also supply your own function by switching to the CUSTOM tab:

您还可以通过切换到“ 自定义”选项卡来提供自己的功能:

Here, you’d need to specify a Docker image of your function that is configured specifically for OpenFaaS and available at a Docker registry (such as Docker Hub). In this step, you’ll deploy a pre-made function from the OpenFaaS store, then in the next steps you’ll create and deploy custom functions to Docker Hub.

在这里,您需要指定功能的Docker映像,该映像是专门为OpenFaaS配置的,可在Docker注册表(例如Docker Hub)上找到。 在这一步中,您将从OpenFaaS存储中部署一个预制函数,然后在下一步中创建自定义函数并将其部署到Docker Hub。

You’ll deploy the NodeInfo function, which returns information about the machine it’s deployed on, such as CPU architecture, number of cores, total RAM memory available, and uptime (in seconds).

您将部署NodeInfo函数,该函数返回有关其部署计算机的信息,例如CPU体系结构,内核数,可用的总RAM内存以及正常运行时间(以秒为单位)。

From the list of store functions, select NodeInfo and click DEPLOY. It will soon show up in the list of deployed functions.

从存储功能列表中,选择NodeInfo并单击DEPLOY 。 它将很快显示在已部署功能的列表中。

Select it. In the central part of the screen, you’ll see basic information about the deployed function.

选择它。 在屏幕的中央部分,您将看到有关已部署功能的基本信息。

The status of the function updates in real time, and should quickly turn to Ready. If it stays at Not Ready for longer periods of time, it’s most likely that your cluster lacks the resources to accept a new pod. You can follow How To Resize Droplets for information on how to fix this.

功能状态实时更新,应Swift变为Ready 。 如果它长时间处于“ Not Ready ”状态,则很可能是您的群集缺少资源来接受新的Pod。 您可以按照如何调整液滴大小来获取有关如何解决此问题的信息。

Once Ready, the deployed function is accessible at the shown URL. To test it, you can navigate to the URL in your browser, or call it from the Invoke function panel located beneath the function info.

一旦Ready ,就可以在显示的URL上访问已部署的功能。 要对其进行测试,可以浏览到浏览器中的URL,或者从位于函数信息下方的Invoke功能面板中调用它。

You can select between Text, JSON, and Download to indicate the type of response you expect. If you want the request to be a POST instead of GET, you can supply request data in the Request body field.

您可以在TextJSONDownload之间进行选择,以指示所需的响应类型。 如果您希望请求是POST而不是GET ,则可以在Request body字段中提供请求数据。

To call the nodeinfo function, click the INVOKE button. OpenFaaS will craft and execute a HTTP request according to the selected options and fill in the response fields with received data.

要调用nodeinfo函数,请单击INVOKE按钮。 OpenFaaS将根据选定的选项设计并执行HTTP请求,并在响应字段中填写接收到的数据。

The response status is HTTP 200 OK, which means that the request was executed successfully. The response body contains system information that the NodeInfo function collects, meaning that it’s properly accessible and working correctly.

响应状态为HTTP 200 OK ,表示请求已成功执行。 响应主体包含NodeInfo函数收集的系统信息,这意味着它可以正确访问并且可以正常工作。

To delete a function, select it from the list and click the garbage can icon in the right upper corner of the page. When prompted, click OK to confirm. The function’s status will turn to Not Ready (which means it’s being removed from the cluster) and the function will soon vanish from the UI altogether.

要删除功能,请从列表中选择它,然后单击页面右上角的垃圾桶图标。 出现提示时,单击“ 确定”进行确认。 该功能的状态将变为“ Not Ready (这意味着它已从集群中删除),并且该功能很快将完全从UI中消失。

In this step, you’ve used the OpenFaaS web UI, as well as deploy and manage functions from it. You’ll now see how you can deploy and manage OpenFaaS functions using the command line.

在此步骤中,您已使用OpenFaaS Web UI以及从中部署和管理功能。 现在,您将看到如何使用命令行来部署和管理OpenFaaS功能。

步骤4 –使用faas-cli管理功能 (Step 4 — Managing Functions Using the faas-cli)

In this section, you’ll configure the faas-cli to work with your cluster. Then, you’ll deploy and manage your existing functions through the command line.

在本部分中,您将配置faas-cli以与您的集群一起使用。 然后,您将通过命令行部署和管理现有功能。

To avoid having to specify your OpenFaaS domain every time you run the faas-cli, you’ll store it in an environment variable called OPENFAAS_URL, whose value the faas-cli will automatically pick up and use during execution.

为了避免每次运行faas-cli时都必须指定OpenFaaS域,请将其存储在名为OPENFAAS_URL的环境变量中,faas-cli的值将在执行期间自动获取并使用。

Open .bash_profile in your home directory for editing:

在您的主目录中打开.bash_profile进行编辑:

  • nano ~/.bash_profile

    纳米〜/ .bash_profile

Add the following line:

添加以下行:

~/.bash_profile
〜/ .bash_profile
. . .
export OPENFAAS_URL=https://openfaas.your_domain

Remember to replace openfaas.your_domain with your domain, then save and close the file.

请记住用您的域替换openfaas.your_domain ,然后保存并关闭文件。

To avoid having to log in again, manually evaluate the file:

为避免再次登录,请手动评估文件:

  • . ~/.bash_profile

    。 〜/ .bash_profile

Now, ensure that you have faas-cli installed on your local machine. If you haven’t yet installed it, do so by following the instructions outlined in the official docs.

现在,确保在本地计算机上安装了faas-cli。 如果尚未安装,请按照官方文档中概述的说明进行安装。

Then, set up your login credentials by running the following command:

然后,通过运行以下命令来设置登录凭据:

  • cat ~/openfaas-password.txt | faas-cli login --username admin --password-stdin

    猫〜/ openfaas-password.txt | faas-cli登录-用户名admin --password-stdin

The output will look like:

输出将如下所示:


   
   
Output
Calling the OpenFaaS server to validate the credentials... credentials saved for admin https://openfaas.your_domain

To deploy a function from the store, run the following command:

要从存储中部署功能,请运行以下命令:

  • faas store deploy function_name

    faas store部署function_name

You can try deploying nodeinfo by running:

您可以尝试通过运行以下命令来部署nodeinfo

  • faas store deploy nodeinfo

    faas store部署nodeinfo

You’ll see output like the following:

您将看到类似以下的输出:


   
   
Output
Deployed. 202 Accepted. URL: https://openfaas.your_domain/function/nodeinfo

To list deployed functions, run faas list:

要列出已部署的功能,请运行faas list

  • faas list

    收藏清单

Your existing functions will be shown:

您现有的功能将显示:


   
   
Output
Function Invocations Replicas nodeinfo 0 1

To get detailed info about a deployed function, use faas describe:

要获取有关已部署功能的详细信息,请使用faas describe

  • faas describe nodeinfo

    faas描述nodeinfo

The output will be similar to:

输出将类似于:

Name:                nodeinfo
Status:              Ready
Replicas:            1
Available replicas:  1
Invocations:         0
Image:               functions/nodeinfo-http:latest
Function process:
URL:                 https://openfaas.your_domain/function/nodeinfo
Async URL:           https://openfaas.your_domain/async-function/nodeinfo
Labels:              faas_function : nodeinfo
                     uid : 514253614
Annotations:         prometheus.io.scrape : false

You can invoke a function with faas invoke:

您可以使用faas invoke来调用函数:

  • faas invoke nodeinfo

    faas调用nodeinfo

You’ll get the following message:

您会收到以下消息:


   
   
Output
Reading from STDIN - hit (Control + D) to stop.

You can then provide a request body. If you do, the method will be POST instead of GET. When you are done with inputting data, or want the request to be GET, press CTRL + D. The faas-cli will then execute the inferred request and output the response, similarly to the web UI.

然后,您可以提供一个请求正文。 如果这样做,该方法将是POST而不是GET 。 完成数据输入后,或希望请求为GET ,请按CTRL + D 然后,faas-cli将执行推断的请求并输出响应,类似于Web UI。

To delete a function, run faas remove:

要删除功能,请运行faas remove

  • faas remove nodeinfo

    faas删除nodeinfo

You’ll get the following output:

您将获得以下输出:


   
   
Output
Deleting: nodeinfo. Removing old function.

Run faas list again to see that nodeinfo was removed:

再次运行faas list以查看nodeinfo已被删除:


   
   
Output
Function Invocations Replicas

In this step, you’ve deployed, listed, invoked, and removed functions in your cluster from the command line using the faas-cli. In the next step, you’ll create your own function and deploy it to your cluster.

在此步骤中,您已使用faas-cli从命令行在群集中部署,列出,调用和删除了功能。 在下一步中,您将创建自己的函数并将其部署到集群中。

第5步-创建和部署新功能 (Step 5 — Creating and Deploying a New Function)

Now you’ll create a sample Node.JS function using the faas-cli and deploy it to your cluster.

现在,您将使用faas-cli创建一个示例Node.JS函数,并将其部署到您的集群中。

The resulting function you’ll create will be packaged as a Docker container and published on Docker Hub. To be able to publish containers, you’ll need to log in by running the following command:

您将创建的结果函数将打包为Docker容器并发布在Docker Hub上。 为了能够发布容器,您需要通过运行以下命令登录:

  • docker login

    码头工人登录

Enter your Docker Hub username and password when prompted to finish the login process.

当提示您完成登录过程时,输入您的Docker Hub用户名和密码。

You’ll store the sample Node.JS function in a folder named sample-js-function. Create it using the following command:

您将把示例Node.JS函数存储在名为sample-js-function的文件夹中。 使用以下命令创建它:

  • mkdir sample-js-function

    mkdir sample-js-function

Navigate to it:

导航到它:

  • cd sample-js-function

    cd sample-js-function

Populate the directory with the template of a JS function by running the following command:

通过运行以下命令,使用JS函数的模板填充目录:

  • faas new sample-js --lang node

    faas new sample-js --lang节点

The output will look like this:

输出将如下所示:


   
   
Output
2020/03/24 17:06:08 No templates found in current directory. 2020/03/24 17:06:08 Attempting to expand templates from https://github.com/openfaas/templates.git 2020/03/24 17:06:10 Fetched 19 template(s) : [csharp csharp-armhf dockerfile go go-armhf java11 java11-vert -x java8 node node-arm64 node-armhf node12 php7 python python-armhf python3 python3-armhf python3-debian ru by] from https://github.com/openfaas/templates.git Folder: sample-js created. ___ _____ ____ / _ \ _ __ ___ _ __ | ___|_ _ __ _/ ___| | | | | '_ \ / _ \ '_ \| |_ / _` |/ _` \___ \ | |_| | |_) | __/ | | | _| (_| | (_| |___) | \___/| .__/ \___|_| |_|_| \__,_|\__,_|____/ |_| Function created in folder: sample-js Stack file written: sample-js.yml ...

As written in the output, the code for the function itself is in the folder sample-js, while the OpenFaaS configuration for the function is in the file sample-js.yaml. Under the sample-js directory (which resembles a regular Node.JS project) are two files, handler.js and package.json.

如输出所示,该函数本身的代码位于sample-js文件夹中,而该函数的OpenFaaS配置位于sample-js.yaml文件中。 根据sample-js目录(这类似于一个普通的Node.js项目)两个文件, handler.jspackage.json

handler.js contains actual JS code that will return a response when the function is called. The contents of the handler look like the following:

handler.js包含实际的JS代码,该代码将在调用函数时返回响应。 处理程序的内容如下所示:

sample-js-function/sample-js/handler.js
sample-js-function / sample-js / handler.js
"use strict"

module.exports = async (context, callback) => {
    return {status: "done"}
}

It exports a lambda function with two parameters, a context with request data and a callback that you can use to pass back response data, instead of just returning it.

它导出带有两个参数的lambda函数 ,一个带有请求数据的context和一个callback ,您可以使用该callback传递回响应数据,而不仅仅是返回它。

Open this file for editing:

打开此文件进行编辑:

  • nano sample-js/handler.js

    纳米样品js / handler.js

Change the highlighted line as follows:

更改突出显示的行,如下所示:

sample-js-function/sample-js/handler.js
sample-js-function / sample-js / handler.js
"use strict"

module.exports = async (context, callback) => {
    return {status: "<h1>Hello Sammy!</h1>"}
}

When you are done, save and close the file. This OpenFaaS function will, when called, write Hello Sammy! to the response.

完成后,保存并关闭文件。 调用此OpenFaaS函数时,将向您Hello Sammy! 回应。

Next, open the configuration file for editing:

接下来,打开配置文件进行编辑:

  • nano sample-js.yml

    纳米样品js.yml

It will look like the following:

它将如下所示:

sample-js-function/sample-js.yml
sample-js-function / sample-js.yml
version: 1.0
provider:
  name: openfaas
  gateway: https://openfaas.your_domain
functions:
  sample-js:
    lang: node
    handler: ./sample-js
    image: sample-js:latest

For the provider, it specifies openfaas and a default gateway. Then, it defines the sample-js function, specifies its language (node), its handler and the Docker image name, which you’ll need to modify to include your Docker Hub account username, like so:

对于provider ,它指定openfaas和默认网关。 然后,它定义sample-js函数,指定其语言( node ),其处理程序和Docker映像名称,您需要对其进行修改以包括Docker Hub帐户用户名,如下所示:

sample-js-function/sample-js.yml
sample-js-function / sample-js.yml
version: 1.0
provider:
  name: openfaas
  gateway: http://127.0.0.1:8080
functions:
  sample-js:
    lang: node
    handler: ./sample-js
    image: your_docker_hub_username/sample-js:latest

Save and close the file.

保存并关闭文件。

Then, build the Docker image, push it to Docker Hub, and deploy it on your cluster, all at the same time by running the following command:

然后,通过运行以下命令,同时构建Docker映像,将其推送到Docker Hub,并将其部署在您的集群上:

  • faas up -f sample-js.yml

    faas up -f sample-js.yml

There will be a lot of output (mainly from Docker), which will end like this:

将有很多输出(主要来自Docker),输出将像这样结束:


   
   
Output
. . . [0] < Pushing sample-js [your_docker_hub_username/sample-js:latest] done. [0] Worker done. Deploying: sample-js. Deployed. 202 Accepted. URL: https://openfaas.your_domain/function/sample-js

Invoke your newly deployed function to make sure it’s working:

调用新部署的功能以确保其正常工作:

  • faas invoke sample-js

    faas调用sample-js

Press CTRL + D. You’ll see the following output:

CTRL + D 您将看到以下输出:


   
   
Output
<h1>Hello Sammy!</h1>

This means that the function was packaged and deployed correctly.

这意味着该功能已正确打包和部署。

You can remove the function by running:

您可以通过运行以下命令删除该功能:

  • faas remove sample-js

    faas删除样本js

You have now successfully created and deployed a custom Node.JS function on your OpenFaaS instance in your cluster.

现在,您已经成功在集群中的OpenFaaS实例上创建并部署了自定义Node.JS函数。

结论 (Conclusion)

You’ve deployed OpenFaaS on your DigitalOcean Kubernetes cluster and are ready to deploy and access both pre-made and custom functions. Now, you are able to implement the Function as a Service architecture, which can increase resource utilization and bring performance improvements to your apps.

您已经在DigitalOcean Kubernetes集群上部署了OpenFaaS,并准备部署和访问预制功能和自定义功能。 现在,您可以实现“功能即服务”架构,该架构可以提高资源利用率并提高应用程序的性能。

If you’d like to learn more about advanced OpenFaaS features, such as autoscaling for your deployed functions and monitoring their performance, visit the official docs.

如果您想了解有关OpenFaaS进阶功能的更多信息,例如对已部署功能的自动缩放以及监视其性能,请访问官方文档

翻译自: https://www.digitalocean.com/community/tutorials/how-to-run-serverless-functions-using-openfaas-on-digitalocean-kubernetes

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值