Create new functions

    • faas-cli build - build an image into the local Docker library
    • faas-cli push - push that image to a remote container registry
    • faas-cli deploy - deploy your function into a cluster

    The faas-cli up command automates all of the above in a single command.

    The OpenFaaS CLI has a template engine built-in which can create new functions in a given programming language. The way this works is by reading a list of templates from the ./template location in your current working folder.

    Before creating a new function make sure you pull in the official OpenFaaS language templates from GitHub via the .

    This page shows how to generate functions in the most popular languages and explains how you can manage their dependencies too.

    The Classic Templates are held in the openfaas/templates repository and are based upon the Classic Watchdog which uses STDIO to communicate with your function. The of-watchdog uses HTTP to communicate with functions and most of its templates are available in the organisation on GitHub and in the store.

    How to pick:

    • Use the Classic Watchdog if you're starting out or following tutorials or guides
    • Use the of-watchdog if you need more performance or if you need full control of the HTTP response

    See also: watchdog design

    Template store

    You can browse templates from the official store or create your own store and add your own templates there.

    To see what templates are available type faas-cli template store list and you should see the following in the terminal:

    1. $ faas-cli template store list
    2.  
    3. NAME SOURCE DESCRIPTION
    4. csharp openfaas Official C# template
    5. dockerfile openfaas Official Dockerfile template
    6. go-armhf openfaas Official Golang armhf
    7. ...
    8. node10-express-armhf openfaas-incubator NodeJS 10 Express armhf template
    9. node10-express openfaas-incubator NodeJS 10 Express template
    10. ruby-http openfaas-incubator Ruby 2.4 HTTP template
    11. golang-middleware openfaas-incubator Golang Middleware template
    12. csharp-httprequest distantcam C# HTTP template
    13. ...

    Choose a template and retrieve it locally with the command:

    1. $ faas-cli template store pull node10-express

    Once downloaded, your chosen template and any others stored in the same repository will be available to use:

    1. $ faas-cli new --list
    2. Languages available as templates:
    3. - node10-express
    4. - node10-express-arm64

    You can add your own store just by specifying the —url flag for both commands to pull and list your custom templates store.

    The classic templates are held in the repository.

    Go templates

    There are several Golang templates available, which are listed below.

    All templates are available via faas-cli template store list/pull

    Go golang-http - (of-watchdog template)

    Read the README for golang-http, this template has a similar-style of API to AWS Lambda.

    Golang modules are supported via —build-arg using GO111MODULE=1 or GO111MODULE=auto

    Go golang-middleware - (of-watchdog template)

    , this template is ideal for full control over the HTTP request and response and corresponds to a HTTP middleware in Go.

    1. func Handle(w http.ResponseWriter, r *http.Request) {
    2. }

    Golang modules are supported via —build-arg using GO111MODULE=1 or GO111MODULE=auto

    Go go - (classic template)

    To create a new function named go-fn in Go type in the following:

    1. $ faas-cli new go-fn --lang go

    You will now see two files generate:

    1. go-fn.yml
    2. ./go-fn/
    3. ./go-fn/handler.go

    You can now edit handler.go and use the faas-cli to build and deploy your function.

    Go go - dependencies

    Dependencies should be managed with a Go vendoring tool such as dep.

    1. $ go get -u github.com/golang/dep/cmd/dep
    • Initialise the dependencies
    1. $ $GOPATH/bin/dep init
    • Now vendor a library Make sure you're in the go-fn folder, now use and the name of the library you want. In this example we are vendoring the github.com/cnf/structhash package for use in our function.
    1. $ dep ensure -add github.com/cnf/structhash
    • Reference the package from function You can now edit your function and add an import statement in handler.go to github.com/cnf/structhash.
    Go go - with CGO

    First you will need to add the dev build option:

    1. build_options:
    2. - dev

    This installs gcc, make, git and some other related packages for the build portion of the function's Dockerfile.

    You can then enable CGO with a build-arg:

    1. faas-cli build --build-arg CGO_ENABLED=1

    Python 3 (classic template)

    To create a Python function named pycon type in:

    1. $ faas-cli new pycon --lang python3

    You'll see:

    Python: dependencies

    You should edit pycon/requirements.txt and add any pip modules you want with each one on a new line, for instance requests.

    The primary Python template uses Alpine Linux as a runtime environment due to its minimal size, but if you need a Debian environment so that you can compile numpy or other modules then read on to the next section.

    Python: advanced dependencies

    If you need to use pip modules that require compilation then you should try the python3-debian template then add your pip modules to the requirements.txt file.

    1. $ faas-cli template pull https://github.com/openfaas-incubator/python3-debian
    2. $ faas-cli new numpy-function --lang python3-debian
    3. $ echo "numpy" > ./numpy-function/requirements.txt
    4. $ faas-build -f ./numpy-function.yml
    5. ...
    6.  
    7. Step 11/17 : RUN pip install -r requirements.txt
    8. ---> Running in d0ff430a607e
    9. Collecting numpy (from -r requirements.txt (line 1))
    10. Downloading https://files.pythonhosted.org/packages/6e/dc/92c0f670e7b986829fc92c4c0208edb9d72908149da38ecda50d816ea057/numpy-1.14.2-cp36-cp36m-manylinux1_x86_64.whl (12.2MB)
    11. Installing collected packages: numpy
    12. Successfully installed numpy-1.14.2
    13.  
    14. ...

    Node.js 12 node12 (of-watchdog template)

    There are three Node.js templates which use the newer of-watchdog:

    NameStyleRuntimeVersionasync/awaitSupported by nodejs.org
    node8-expressFunctionNodeJS8.xnono
    node10-expressFunctionNodeJS10.xnono
    node10-express-serviceMicro-serviceNodeJS10.xnono
    node12FunctionNodeJS12.xyesyes, LTS version

    It is recommended that all new users opt for the node12-express template.

    For more details on the event and context objects, see the for the node10-express template, this also applies to node12.

    Node.js 12 node12 - async/await
    1. "use strict"
    2.  
    3. module.exports = async (event, context) => {
    4. const result = {
    5. status: "Received input: " + JSON.stringify(event.body),
    6. };
    7. return result
    8. }
    Node.js 12 node12 - async/await with error
    1. "use strict"
    2.  
    3. module.exports = async (event, context) => {
    4. throw new Error("there was an error created in the function")
    5. }
    Node.js 12 node12 - without async/await
    1. "use strict"
    2.  
    3. module.exports = (event, context) => {
    4. let err;
    5. const result = {
    6. status: "Received input: " + JSON.stringify(event.body),
    7. };
    8.  
    9. context.succeed(result).
    10. status(201);
    11. }

    Node.js (classic template)

    Generate a function named js-fn:

    1. $ faas-cli new js-fn --lang node

    You'll see:

    1. ./js-fn.yml
    2. ./js-fn/
    3. ./js-fn/package.json
    Node.js dependencies

    Node.js dependencies are managed with npm and the package.json file which was generated for you.

    To add the cheerio module type in:

    1. cd js-fn
    2. npm i --save cheerio

    You can now add a require('cheerio') statement into your function and make use of this library.

    CSharp / .NET Core 2.1

    You can create functions in .NET Core 2.1 using C# / CSharp.

    • Write a function named csharp-function
    1. faas-cli new --lang csharp csharp-function

    Now you can open your current folder in a tool such as Visual Studio Code and add dependencies using the project (csproj) file.

    Ruby

    Create a function called ruby-function:

    1. $ faas-cli new --lang ruby ruby-function

    The directory structure is:

    1. ├── ruby-function
    2. ├── Gemfile
    3. └── handler.rb
    4. ├── ruby-function.yml

    Your code should be in the handler.rb file

    Ruby: Adding a Gem (Library)

    Open the Gemfile in the ruby-function directory

    Add the following line

    1. gem 'httparty'
    Ruby: Using our own Gem

    Replace your handler.rb code with the following

    1. require 'httparty'
    2.  
    3. class Handler
    4. def run(req)
    5. return HTTParty.get("http://api.stackexchange.com/2.2/questions?site=stackoverflow&tagged=#{req}")
    6. end
    7. end
    Ruby: Building / Deploy / Run

    Edit the ruby-function.yml and point your image to your dockerhub, for example${your_user}/ruby-function

    Now you can invoke the function:

    1. $ echo 'OpenFaaS' | faas-cli invoke ruby-function
    2. {
    3. "quota_remaining" : 298,
    4. "quota_max" : 300,
    5. "has_more" : false,
    6. "items" : [
    7. {
    8. "title" : "Scaling with GPU usage",
    9. "creation_date" : 1536315498,
    10. "answer_count" : 0,
    11. "view_count" : 10,
    12. "is_answered" : false,
    13. ...

    Java (of-watchdog)

    Two Java templates are provided and java12, if you need a different version, then please fork the templates repo or request it from the community.

    Support is made available for external code repositories via the build.gradle file where you specify dependencies to fetch from repositories or JAR files to be added via the build.

    • Write a function java-function:
    1. $ faas-cli new --lang java8 java-function
    • Write your code in: ./src/main/Handler.java

    • Write junit tests in: ./src/tests/

    • Update gradle config if needed in: ./build.gradle./settings.gradle

    • Working with headers You can use getHeader(k) on the Request interface to query a header.

    To set a header such as content-type you can use setHeader(k, v) on the Response interface.

    PHP7

    1. $ faas-cli new my-function --lang php7

    You'll see:

    1. my-function.yml
    2. my-function/src/Handler.php
    3. my-function/composer.json
    4. my-function/php-extension.sh

    Add any dependencies/extensions as described below and implement your functions business logic in Handler.php.

    PHP7 - Composer Dependencies

    You should edit composer.json and add any required package dependencies, referring to the Composer Documentation for instructions on using composer.json.

    PHP7 - Private Composer Repositories

    Refer to the for instructions on how to use Composers COMPOSER_AUTH environment variable to configure access to dependencies in private repositories.

    PHP7 - PHP Extensions

    The PHP7 template is based upon the and provides the php-extension.sh script which exposes the ability to customise extensions installed in a function image.

    Refer to the PHP7 Template Documentation for instructions on customising installed extensions.

    Customise a template

    It is recommended that you use the official templates as they are provided and if there is a short-coming that you raise a GitHub issue so we can improve the templates for everyone.

    All templates are driven by a Dockerfile and can be customised by editing the files found in the ./template folder.

    Update the Dockerfile

    There are several reasons why you may want to update your Dockerfile, just edit ./template/<language_name>/Dockerfile.

    • New base image - some companies prefer to use their own base images for Docker images for compliance, support or licensing reasons

    • Add native package - sometimes you may want to add a native package from the Alpine Linux repository or the Debian package repository - just add a step into the Dockerfile

    • Try a new version of a base-image - it may be that the project is showing support for Node.js LTS, but you want the cutting-edge version, you can do that too

    Update a template's configuration

    The name of a template is read from a "template.yml" file kept within the template folder: ./template/<language_name>/template.yml

    For csharp we have the following:

    1. language: csharp
    2. fprocess: dotnet ./root.dll
    • language is the display name used for faas-cli new —list.
    • fprocess provides the process to run for each invocation - i.e. your function
    Use your own templates

    You can use your own Git repository for a custom or forked set of templates. This can be public or private.

    See faas-cli template pull for more information.

    If you want to set up your own default template location, specify the OPENFAAS_TEMPLATE_URL environmental variable the following way:

    1. export OPENFAAS_TEMPLATE_URL=https://raw.githubusercontent.com/user/mytemplate/customtemplates
    Download templates from the template store

    Check what templates are available in the template store with the CLI by typing:

    1. faas-cli template store list

    Pull the desired template by specifying NAME attribute only:

    1. faas-cli template store pull go

    or pull the template by mixing the REPOSITORY and NAME attributes the following way:

    1. faas-cli template store pull openfaas/go

    To get more information on specific store use the describe verb like:

    1. faas-cli template store describe openfaas/go

    or if there is no collision between names use only the name field:

    1. faas-cli template store describe go

    If you have your own store with templates, you can set that as your default official store by setting the environmental variable OPENFAAS_TEMPLATE_STORE_URL the following way:

    1. export OPENFAAS_TEMPLATE_STORE_URL=https://raw.githubusercontent.com/user/openfaas-templates/templates.json

    Now the source of the store is changed to the URL you have specified above.

    Templates for ARM and Raspberry Pi are provided on a best-effort basis. If you can help with maintenance please let the project contributors know.

    • ARMv7 / Raspberry Pi Type in faas-cli new —list and look for any languages ending in -armhf. You can use any of these for your functions.

    • ARM64 / Packet.net / Scaleway ARM 64-bit For these platforms do the same as above and look for the suffix.