Menu

Your first serverless Python function with OpenFaaS

Let's write a Python function with OpenFaaS that executes hello-world and then move onto something more. We'll start by deploying OpenFaaS on our machine and then we'll install the CLI and write the handler for our function.

Step 1 - Install OpenFaaS

If you already have FaaS and the CLI configured, skip to step 3.

If you head over to Github you will find full instructions on how to launch FaaS on Docker Swarm or Kubernetes. For this post we'll use with Swarm, but the instructions are effectively the same once FaaS is deployed.

$ git clone https://github.com/alexellis/faas

Initialize Swarm mode on your Docker daemon.

$ docker swarm init

If you have more than one Ethernet adapter, Swarm may ask you to select one via the --advertise-addr parameter.

You now have a single-node Docker cluster. That's all we need - so now we can deploy the FaaS stack and sample functions:

You can try out the functions in the UI, for instance The function named func_hubstats will tell you how many Docker Hub images a user has. I typed in my user account and found out I have almost 200 already!

Step 2 - Install the CLI

The CLI is a convenient way to interact with your functions. You can use it to build and/or deploy functions to your cluster.

On a Mac if you're using brew then you can type in:

$ brew install faas-cli

On Linux (or Mac without brew available) type in:

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

If you're using Windows, then you're not out of luck, you can actually find the Windows executable on the FaaS releases page.

Step 3 - Write your function

Create a new folder for your work:

$ mkdir -p ~/functions/hello-python
$ cd ~/functions

Now create hello-python/handler.py:

def handle(req):
print("Hello! You said: " + req)

handler.py

All your functions should be specified in a YAML file like this - it tells the CLI what to build and deploy onto your OpenFaaS cluster.

If you are using a remote server or a multi-node cluster then you can push your function's image to a registry or the Docker Hub. You'll also need to image the image: name to include your Hub account such as image: alexellis2/faas-hello-python.

Prometheus is also baked into the FaaS stack, which means you can checkout the various metrics on how your functions are being used as well as how long they're taking to run. You can view the Prometheus UI at http://localhost:9090

Troubleshooting

If you run into any errors such as Can't reach service check the following:

If it's a multi-node cluster, you have to push your images to the Docker Hub or similar registry before deploying

If you're still getting the error docker service logs --no-trunc=true hello-python will give a bit more info.

If the above didn't help then Docker Swarm has a known issue around re-creating Swarm services, you can work around it by running the deploy command a second time.