Create Serverless Functions With OpenFaaS
Create Serverless Functions With OpenFaaS
In this article, we discuss how to create serverless functions with OpenFaaS.
Join the DZone community and get the full member experience.Join For Free
OpenFaaS is serverless functions framework that runs on top of Docker and Kubernetes. In this tutorial, you'll learn how to:
- Deploy OpenFaaS to a Kubernetes cluster
- Set up the OpenFaaS CLI
- Create, build, and deploy serverless functions using the CLI
- Invoke serverless functions using the CLI
- Update an existing serverless function
- Deploy serverless functions using the web interface
- Monitor your serverless functions with Prometheus and Grafana
- A Kubernetes cluster. If you don't have a running Kubernetes cluster, follow the instructions from the Set Up a Kubernetes Cluster with Kind section below.
- A Docker Hub Account. See the Docker Hub page for details about creating a new account.
- kubectl. Refer the Install and Set Up kubectl page for details about installing
- Node.js 10 or higher. To check if Node.js is installed on your computer, type the following command:
The following example output shows that Node.js is installed on your computer:
If Node.js is not installed or you're running an older version, you can download the installer from the Downloads page.
- This tutorial assumes basic familiarity with Docker and Kubernetes.
Set Up a Kubernetes Cluster With Kind (Optional)
With Kind, you can run a local Kubernetes cluster using Docker containers as nodes. The steps in this section are optional. Follow them only if you don't have a running Kubernetes cluster.
- Create a file named
openfaas-cluster.yaml, and copy in the following spec:
2. Use the
kind create cluster command to create a Kubernetes cluster with one control plane and two worker nodes:
Deploy OpenFaaS to a Kubernetes Cluster
You can install OpenFaaS using Helm, plain YAML files, or its own installer named
arkade which provides a quick and easy way to get OpenFaaS running. In this section, you'll deploy OpenFaaS with
- Enter the following command to install
2. Now, install
3. To verify that the deployments were created, run the
kubectl get deployments command. Specify the namespace and the selector using the
-l parameters as follows:
If the deployments are not yet ready, you should see something similar to the following example output:
Once the installation is finished, the output should look like this:
4. Check the rollout status of the
The following example output shows that the
gateway deployment has been successfully rolled out:
Note that the ampersand sign (
&) runs the process in the background. You can use the
jobs command to show the status of your background processes:
Set Up the OpenFaaS CLI
OpenFaaS provides a command-line utility you can use to build and deploy your serverless functions. You can install it by following the steps from the Installation page.
Create a Serverless Function Using the CLI
Now that OpenFaaS and the
faas-cli command-line utility are installed, you can create and deploy serverless functions using the built-in template engine. OpenFaaS provides two types of templates:
- The Classic templates are based on the Classic Watchdog and use
stdioto communicate with your serverless function. Refer to the Watchdog page for more details about how OpenFaaS Watchdog works.
- The of-watchdog templates use HTTP to communicate with your serverless function. These templates are available through the OpenFaaS Incubator GitHub repository.
In this tutorial, you'll use a classic template.
- Run the following command to see the templates available in the official store:
☞ Note that you can specify an alternative store for templates. The following example command lists the templates from a repository named
2. Download the official templates locally:
☞ By default, the above command downloads the templates from the OpenFaaS official GitHub repository. If you want to use a custom repository, then you should specify the URL of your repository. The following example command pulls the templates from a repository named
- To create a new serverless function, run the
faas-cli newcommand specifying:
- The name of your new function (
langparameter followed by the programming language template (
At this point, your directory structure should look like the following:
Things to note:
appfleet-hello-world/handler.jsfile contains the code of your serverless function. You can use the
echocommand to list the contents of this file:
- You can specify the dependencies required by your serverless function in the
package.jsonfile. The automatically generated file is just an empty shell:
- The spec of the
appfleet-hello-worldfunction is stored in the
Build Your Serverless Function
- Open the
appfleet-hello-world.ymlfile in a plain-text editor, and update the
imagefield by prepending your Docker Hub user name to it. The following example prepends my username (
andrepopescu12) to the image field:
Once you've made this change, the
appfleet-hello-world.yml file should look similar to the following:
2. Build the function. Enter the
faas-cli build command specifying the
-f argument with the name of the YAML file you edited in the previous step (
3. You can list your Docker images with:
Push Your Image to Docker Hub
- Log in to Docker Hub. Run the
docker logincommand with the
--usernameflag followed by your Docker Hub user name. The following example command logs you in as
Next, you will be prompted to enter your Docker Hub password:
2. Use the
faas-cli push command to push your serverless function to Docker Hub:
Deploy Your Function Using the CLI
- With your serverless function pushed to Docker Hub, log in to your local instance of the OpenFaaS gateway by entering the following command:
2. Run the
faas-cli deploy command to deploy your serverless function:
☞ OpenFaaS provides an auto-scaling mechanism based on the number of requests per second, which is read from Prometheus. For the sake of simplicity, we won't cover auto-scaling in this tutorial. To further your knowledge, you can refer the Auto-scaling page.
- Use the
faas-cli listcommand to list the functions deployed to your local OpenFaaS gateway:
☞ Note that you can also list the functions deployed to a different gateway by providing the URL of the gateway as follows:
4. You can use the
faas-cli describe method to retrieve more details about the
Invoke Your Serverless Function Using the CLI
- To see your serverless function in action, issue the
faas-cli invokecommand, specifying:
-fflag with the name of the YAML file that describes your function (
- The name of your function (
CTRL+D. The following example output shows that your serverless function works as expected:
Update Your Function
The function you created, deployed, and then invoked in the previous sections is just an empty shell. In this section, we'll update it to:
- Read the name of a city from
- Fetch the weather forecast from the openweathermap.org
- Print to the console the weather forecast
- Create an OpenWeatherMap account by following the instructions from the Sign Up page.
- Log in to OpenWeatherMap and then select API KEYS:
- From here, you can either copy the value of the default key or create a new API key, and then copy its value:
- Now that you have an OpenWeatherMap API key, you must use
npmto install a few dependencies. The following command moves into the
appfleet-hello-worlddirectory and then installs the
5. Replace the content of the
handler.js file with:
☞ To try this function, replace
<YOUR-OPENWEATHERMAP-API-KEY> with your OpenWeatherMap API KEY.
- You can use the
faas-cli removecommand to remove the function you've deployed earlier in this tutorial:
7. Now that the old function has been removed, you must rebuild, push, and deploy your modified function. Instead of issuing three separate commands, you can use the
openfaas-cli up command as in the following example:
☞ Note that you can skip the push or the deploy steps:
- The following example command skips the push step:
- The following example command skips the deploy step:
8. To verify that the updated serverless function works as expected, invoke it as follows:
9. To clean-up, run the
faas-cli remove command with the name of your serverless function (
appfleet-hello-world as an argument):
Deploy Serverless Functions Using the Web Interface
OpenFaaS provides a web-based user interface. In this section, you'll learn how you can use it to deploy a serverless function.
- First, you must use the
echocommand to retrieve your password:
2. Open a browser and visit http://localhost:8080. To log in, use the
admin username and the password you retrieved in the previous step. You will be redirected to the OpenFaaS home page. Select the DEPLOY NEW FUNCTION button.
- A new window will be displayed. Select the Custom tab, and then type:
docker.io/andreipopescu12/appfleet-hello-worldin the Docker Image input box
appfleet-hello-worldin the Function name input box.
- Once you've filled in the Docker image and Function name input boxes, select the DEPLOY button:
- Your new function will be visible in the left navigation bar. Click on it:
You'll be redirected to the invoke function page:
- In the Request body input box, type in the name of the city you want to retrieve the weather forecast for, and then select the INVOKE button:
If everything works well, the weather forecast will be displayed in the Response Body field:
Monitor Your Serverless Functions with Prometheus and Grafana
The OpenFaaS gateway exposes the following metrics:
In this section, you will learn how to set up Prometheus and Grafana to track the health of your serverless functions.
- Use the following command to list your deployments:
2. To expose the
prometheus deployment, create a service object named
--type=NodePort flag exposes the
prometheus-ui service on each of the node's IP addresses. Also, a
ClusterIP service is created. You'll use this to connect to the
prometheus-ui service from outside of the cluster.
3. To inspect the
prometheus-ui service, enter the following command:
4. Forward all requests made to http://localhost:9090 to the pod running the
5. Now, you can point your browser to http://localhost:9090, and you should see a page similar to the following screenshot:
- To deploy Grafana, you'll the
stefanprodan/faas-grafana:4.6.3image. Run the following command:
7. Now, you can list your deployments with:
8. Use the following
kubectl expose deployment command to create a service object that exposes the
9. Retrieve details about your new service with:
10. Forward all requests made to http://localhost:3030 to the pod running the
11. Now that you set up the port forwarding, you can access Grafana by pointing your browser to http://localhost:3000:
- Log into Grafana using the username
admin. The Home Dashboard page will be displayed:
- From the left menu, select Dashboards --> Import:
https://grafana.com/grafana/dashboards/3434in the Grafana.com Dashboard input box. Then, select the Load button:
- In the Import Dashboard dialog box, set the Prometheus data source to
faas, and then select Import:
An empty dashboard will be displayed:
- Now, you can invoke your function a couple of times using the
faas-cli invokecommand as follows:
16. Switch back to the browser window that opened Grafana. Your dashboard should be automatically updated and look similar to the following screenshot:
We hope this tutorial was useful for learning the basics of deploying serverless functions with OpenFaaS. For more great tutorials about Docker and Kubernetes, we recommend you visit our blog.
Thanks for reading!
Published at DZone with permission of Sudip Sengupta . See the original article here.
Opinions expressed by DZone contributors are their own.