Start docker swarm
$ docker swarm init --advertise-addr lo # {network}OpenFaaS is a framework for building Serveless functions with Docker
git clone https://github.com/openfaas/faasurl -sL https://cli.openfaas.com | sudo shAnd start faas by:
$ cd faas/ && ./deploy_stack.shAfter running stack, you have to log into faas
echo -n {password} | faas-cli login --username={username} --password-stdinTo create functions you need some templates, you can pull them by following commands
# PHP Template
faas-cli template pull https://github.com/itscaro/openfaas-template-php
# Other languages' templates
faas-cli template pull https://github.com/openfaas/templatesLet's start by creating our first function using PHP.
faas-cli new hello-php --lang phpAfter you create a new function, faas will create a new directory containing a class Handler.php inside src/ folder, this is our proper function.
Let's build our function
faas-cli build -f ./hello-php.ymlThis will build a docker container to execute the function. Now lets deploy our function
faas-cli deploy -f hello-php.ymlNow lets try it
curl -XPOST -d 'hello boy' http://127.0.0.1:8080/function/hello-phpIf everything is ok, you should see the hello boy printed, which is the functions being executed.
Now lets change our function:
<?php
# hello-php/src/Handler.php
namespace App;
class Handler
{
public function handle(string $data): void
{
echo json_encode(['number' => mt_rand(10000, 999999)]);
}
}And then we have to re-build it
faas-cli build -f hello-php.ymlAnd re-deploy it
faas-cli deploy -f hello-php.ymlSo, lets try again
curl -XPOST http://127.0.0.1:8080/function/hello-phpLet's start by creating our first function using Python.
faas-cli new hello-python --lang pythonAfter you create a new function, faas will create a file called handler.py inside hello-python/ folder, this is our proper function.
Let's build our function
faas-cli build -f ./hello-python.ymlThis will build a docker container to execute the function. Now lets deploy our function
faas-cli deploy -f hello-python.ymlNow lets try it
curl -XPOST http://127.0.0.1:8080/function/hello-python -d "it's me here"If everything is ok, you should see the hello boy printed, which is the functions being executed.
Now lets change our function:
import random
import json
def handle(req):
result = {"number": random.randint(1000, 9999)}
print json.dumps(result)And then we have to re-build it
faas-cli build -f hello-python.ymlAnd re-deploy it
faas-cli deploy -f hello-python.ymlSo, lets try again
curl -XPOST http://127.0.0.1:8080/function/hello-python