Serverless “Hello World” with Fn Framework

Introduction

The hype about serverless applications has been growing lately and AWS is the leader at the moment, however there are other alternative such as Fn Project supported by Oracle or OpenWhisk supported by IBM.

I found out about Fn Project during Democratizing Serverless Talk at London QCon 2018 and couldn’t wait to try this platform, since you can run your own serverless architecture on your own laptop.

Features

Fn Project Architecture
Fn Project Architecture

Requirements

  1. Docker 17.06 or later version.
  2. Docker Hub account
  3. Log into your Docker Hub account (docker login).
  4. Install Fn CLI tool.
    • MacOS:
brew install fn
curl -LSs https://raw.githubusercontent.com/fnproject/cli/master/install | sh
  1. MacOS, Wi_n_dows and Linux: download latest bin file for your OS.

Getting Started

  1. Start up Fn server.

Make sure Docker is up and running.

fn start

Now a docker container (fnproject/fnserver) is running on our machine.

  1. Make use of Fn CLI tool to create a project with the language of your choice.
fn init --runtime go --timeout 10 --idle-timeout 10 hello-serverless

Golang has been my choice for this hello world serverless application since it is a lightweight and easy to use programming language.

–timeout -> for how long the code is going to be running

–idle-timeout 10 -> time container is going to wait for another call

When running fn init a Dockerfile is generated by Fn:

FROM fnproject/go:dev as build-stage
WORKDIR /function
RUN go get -u github.com/golang/dep/cmd/dep
ADD . /go/src/func/
RUN cd /go/src/func/ && dep ensure
RUN cd /go/src/func/ && go build -o func
FROM fnproject/go
WORKDIR /function
COPY --from=build-stage /go/src/func/func /function/
ENTRYPOINT ["./func"]

After running the init command all the boilerplate has been created:

func.go -> Go application func.yaml -> Fn configuration file test.json -> test file for the application Gopkg.toml -> file for Goland dependency management.

  1. Run application
fn run

First time you run this command will take longer.

{"message":"Hello World"}
  1. Deploy the function to the local Fn server to add the application to the Fn list.
fn deploy --app myapp --local

The local flag is to avoid pushing the image to your Docker Hub. In case you want to use the Docker repository, first you have to set the Docker Hub username: export FN_REGISTRY=DOCKER_HUB_USERNAME

Now you can open your browser and go to http://localhost:8080/r/myapp/hello-serverless

Useful commands

fn apps list #shows applications registered on your Fn server
fn routes list myapp #shows application endpoints
fn apps delete myapp #deletes application