OpenFaaS: Getting Started on Kubernetes

OpenFaaS (Function as a Service) is a popular serverless framework that provides an easy way to create portable functions, microservices and APIs using Kubernetes and Docker. This tutorial guide will serve as your OpenFaaS introduction to get you up and running quickly.

You may also want to read: How to install using MicroK8s on Ubuntu.
YouTube player

Install/enable OpenFaaS

There are a variety of methods to install or enable OpenFaas on your Kubernetes. Use the install method that you prefer.

Enable OpenFaaS using MicroK8s

Use this command if you want to enable OpenFaaS if you are using MicroK8s:

microk8s enable openfaas

MicroK8s will automatically enable DNS, Helm 3, basic auth, and install OpenFaaS for you.

Visit MicroK8s for more information about installing and using it.

Install OpenFaaS using arkade

You can also install OpenFaaS using the following arkade command:

arkade install openfaas

You can, among others, add additional flags such as:

  • –gateways int – This sets the number of gateway (default 1)
  • –load-balancer boolean – This adds a load balancer

Visit arkade for more information about installing and using it.

Check the deployment status

The deployment process onto Kubernetes will start once you install or enable OpenFaas. Note that the OpenFaaS install deploys multiple services using the “openfaas” namespace.

The following command will show you the status of all the deployments for the “openfaas” namespace.

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

A completed deployment will look like this:

NAME                READY   UP-TO-DATE   AVAILABLE   AGE
nats                1/1     1            1           65m
alertmanager        1/1     1            1           65m
queue-worker        1/1     1            1           65m
basic-auth-plugin   1/1     1            1           65m
prometheus          1/1     1            1           65m
gateway             1/1     1            1           65m

Alternatively, you can use the following command to query the deployment status of a specific service. For example, the following command will show the gateway deployment status:

kubectl rollout status -n openfaas deploy/gateway

The result will look like this:

deployment "gateway" successfully rolled out

Port-Forward OpenFaaS

Next, let’s look at how you connect to the OpenFaaS gateway running on your Kubernetes cluster. 

You can do this by forwarding your local machine port to the OpenFaaS Kubernetes gateway using the following command:

kubectl port-forward -n openfaas svc/gateway 8080:8080 &

Note that the ampersand sign (&) runs the port-forward process in the background. You can use the following command to show the status of your background processes: 

jobs

You can now access OpenFaaS using http://localhost:8080/. The mentioned URL is known as your gateway URL. In addition, accessing the UI is done via the following URL: http://localhost:8081/ui/. This guide has information on how to log in further below.

Install the OpenFaaS CLI

Next, you must install the OpenFaaS CLI using the following command:

curl -SLsf https://cli.openfaas.com | sudo sh

You can access OpenFaaS using a web interface, but it’s best to get to know the CLI.

Set defaults

OpenFaaS allows you to set some defaults. For example, you can set the default gateway URL. This default setting prevents you from needing to add the “– gateway” parameter every time you run the Open-FaaS CLI.

Use the following command to avoid this:

export OPENFAAS_URL=http://localhost:8081

Next, the following command will tell the CLI tool your Docker Hub username. This default setting is handy when you create a base for your new function.

export OPENFAAS_PREFIX=<YOUR_DOCKER_HUB_USERNAME>

Alternatively, if you are using a remote self-hosted container registry, like AWS ECR, then set something like this:

export OPENFAAS_PREFIX=<YOUR_AWS_ACCOUNT_ID>.dkr.ecr.<YOUR_AWS_REGION>.amazonaws.com

Login to your Docker repository and OpenFaaS

Next, you need to be logged into your Docker repository to push images. A Private repository will require you to log in to push and pull images. But you also need to be logged into OpenFaaS via the gateway.

Login to your Docker repository of choice

Let’s see how to log in to your favorite Docker repository.

Login to Docker Hub

For Docker Hub, add your password to a YOUR_PASSWORD.txt file and then provide the rest of the info as required.

The Docker login command is below:

cat ~/YOUR_PASSWORD.txt | docker login --username YOUR_USERNAME --password-stdin

Login to AWS Elastic Container Registry (ECR)

For AWS Elastic Container Registry (ECR), ensure that you have installed AWS CLI v2 or newer. Then, swap the YOUR_REGION and YOUR_REPO as is needed.

aws ecr get-login-password --region <YOUR_REGION> | sudo docker login --username AWS --password-stdin YOUR_REPO_URL

As per the AWS documentation: This command retrieves and displays an authentication token using the GetAuthorizationToken API that you can use to authenticate to an Amazon ECR registry. You can pass the authorization token to the login command of the container client of your preference, such as the Docker CLI. After you have authenticated to an Amazon ECR registry with this command, you can use the client to push and pull images from that registry if your IAM principal has access to do so until the token expires. The authorization token is valid for 12 hours.

Running “aws ecr get-login-password –region YOUR_REGION” will echo your authorization token. This command is essential if you need to provide Kubernetes with your AWS ECR password to pull images.

Login to the faas-cli

You must log in to the faas-cli as this is the primary means for you to do anything in OpenFaaS.

The following command will allow you to log in to the faas-cli:

echo -n $(kubectl get secret -n openfaas basic-auth -o jsonpath="{.data.basic-auth-password}" | base64 --decode; echo) | faas-cli login --username admin --password-stdin

Login to the OpenFaaS UI

The OpenFaaS UI is optional but helpful if you don’t want to use the CLI. This OpenFaaS tutorial uses the CLI.

The following command will allow you to get the password required to access the OpenFaaS UI:

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

Finally, to open the UI using your browser and the port-forward you have configured:

http://localhost:8081/ui/

The username will be: “admin”, and the password is from the previous step.

Troubleshooting

The following command will show you the deployment status of OpenFaaS:

kubectl get deploy -o wide -n openfaas --all-namespaces

You can also use this command to get a list of all the services:

microk8s kubectl get services -o wide --all-namespaces

You can get events from multiple namespaces. For example, the “openfaas-fn” namespace contains events related to functions that you have deployed. And the “openfaas” namespace contains events related to OpenFaaS and not the functions you have deployed necessarily.

The following command will get all events raised to the “openfaas” namespace:

kubectl get events -n openfaas

Finally, the following command will get all events raised to the “openfaas-fn” namespace:

kubectl get events -n openfaas-fn

Run a basic function using the faas-cli

Now, let’s run an out-of-the-box function from the OpenFaaS store. The example below will show how you can run the NMAP function provided by OpenFaaS. NMAP is a free and open-source network scanner used to discover hosts and services on a computer.

The following command will list all the items in the OpenFaaS store:

faas-cli store list

This results in:

FUNCTION                                 DESCRIPTION
NodeInfo                                 Get info about the machine that you'r...
alpine                                   An Alpine Linux shell, set the "fproc...
env                                      Print the environment variables prese...
sleep                                    Simulate a 2s duration or pass an X-S...
shasum                                   Generate a shasum for the given input
Figlet                                   Generate ASCII logos with the figlet CLI
curl                                     Use curl for network diagnostics, pas...
SentimentAnalysis                        Python function provides a rating on ...
hey                                      HTTP load generator, ApacheBench (ab)...
nslookup                                 Query the nameserver for the IP addre...
SSL/TLS cert info                        Returns SSL/TLS certificate informati...
Colorization                             Turn black and white photos to color ...
Inception                                This is a forked version of the work ...
...

Next, you can inspect the item in the store using:

faas-cli store inspect "Nmap Security Scanner"

You can then install the store item using the following command:

faas-cli store deploy "Nmap Security Scanner"

Next, you can invoke the function using:

echo "-sP anto.online" | faas-cli invoke nmap

Finally, you can also invoke the function using CURL:

curl -sL http://localhost:8080/function/nmap -d "-sP anto.online"

Create your own function using the faas-cli

The faas-cli has a handy command to get started from predefined templates. The “lang” parameter allows you to set your preferred language. You can use the: “faas-cli new –list” command to list all the currently available languages.

Then use the following command to create a function based on an existing python3 template:

faas-cli new --lang python3 my-function

Result:

2021/10/31 00:10:12 No templates found in current directory.
2021/10/31 00:10:12 Attempting to expand templates from https://github.com/openfaas/templates.git
2021/10/31 00:10:13 Fetched 14 template(s) : [csharp dockerfile go java11 java11-vert-x node node12 node12-debian node14 php7 python python3 python3-debian ruby] from https://github.com/openfaas/templates.git
Folder: my-function created.
  ___                   _____           ____
 / _ \ _ __   ___ _ __ |  ___|_ _  __ _/ ___|
| | | | '_ \ / _ \ '_ \| |_ / _` |/ _` \___ \
| |_| | |_) |  __/ | | |  _| (_| | (_| |___) |
 \___/| .__/ \___|_| |_|_|  \__,_|\__,_|____/
      |_|


Function created in folder: my-function
Stack file written: my-function.yml

Notes:
You have created a Python3 function using the Classic Watchdog.

To include third-party dependencies create a requirements.txt file.

For high-throughput applications, we recommend using the python3-flask
or python3-http templates.

This command will then create a few files in the folder in which you ran the command. See below:

.
├── my-function
│   ├── handler.py
│   ├── __init__.py
│   └── requirements.txt
├── my-function.yml
└── template

You will see a:

  • YAML file that contains deployment and build info about your function.
  • “my-function” folder that contains your function’s handler.
  • Requirements.txt file that is used to set up the python pip modules that you need.
  • Template folder that is always named “template” and cannot be moved.

Now let’s make our function return “hello world!” To do this, edit the handler.py file and change it to the following:

def handle(req):
    """handle a request to the function
    Args:
        req (str): request body
    """

    return "Hello World!"

Equally important is the my-function.yml file. The YAML below will instruct the push command to push the image to the public Docker Hub repository called “anto-online/my-function” and tag it as “latest.” Finally, the gateway parameter will tell the deploy command which gateway to use.

version: 1.0
provider:
  name: openfaas
  gateway: http://localhost:8080
functions:
  my-function:
    lang: python3
    handler: ./my-function
    image: your-repo-username/my-function:latest

This file may need to change depending on the type of repository you use. See more information below.

For the public Docker Hub Repository

OpenFaaS will, by default, push and pull from your public repository at Docker Hub. Of course, the push command will require you to log in to the Docker Hub. You can see an example of the login process for Docker Hub further up in the guide.

For a private Docker Repository

First, set up some environment variables for OpenFaaS:

export DOCKER_USERNAME=<YOUR_DOCKER_USERNAME>
export DOCKER_PASSWORD=<YOUR_DOCKER_PASSWORD>
export DOCKER_EMAIL=<YOUR_DOCKER_EMAIL>
For AWS Elastic Container Service (ECR), you can use “AWS” as the username.

If your private repo is not Docker Hub, then also export the following variable:

export DOCKER_SERVER=<YOUR_DOCKER_SERVER>
For AWS Elastic Container Service (ECR), you can use “YOUR_AWS_ACCOUNT_ID>.dkr.ecr.<YOUR_AWS_REGION>.amazonaws.com” as the server address. Note that you must swap the details as needed for your account.

Next, we need to create a Kubernetes secret using the following command:

kubectl create secret docker-registry my-private-repo-secret --docker-username=$DOCKER_USERNAME --docker-password=$DOCKER_PASSWORD --docker-email=$DOCKER_EMAIL --namespace openfaas-fn

If your private repo is not Docker Hub, then also export the following argument “–docker-server=$DOCKER_SERVER” to the command:

kubectl create secret docker-registry my-private-repo-secret --docker-server=$DOCKER_SERVER --docker-username=$DOCKER_USERNAME --docker-password=$DOCKER_PASSWORD --docker-email=$DOCKER_EMAIL --namespace openfaas-fn

Finally, add the “secrets” parameter to the “my-function.yml” file mentioned above.

version: 1.0
provider:
  name: openfaas
  gateway: http://localhost:8080
functions:
  my-function:
    lang: python3
    handler: ./my-function
    image: your-repo-username/my-function:latest
    secrets:
    - my-private-repo-secret

Build your function

Next, we need to build the function using the following command:

faas-cli build -f my-function.yml

Push your function to the Docker repository

Next, we can push our image into the Docker Repo. Before doing this, make sure you are logged in to the repo. Also, make sure your my-function.yml file image location is valid in the repo.

faas-cli push -f my-function.yml

Deploy your function to Kubernetes

Next, let’s deploy the function onto Kubernetes:

faas-cli deploy -f ./my-function.yml

Run your function

There are many ways to run your function. This OpenFaas tutorial will show you how to invoke the function via the command line using the faas-cli or CURL.

You can run your function using CURL:

curl -sL http://localhost:8081/function/my-function -d "Hello!"
Note that the -d value passes in the argument for your function, which is read via the STDIN.

Additionally, you can invoke the function using:

echo "Hello!" | faas-cli invoke my-function

Remove your function

You can remove your function using the command below:

faas-cli rm -f my-function.yml

Remove a secret

Earlier in this OpenFaaS tutorial, you saw how to add a secret to Kubernetes. You can also remove the secret if you need to use the following command:

kubectl delete -n openfaas-fn secret <MY-SECRET-NAME>

Build, Push and Deploy your function

Finally, you can use the “up” command instead of the faas-cli to build, push and deploy. This OpenFaaS tutorial used individual steps to demonstrate the process. However, the “up” command is much shorter and does the same thing.

See the command below:

faas-cli up -f my-function.yml

Wrapping up this OpenFaaS tutorial

This introduction tutorial has shown you how to install and use OpenFaaS. Which functions do you plan to use?

You may also be interested in

Sources:

About Anto Online

Anto, a seasoned technologist with over two decades of experience, has traversed the tech landscape from Desktop Support Engineer to enterprise application consultant, specializing in AWS serverless technologies. He guides clients in leveraging serverless solutions while passionately exploring cutting-edge cloud concepts beyond his daily work. Anto's dedication to continuous learning, experimentation, and collaboration makes him a true inspiration, igniting others' interest in the transformative power of cloud computing.

View all posts by Anto Online

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.